_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
|
---|---|---|---|---|---|---|---|---|
2480d759429beb8232f16d227f51d6e0b762d03d8aad1b0c2ed757006717159f | xsc/base64-clj | core.clj | (ns ^{ :doc "Base64 Encoding/Decoding in Clojure."
:author "Yannick Scherer" }
base64-clj.core
(:use base64-clj.alphabet
base64-clj.utils)
(:import java.nio.ByteBuffer))
(set! *unchecked-math* true)
(set! *warn-on-reflection* true)
# # Encoding
;;
# # # Write Helpers
(defmacro write-base64
"Write the given three octets to the given ByteBuffer, converting
them to four Base64-encoded sextets first. If o2 or o1 is `nil`
padding bytes will be written. If o1 is `nil`, o2 is automatically
assumed to be `nil`, too."
[b o0 o1 o2]
(let [v (gensym "v")]
`(let [~v (int
(bit-or
(<< (->int ~o0) 16)
~(if o1 `(<< (->int ~o1) 8) 0)
~(if o2 `(->int ~o2) 0)))]
(doto ~b
(.put (int->base64-byte (get-sextet ~v 0)))
(.put (int->base64-byte (get-sextet ~v 1)))
(.put ~(if o1 `(int->base64-byte (get-sextet ~v 2)) `BASE64_PAD))
(.put ~(if (and o1 o2) `(int->base64-byte (get-sextet ~v 3)) `BASE64_PAD))))))
(defmacro write-octets
"Write `n` octets of the given byte array to the given ByteBuffer, converting
them to four Base64-encoded sextets (possibly padding bytes) first."
[buffer data idx n]
`(condp == ~n
1 (write-base64 ~buffer (get-byte-at ~data ~idx 0) nil nil)
2 (write-base64 ~buffer (get-byte-at ~data ~idx 0) (get-byte-at ~data ~idx 1) nil)
3 (write-base64 ~buffer (get-byte-at ~data ~idx 0) (get-byte-at ~data ~idx 1) (get-byte-at ~data ~idx 2))))
# # # Encoder
(defn encode-bytes
"Encode the given Byte Array to its Base64 Representation."
^"[B"
[^"[B" data]
(let [len (int (count data))
cap (int (encode-result-size len))
b (ByteBuffer/allocate cap)]
(loop [i (int 0)]
(if (< i len)
(let [next-i (+ i (int 3))
n (if (<= next-i len) (int 3) (unchecked-remainder-int (unchecked-subtract-int len i) (int 3)))]
(write-octets b data i n)
(recur next-i))
(.array b)))))
(defn encode
"Encode the given String to its UTF-8 Base64 Representation."
([^String s] (encode s "UTF-8"))
([^String s ^String encoding]
(let [data (encode-bytes (.getBytes s encoding))]
(String. data "UTF-8"))))
;; ## Decoding
;;
# # # Read Helpers
(defmacro read-base64
"Read the given four sextets into the given ByteBuffer by converting them
to three octets first."
[b s0 s1 s2 s3]
`(let [v# (int (bit-or (<< ~s0 18) (<< ~s1 12) (<< (or ~s2 0) 6) (or ~s3 (int 0))))]
(.put ~b (get-octet v# 0))
(when ~s2
(.put ~b (get-octet v# 1))
(when ~s3
(.put ~b (get-octet v# 2))))))
(defmacro read-sextets
"Read the four sextets at the given index in the given byte array into
the given ByteBuffer."
[buffer data idx]
`(let [s0# (get-byte-at ~data ~idx 0)
s1# (get-byte-at ~data ~idx 1)
s2# (get-byte-at ~data ~idx 2)
s3# (get-byte-at ~data ~idx 3)]
(read-base64 ~buffer
(base64-byte->int s0#)
(base64-byte->int s1#)
(when-not (== s2# BASE64_PAD)
(base64-byte->int s2#))
(when-not (or (== s2# BASE64_PAD) (== s3# BASE64_PAD))
(base64-byte->int s3#)))))
# # # Decoder
(defn decode-bytes
"Decode the given Base64 Byte Array."
^"[B"
[^"[B" data]
(let [len (int (count data))]
(when-not (zero? (unchecked-remainder-int len (int 4)))
(throw (IllegalArgumentException. "Expects a byte array whose length is dividable by 4.")))
(let [cap (let [x (aget data (unchecked-dec-int len))
y (aget data (unchecked-subtract-int len (int 2)))
s (decode-result-size len)]
(cond (== y BASE64_PAD) (unchecked-subtract-int s (int 2))
(== x BASE64_PAD) (unchecked-subtract-int s (int 1))
:else s))
b (ByteBuffer/allocate (int cap))]
(loop [i (int 0)]
(if (< i len)
(let [next-i (unchecked-add-int i (int 4))]
(when (<= next-i len)
(read-sextets b data i))
(recur next-i))
(.array b))))))
(defn decode
"Decode the given Base64-encoded String to its String Representation."
([^String s] (decode s "UTF-8"))
([^String s ^String encoding]
(let [data (decode-bytes (.getBytes s "UTf-8"))]
(String. data encoding))))
| null | https://raw.githubusercontent.com/xsc/base64-clj/56a016526cb5ea9e2aed9fd89bc703a5a83c3547/src/base64_clj/core.clj | clojure |
## Decoding
| (ns ^{ :doc "Base64 Encoding/Decoding in Clojure."
:author "Yannick Scherer" }
base64-clj.core
(:use base64-clj.alphabet
base64-clj.utils)
(:import java.nio.ByteBuffer))
(set! *unchecked-math* true)
(set! *warn-on-reflection* true)
# # Encoding
# # # Write Helpers
(defmacro write-base64
"Write the given three octets to the given ByteBuffer, converting
them to four Base64-encoded sextets first. If o2 or o1 is `nil`
padding bytes will be written. If o1 is `nil`, o2 is automatically
assumed to be `nil`, too."
[b o0 o1 o2]
(let [v (gensym "v")]
`(let [~v (int
(bit-or
(<< (->int ~o0) 16)
~(if o1 `(<< (->int ~o1) 8) 0)
~(if o2 `(->int ~o2) 0)))]
(doto ~b
(.put (int->base64-byte (get-sextet ~v 0)))
(.put (int->base64-byte (get-sextet ~v 1)))
(.put ~(if o1 `(int->base64-byte (get-sextet ~v 2)) `BASE64_PAD))
(.put ~(if (and o1 o2) `(int->base64-byte (get-sextet ~v 3)) `BASE64_PAD))))))
(defmacro write-octets
"Write `n` octets of the given byte array to the given ByteBuffer, converting
them to four Base64-encoded sextets (possibly padding bytes) first."
[buffer data idx n]
`(condp == ~n
1 (write-base64 ~buffer (get-byte-at ~data ~idx 0) nil nil)
2 (write-base64 ~buffer (get-byte-at ~data ~idx 0) (get-byte-at ~data ~idx 1) nil)
3 (write-base64 ~buffer (get-byte-at ~data ~idx 0) (get-byte-at ~data ~idx 1) (get-byte-at ~data ~idx 2))))
# # # Encoder
(defn encode-bytes
"Encode the given Byte Array to its Base64 Representation."
^"[B"
[^"[B" data]
(let [len (int (count data))
cap (int (encode-result-size len))
b (ByteBuffer/allocate cap)]
(loop [i (int 0)]
(if (< i len)
(let [next-i (+ i (int 3))
n (if (<= next-i len) (int 3) (unchecked-remainder-int (unchecked-subtract-int len i) (int 3)))]
(write-octets b data i n)
(recur next-i))
(.array b)))))
(defn encode
"Encode the given String to its UTF-8 Base64 Representation."
([^String s] (encode s "UTF-8"))
([^String s ^String encoding]
(let [data (encode-bytes (.getBytes s encoding))]
(String. data "UTF-8"))))
# # # Read Helpers
(defmacro read-base64
"Read the given four sextets into the given ByteBuffer by converting them
to three octets first."
[b s0 s1 s2 s3]
`(let [v# (int (bit-or (<< ~s0 18) (<< ~s1 12) (<< (or ~s2 0) 6) (or ~s3 (int 0))))]
(.put ~b (get-octet v# 0))
(when ~s2
(.put ~b (get-octet v# 1))
(when ~s3
(.put ~b (get-octet v# 2))))))
(defmacro read-sextets
"Read the four sextets at the given index in the given byte array into
the given ByteBuffer."
[buffer data idx]
`(let [s0# (get-byte-at ~data ~idx 0)
s1# (get-byte-at ~data ~idx 1)
s2# (get-byte-at ~data ~idx 2)
s3# (get-byte-at ~data ~idx 3)]
(read-base64 ~buffer
(base64-byte->int s0#)
(base64-byte->int s1#)
(when-not (== s2# BASE64_PAD)
(base64-byte->int s2#))
(when-not (or (== s2# BASE64_PAD) (== s3# BASE64_PAD))
(base64-byte->int s3#)))))
# # # Decoder
(defn decode-bytes
"Decode the given Base64 Byte Array."
^"[B"
[^"[B" data]
(let [len (int (count data))]
(when-not (zero? (unchecked-remainder-int len (int 4)))
(throw (IllegalArgumentException. "Expects a byte array whose length is dividable by 4.")))
(let [cap (let [x (aget data (unchecked-dec-int len))
y (aget data (unchecked-subtract-int len (int 2)))
s (decode-result-size len)]
(cond (== y BASE64_PAD) (unchecked-subtract-int s (int 2))
(== x BASE64_PAD) (unchecked-subtract-int s (int 1))
:else s))
b (ByteBuffer/allocate (int cap))]
(loop [i (int 0)]
(if (< i len)
(let [next-i (unchecked-add-int i (int 4))]
(when (<= next-i len)
(read-sextets b data i))
(recur next-i))
(.array b))))))
(defn decode
"Decode the given Base64-encoded String to its String Representation."
([^String s] (decode s "UTF-8"))
([^String s ^String encoding]
(let [data (decode-bytes (.getBytes s "UTf-8"))]
(String. data encoding))))
|
7a798b0343d4dade88f7db47d56994a6ea3cb5005a1cfad99aea21e3d7ba5420 | static-analysis-engineering/codehawk | jCHArrayInstantiation.ml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Arnaud Venet
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
chlib
open CHAtlas
open CHCollections
open CHIterator
open CHLanguage
open CHNonRelationalDomainValues
open CHNumerical
open CHPretty
open CHStack
open CHSymbolicSets
open CHSymbolicSetsDomainNoArrays
open CHSymbolicTypeRefinement
open CHUtils
(* jchlib *)
open JCHBasicTypes
module F = CHOnlineCodeSet.LanguageFactory
let dummy_sym = new symbol_t "_"
type type_attribute_t =
| UNKNOWN_TYPE_ATTRIBUTE
| NUM_ARRAY_TYPE_ATTRIBUTE
let isNumType (t: string) =
match t with
| "int"
| "short"
| "char"
| "byte"
| "bool"
| "long"
| "float"
| "double"
| "Int2Bool"
| "ByteBool" -> true
| _ -> false
let isInvokeOperation (o: operation_t) =
match o.op_name#getBaseName with
| "OpInvokeStatic"
| "OpInvokeSpecial"
| "OpInvokeInterface"
| "OpInvokeVirtual" -> true
| _ -> false
let isFieldOperation (o: operation_t) =
match o.op_name#getBaseName with
| "OpGetField"
| "OpPutField"
| "OpPutStatic"
| "OpGetStatic" -> true
| _ -> false
let isScalarOpNewArray (o: operation_t) =
let s = o.op_name in
match (s#getBaseName, s#getAttributes) with
| ("OpNewArray", _ :: t :: _) when isNumType t -> true
| _ -> false
let isScalarOpArrayLoadOperation (o: operation_t) =
let s = o.op_name in
match (s#getBaseName, s#getAttributes) with
| ("OpArrayLoad", t :: _) when isNumType t -> true
| _ -> false
let isScalarOpArrayStoreOperation (o: operation_t) =
let s = o.op_name in
match (s#getBaseName, s#getAttributes) with
| ("OpArrayStore", t :: _) when isNumType t -> true
| _ -> false
let isArraycopyOperation (o: operation_t) =
let s = o.op_name in
s#getBaseName = "OpInvokeStatic"
&& match s#getAttributes with
| "java.lang.System" :: "arraycopy" :: _ -> true
| _ -> false
let getOpNewArrayArgs (o: operation_t) =
try
let (_, r, _) = List.find (fun (s, _, _) -> s = "ref") o.op_args in
let (_, l, _) = List.find (fun (s, _, _) -> s = "length") o.op_args in
(r, l)
with _ ->
raise (JCH_failure
(STR "Array instantiation: malformed operation OpNewArray"))
let getOpArrayLength (o: operation_t) =
try
let (_, r, _) = List.find (fun (s, _, _) -> s = "ref") o.op_args in
let (_, v, _) = List.find (fun (s, _, _) -> s = "val") o.op_args in
(r, v)
with _ ->
raise (JCH_failure
(STR "Array instantiation: malformed operation OpArrayLength"))
let getOpArrayAccessArgs (o: operation_t) =
try
let (_, a, _) = List.find (fun (s, _, _) -> s = "array") o.op_args in
let (_, i, _) = List.find (fun (s, _, _) -> s = "index") o.op_args in
let (_, v, _) = List.find (fun (s, _, _) -> s = "val") o.op_args in
(a, i, v)
with _ ->
raise (JCH_failure
(STR "Array instantiation: malformed array access operation"))
let getSystemArraycopyArgs (o: operation_t) =
try
let (_, src, _) = List.find (fun (s, _, _) -> s = "arg0") o.op_args in
let (_, src_o, _) = List.find (fun (s, _, _) -> s = "arg1") o.op_args in
let (_, tgt, _) = List.find (fun (s, _, _) -> s = "arg2") o.op_args in
let (_, tgt_o, _) = List.find (fun (s, _, _) -> s = "arg3") o.op_args in
let (_, n, _) = List.find (fun (s, _, _) -> s = "arg4") o.op_args in
(src, src_o, tgt, tgt_o, n)
with _ ->
raise (JCH_failure
(STR "Array instantiation: call to System.arraycopy has incorrect signature"))
class array_type_refinement_t (proc: procedure_int) =
let length_field = new symbol_t "length" in
let elements_field = new symbol_t "elements" in
let array_type =
STRUCT_TYPE [(length_field, NUM_VAR_TYPE); (elements_field, NUM_ARRAY_TYPE)] in
object (self: _)
inherit [type_attribute_t] symbolic_type_refinement_t
val new_array_sym = new symbol_t "OpNewArray"
val array_load_sym = new symbol_t "OpArrayLoad"
val array_store_sym = new symbol_t "OpArrayStore"
val array_length_sym = new symbol_t "OpArrayLength"
val arraycopy_sym = new symbol_t "System.Arraycopy"
method mergeAttributes a b =
match (a, b) with
| (UNKNOWN_TYPE_ATTRIBUTE, _) -> UNKNOWN_TYPE_ATTRIBUTE
| (_, UNKNOWN_TYPE_ATTRIBUTE) -> UNKNOWN_TYPE_ATTRIBUTE
| _ -> NUM_ARRAY_TYPE_ATTRIBUTE
method abstract v = self#set v UNKNOWN_TYPE_ATTRIBUTE
method analyzeOperation (o: operation_t) =
if isScalarOpNewArray o then
let (r, _) = getOpNewArrayArgs o in
self#set r NUM_ARRAY_TYPE_ATTRIBUTE
else if (isInvokeOperation o && not(isArraycopyOperation o)) || isFieldOperation o then
List.iter (fun (_, v, _) ->
if v#isSymbolic then
self#abstract v
else
()
) o.op_args
else
()
method refineSymbolicType a =
match a with
| NUM_ARRAY_TYPE_ATTRIBUTE -> array_type
| UNKNOWN_TYPE_ATTRIBUTE -> SYM_VAR_TYPE
method op_semantics
~(invariant: atlas_t)
~(stable: bool) ~(fwd_direction: bool)
~(context: symbol_t stack_t)
~(operation: operation_t) =
if isScalarOpNewArray operation then
let (r, _) = getOpNewArrayArgs operation in
let inv' = invariant#analyzeFwd (ASSIGN_SYM (r, SYM operation.op_name)) in
inv'
else
invariant
method getArrayRefs (v: variable_t) (invariant: atlas_t) =
match ((invariant#getDomain "symbolic sets")#getNonRelationalValue v)#getValue with
| SYM_SET_VAL sym_set ->
begin
match sym_set#getSymbols with
| SET refs -> List.map (fun s -> new variable_t s array_type) refs#toList
| _ -> []
end
| _ ->
[]
method transformer
~(invariant: atlas_t)
~(context: symbol_t stack_t)
~(cmd: (code_int, cfg_int) command_t) =
match cmd with
| OPERATION operation ->
begin
if isScalarOpNewArray operation then
let (r, l) = getOpNewArrayArgs operation in
begin
match self#get r with
| Some NUM_ARRAY_TYPE_ATTRIBUTE ->
let scope = proc#getScope in
let array_variable = new variable_t operation.op_name array_type in
let _ = scope#addVariable array_variable in
let _ = scope#startTransaction in
let start_i = scope#requestNumTmpVariable in
let len = scope#requestNumTmpVariable in
let value = scope#requestNumTmpVariable in
let _ = scope#endTransaction in
TRANSACTION
(new_array_sym,
F.mkCode [ASSIGN_NUM (array_variable#field length_field, NUM_VAR l);
ASSIGN_NUM (start_i, NUM numerical_zero);
ASSIGN_NUM (len, NUM_VAR l);
ASSIGN_NUM (value, NUM numerical_zero);
SET_ARRAY_ELTS (array_variable#field elements_field, start_i, len, value)
],
None)
| _ -> cmd
end
else if isScalarOpArrayLoadOperation operation then
let (a, i, v) = getOpArrayAccessArgs operation in
begin
match self#get a with
| Some NUM_ARRAY_TYPE_ATTRIBUTE ->
let array_refs = self#getArrayRefs a invariant in
begin
match array_refs with
| [] -> ABSTRACT_VARS [v]
| _ ->
begin
match List.map (fun r -> F.mkCode [READ_NUM_ELT (v, r#field elements_field, i)]) array_refs with
| [c] -> CODE (array_load_sym, c)
| _ as l -> BRANCH l
end
end
| _ -> cmd
end
else if isScalarOpArrayStoreOperation operation then
let (a, i, v) = getOpArrayAccessArgs operation in
begin
match self#get a with
| Some NUM_ARRAY_TYPE_ATTRIBUTE ->
let array_refs = self#getArrayRefs a invariant in
begin
match array_refs with
| [] -> SKIP
| _ ->
begin
match List.map (fun r -> F.mkCode [ASSIGN_NUM_ELT (r#field elements_field, i, v)]) array_refs with
| [c] -> CODE (array_store_sym, c)
| _ as l -> BRANCH l
end
end
| _ -> cmd
end
else if operation.op_name#getBaseName = "OpArrayLength" then
let (a, v) = getOpArrayLength operation in
begin
match self#get a with
| Some NUM_ARRAY_TYPE_ATTRIBUTE ->
let array_refs = self#getArrayRefs a invariant in
begin
match array_refs with
| [] -> ABSTRACT_VARS [v]
| _ ->
begin
match List.map (fun r -> F.mkCode [ASSIGN_NUM (v, NUM_VAR (r#field length_field))]) array_refs with
| [c] -> CODE (array_length_sym, c)
| _ as l -> BRANCH l
end
end
| _ -> cmd
end
else if isArraycopyOperation operation then
let (src, src_o, tgt, tgt_o, n) = getSystemArraycopyArgs operation in
match (self#get src, self#get tgt) with
| (Some NUM_ARRAY_TYPE_ATTRIBUTE, Some NUM_ARRAY_TYPE_ATTRIBUTE) ->
let src_refs = self#getArrayRefs src invariant in
let tgt_refs = self#getArrayRefs tgt invariant in
let code = List.fold_left (fun a src_r ->
List.fold_left (fun a' tgt_r ->
BLIT_ARRAYS (tgt_r#field elements_field, tgt_o, src_r#field elements_field, src_o, n) :: a'
) a tgt_refs
) [] src_refs
in
CODE (arraycopy_sym, F.mkCode code)
| _ ->
cmd
else
cmd
end
| ASSIGN_SYM (x, SYM_VAR y) ->
begin
match self#get x with
| Some NUM_ARRAY_TYPE_ATTRIBUTE -> SKIP
| _ -> cmd
end
| _ -> cmd
end
class array_instantiator_t (code_set: system_int) =
object (self: _)
method transform_procedure (proc: procedure_int) =
let refinement = new array_type_refinement_t proc in
let _ = refinement#analyzeProcedure proc in
let strategy = {widening = (fun _ -> (true, "")); narrowing = (fun _ -> true)} in
let iterator =
new iterator_t
~do_loop_counters:false
~strategy:strategy
~op_semantics:refinement#op_semantics code_set
~cmd_processor:refinement#transformer in
let init = new atlas_t [("symbolic sets", new symbolic_sets_domain_no_arrays_t)] in
let _ =
iterator#runFwd
~domains:["symbolic sets"]
~atlas:init (CODE (dummy_sym, proc#getBody)) in
()
end
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchlib/jCHArrayInstantiation.ml | ocaml | jchlib | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Arnaud Venet
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
chlib
open CHAtlas
open CHCollections
open CHIterator
open CHLanguage
open CHNonRelationalDomainValues
open CHNumerical
open CHPretty
open CHStack
open CHSymbolicSets
open CHSymbolicSetsDomainNoArrays
open CHSymbolicTypeRefinement
open CHUtils
open JCHBasicTypes
module F = CHOnlineCodeSet.LanguageFactory
let dummy_sym = new symbol_t "_"
type type_attribute_t =
| UNKNOWN_TYPE_ATTRIBUTE
| NUM_ARRAY_TYPE_ATTRIBUTE
let isNumType (t: string) =
match t with
| "int"
| "short"
| "char"
| "byte"
| "bool"
| "long"
| "float"
| "double"
| "Int2Bool"
| "ByteBool" -> true
| _ -> false
let isInvokeOperation (o: operation_t) =
match o.op_name#getBaseName with
| "OpInvokeStatic"
| "OpInvokeSpecial"
| "OpInvokeInterface"
| "OpInvokeVirtual" -> true
| _ -> false
let isFieldOperation (o: operation_t) =
match o.op_name#getBaseName with
| "OpGetField"
| "OpPutField"
| "OpPutStatic"
| "OpGetStatic" -> true
| _ -> false
let isScalarOpNewArray (o: operation_t) =
let s = o.op_name in
match (s#getBaseName, s#getAttributes) with
| ("OpNewArray", _ :: t :: _) when isNumType t -> true
| _ -> false
let isScalarOpArrayLoadOperation (o: operation_t) =
let s = o.op_name in
match (s#getBaseName, s#getAttributes) with
| ("OpArrayLoad", t :: _) when isNumType t -> true
| _ -> false
let isScalarOpArrayStoreOperation (o: operation_t) =
let s = o.op_name in
match (s#getBaseName, s#getAttributes) with
| ("OpArrayStore", t :: _) when isNumType t -> true
| _ -> false
let isArraycopyOperation (o: operation_t) =
let s = o.op_name in
s#getBaseName = "OpInvokeStatic"
&& match s#getAttributes with
| "java.lang.System" :: "arraycopy" :: _ -> true
| _ -> false
let getOpNewArrayArgs (o: operation_t) =
try
let (_, r, _) = List.find (fun (s, _, _) -> s = "ref") o.op_args in
let (_, l, _) = List.find (fun (s, _, _) -> s = "length") o.op_args in
(r, l)
with _ ->
raise (JCH_failure
(STR "Array instantiation: malformed operation OpNewArray"))
let getOpArrayLength (o: operation_t) =
try
let (_, r, _) = List.find (fun (s, _, _) -> s = "ref") o.op_args in
let (_, v, _) = List.find (fun (s, _, _) -> s = "val") o.op_args in
(r, v)
with _ ->
raise (JCH_failure
(STR "Array instantiation: malformed operation OpArrayLength"))
let getOpArrayAccessArgs (o: operation_t) =
try
let (_, a, _) = List.find (fun (s, _, _) -> s = "array") o.op_args in
let (_, i, _) = List.find (fun (s, _, _) -> s = "index") o.op_args in
let (_, v, _) = List.find (fun (s, _, _) -> s = "val") o.op_args in
(a, i, v)
with _ ->
raise (JCH_failure
(STR "Array instantiation: malformed array access operation"))
let getSystemArraycopyArgs (o: operation_t) =
try
let (_, src, _) = List.find (fun (s, _, _) -> s = "arg0") o.op_args in
let (_, src_o, _) = List.find (fun (s, _, _) -> s = "arg1") o.op_args in
let (_, tgt, _) = List.find (fun (s, _, _) -> s = "arg2") o.op_args in
let (_, tgt_o, _) = List.find (fun (s, _, _) -> s = "arg3") o.op_args in
let (_, n, _) = List.find (fun (s, _, _) -> s = "arg4") o.op_args in
(src, src_o, tgt, tgt_o, n)
with _ ->
raise (JCH_failure
(STR "Array instantiation: call to System.arraycopy has incorrect signature"))
class array_type_refinement_t (proc: procedure_int) =
let length_field = new symbol_t "length" in
let elements_field = new symbol_t "elements" in
let array_type =
STRUCT_TYPE [(length_field, NUM_VAR_TYPE); (elements_field, NUM_ARRAY_TYPE)] in
object (self: _)
inherit [type_attribute_t] symbolic_type_refinement_t
val new_array_sym = new symbol_t "OpNewArray"
val array_load_sym = new symbol_t "OpArrayLoad"
val array_store_sym = new symbol_t "OpArrayStore"
val array_length_sym = new symbol_t "OpArrayLength"
val arraycopy_sym = new symbol_t "System.Arraycopy"
method mergeAttributes a b =
match (a, b) with
| (UNKNOWN_TYPE_ATTRIBUTE, _) -> UNKNOWN_TYPE_ATTRIBUTE
| (_, UNKNOWN_TYPE_ATTRIBUTE) -> UNKNOWN_TYPE_ATTRIBUTE
| _ -> NUM_ARRAY_TYPE_ATTRIBUTE
method abstract v = self#set v UNKNOWN_TYPE_ATTRIBUTE
method analyzeOperation (o: operation_t) =
if isScalarOpNewArray o then
let (r, _) = getOpNewArrayArgs o in
self#set r NUM_ARRAY_TYPE_ATTRIBUTE
else if (isInvokeOperation o && not(isArraycopyOperation o)) || isFieldOperation o then
List.iter (fun (_, v, _) ->
if v#isSymbolic then
self#abstract v
else
()
) o.op_args
else
()
method refineSymbolicType a =
match a with
| NUM_ARRAY_TYPE_ATTRIBUTE -> array_type
| UNKNOWN_TYPE_ATTRIBUTE -> SYM_VAR_TYPE
method op_semantics
~(invariant: atlas_t)
~(stable: bool) ~(fwd_direction: bool)
~(context: symbol_t stack_t)
~(operation: operation_t) =
if isScalarOpNewArray operation then
let (r, _) = getOpNewArrayArgs operation in
let inv' = invariant#analyzeFwd (ASSIGN_SYM (r, SYM operation.op_name)) in
inv'
else
invariant
method getArrayRefs (v: variable_t) (invariant: atlas_t) =
match ((invariant#getDomain "symbolic sets")#getNonRelationalValue v)#getValue with
| SYM_SET_VAL sym_set ->
begin
match sym_set#getSymbols with
| SET refs -> List.map (fun s -> new variable_t s array_type) refs#toList
| _ -> []
end
| _ ->
[]
method transformer
~(invariant: atlas_t)
~(context: symbol_t stack_t)
~(cmd: (code_int, cfg_int) command_t) =
match cmd with
| OPERATION operation ->
begin
if isScalarOpNewArray operation then
let (r, l) = getOpNewArrayArgs operation in
begin
match self#get r with
| Some NUM_ARRAY_TYPE_ATTRIBUTE ->
let scope = proc#getScope in
let array_variable = new variable_t operation.op_name array_type in
let _ = scope#addVariable array_variable in
let _ = scope#startTransaction in
let start_i = scope#requestNumTmpVariable in
let len = scope#requestNumTmpVariable in
let value = scope#requestNumTmpVariable in
let _ = scope#endTransaction in
TRANSACTION
(new_array_sym,
F.mkCode [ASSIGN_NUM (array_variable#field length_field, NUM_VAR l);
ASSIGN_NUM (start_i, NUM numerical_zero);
ASSIGN_NUM (len, NUM_VAR l);
ASSIGN_NUM (value, NUM numerical_zero);
SET_ARRAY_ELTS (array_variable#field elements_field, start_i, len, value)
],
None)
| _ -> cmd
end
else if isScalarOpArrayLoadOperation operation then
let (a, i, v) = getOpArrayAccessArgs operation in
begin
match self#get a with
| Some NUM_ARRAY_TYPE_ATTRIBUTE ->
let array_refs = self#getArrayRefs a invariant in
begin
match array_refs with
| [] -> ABSTRACT_VARS [v]
| _ ->
begin
match List.map (fun r -> F.mkCode [READ_NUM_ELT (v, r#field elements_field, i)]) array_refs with
| [c] -> CODE (array_load_sym, c)
| _ as l -> BRANCH l
end
end
| _ -> cmd
end
else if isScalarOpArrayStoreOperation operation then
let (a, i, v) = getOpArrayAccessArgs operation in
begin
match self#get a with
| Some NUM_ARRAY_TYPE_ATTRIBUTE ->
let array_refs = self#getArrayRefs a invariant in
begin
match array_refs with
| [] -> SKIP
| _ ->
begin
match List.map (fun r -> F.mkCode [ASSIGN_NUM_ELT (r#field elements_field, i, v)]) array_refs with
| [c] -> CODE (array_store_sym, c)
| _ as l -> BRANCH l
end
end
| _ -> cmd
end
else if operation.op_name#getBaseName = "OpArrayLength" then
let (a, v) = getOpArrayLength operation in
begin
match self#get a with
| Some NUM_ARRAY_TYPE_ATTRIBUTE ->
let array_refs = self#getArrayRefs a invariant in
begin
match array_refs with
| [] -> ABSTRACT_VARS [v]
| _ ->
begin
match List.map (fun r -> F.mkCode [ASSIGN_NUM (v, NUM_VAR (r#field length_field))]) array_refs with
| [c] -> CODE (array_length_sym, c)
| _ as l -> BRANCH l
end
end
| _ -> cmd
end
else if isArraycopyOperation operation then
let (src, src_o, tgt, tgt_o, n) = getSystemArraycopyArgs operation in
match (self#get src, self#get tgt) with
| (Some NUM_ARRAY_TYPE_ATTRIBUTE, Some NUM_ARRAY_TYPE_ATTRIBUTE) ->
let src_refs = self#getArrayRefs src invariant in
let tgt_refs = self#getArrayRefs tgt invariant in
let code = List.fold_left (fun a src_r ->
List.fold_left (fun a' tgt_r ->
BLIT_ARRAYS (tgt_r#field elements_field, tgt_o, src_r#field elements_field, src_o, n) :: a'
) a tgt_refs
) [] src_refs
in
CODE (arraycopy_sym, F.mkCode code)
| _ ->
cmd
else
cmd
end
| ASSIGN_SYM (x, SYM_VAR y) ->
begin
match self#get x with
| Some NUM_ARRAY_TYPE_ATTRIBUTE -> SKIP
| _ -> cmd
end
| _ -> cmd
end
class array_instantiator_t (code_set: system_int) =
object (self: _)
method transform_procedure (proc: procedure_int) =
let refinement = new array_type_refinement_t proc in
let _ = refinement#analyzeProcedure proc in
let strategy = {widening = (fun _ -> (true, "")); narrowing = (fun _ -> true)} in
let iterator =
new iterator_t
~do_loop_counters:false
~strategy:strategy
~op_semantics:refinement#op_semantics code_set
~cmd_processor:refinement#transformer in
let init = new atlas_t [("symbolic sets", new symbolic_sets_domain_no_arrays_t)] in
let _ =
iterator#runFwd
~domains:["symbolic sets"]
~atlas:init (CODE (dummy_sym, proc#getBody)) in
()
end
|
2c29d97b8fbc77745869ad22537f30c9ac7b0b90505b45b44e9982a5f65f54df | Mathieu-Desrochers/Schemings | http-server-intern.scm | (import srfi-1)
(import (chicken condition))
(declare (unit http-server-intern))
(declare (uses exceptions))
(declare (uses fastcgi))
(declare (uses json))
(declare (uses regex))
(declare (uses validation))
;; invokes a procedure with compiled http binding regexes
(: with-compiled-http-binding-regexes
(forall (r) (
(list-of (struct http-binding)) ((list-of (struct regex)) -> r) -> r)))
(define (with-compiled-http-binding-regexes http-bindings procedure)
(with-guaranteed-release
(lambda ()
(map
(lambda (http-binding)
(regex-compile (http-binding-route-regex http-binding)))
http-bindings))
(lambda (http-binding-regexes)
(procedure http-binding-regexes))
(lambda (http-binding-regexes)
(for-each
(lambda (http-binding-regex)
(regex-free http-binding-regex))
http-binding-regexes))))
;; searches for a http binding matching a request
(: find-http-binding-match (
(list-of (struct http-binding)) (list-of (struct regex)) string string ->
(or (pair (struct http-binding) (list-of string)) false)))
(define (find-http-binding-match http-bindings http-binding-regexes method uri)
(letrec* ((find-http-binding-match-iter
(lambda (zipped)
(if (not (null? zipped))
(let* ((http-binding (caar zipped))
(http-binding-method (http-binding-method http-binding))
(http-binding-regex (cadar zipped)))
(if (equal? http-binding-method method)
(let ((regex-captures
(regex-execute-compiled
http-binding-regex
uri)))
(if (not (null? regex-captures))
(cons http-binding regex-captures)
(find-http-binding-match-iter (cdr zipped))))
(find-http-binding-match-iter (cdr zipped))))
#f))))
(find-http-binding-match-iter
(zip http-bindings http-binding-regexes))))
;; invokes a procedure with validation errors exception handling
(: http-with-validation-errors-exception-handling
(forall (r) ((-> r) ((list-of symbol) -> *) -> r)))
(define (http-with-validation-errors-exception-handling procedure exception-procedure)
(handle-exceptions
exception
(if (validation-errors-exception? exception)
(let ((validation-errors (validation-errors-exception-validation-errors exception)))
(exception-procedure validation-errors))
(abort exception))
(procedure)))
;; formats a list of validation errors
(: http-format-validation-errors ((list-of symbol) -> string))
(define (http-format-validation-errors validation-errors)
(with-json-array
(lambda (json-node)
(for-each
(lambda (validation-error)
(json-array-add-value json-node (symbol->string validation-error)))
validation-errors)
(json->string json-node))))
| null | https://raw.githubusercontent.com/Mathieu-Desrochers/Schemings/3df7c8f8589a1c9c4135a3ae4c1bab3244e6444c/sources/units/http-server-intern.scm | scheme | invokes a procedure with compiled http binding regexes
searches for a http binding matching a request
invokes a procedure with validation errors exception handling
formats a list of validation errors | (import srfi-1)
(import (chicken condition))
(declare (unit http-server-intern))
(declare (uses exceptions))
(declare (uses fastcgi))
(declare (uses json))
(declare (uses regex))
(declare (uses validation))
(: with-compiled-http-binding-regexes
(forall (r) (
(list-of (struct http-binding)) ((list-of (struct regex)) -> r) -> r)))
(define (with-compiled-http-binding-regexes http-bindings procedure)
(with-guaranteed-release
(lambda ()
(map
(lambda (http-binding)
(regex-compile (http-binding-route-regex http-binding)))
http-bindings))
(lambda (http-binding-regexes)
(procedure http-binding-regexes))
(lambda (http-binding-regexes)
(for-each
(lambda (http-binding-regex)
(regex-free http-binding-regex))
http-binding-regexes))))
(: find-http-binding-match (
(list-of (struct http-binding)) (list-of (struct regex)) string string ->
(or (pair (struct http-binding) (list-of string)) false)))
(define (find-http-binding-match http-bindings http-binding-regexes method uri)
(letrec* ((find-http-binding-match-iter
(lambda (zipped)
(if (not (null? zipped))
(let* ((http-binding (caar zipped))
(http-binding-method (http-binding-method http-binding))
(http-binding-regex (cadar zipped)))
(if (equal? http-binding-method method)
(let ((regex-captures
(regex-execute-compiled
http-binding-regex
uri)))
(if (not (null? regex-captures))
(cons http-binding regex-captures)
(find-http-binding-match-iter (cdr zipped))))
(find-http-binding-match-iter (cdr zipped))))
#f))))
(find-http-binding-match-iter
(zip http-bindings http-binding-regexes))))
(: http-with-validation-errors-exception-handling
(forall (r) ((-> r) ((list-of symbol) -> *) -> r)))
(define (http-with-validation-errors-exception-handling procedure exception-procedure)
(handle-exceptions
exception
(if (validation-errors-exception? exception)
(let ((validation-errors (validation-errors-exception-validation-errors exception)))
(exception-procedure validation-errors))
(abort exception))
(procedure)))
(: http-format-validation-errors ((list-of symbol) -> string))
(define (http-format-validation-errors validation-errors)
(with-json-array
(lambda (json-node)
(for-each
(lambda (validation-error)
(json-array-add-value json-node (symbol->string validation-error)))
validation-errors)
(json->string json-node))))
|
95d26ec50db05536c6aa648c9449f5bb027ffb827fdcaa5a305791cda99461ac | tmprender/texy | codegen-hello.ml | Code generation : translate takes a semantically checked AST and
produces LLVM IR
LLVM tutorial : Make sure to read the OCaml version of the tutorial
Detailed documentation on the OCaml LLVM library :
/
/
produces LLVM IR
LLVM tutorial: Make sure to read the OCaml version of the tutorial
Detailed documentation on the OCaml LLVM library:
/
/
*)
We 'll refer to and Ast constructs with module names
module L = Llvm
module A = Ast
open Sast
module StringMap = Map.Make(String)
Code Generation from the SAST . Returns an LLVM module if successful ,
throws an exception if something is wrong .
throws an exception if something is wrong. *)
let translate (_, functions) =
let context = L.global_context () in
Add types to the context so we can use them in our LLVM code
let i32_t = L.i32_type context
and i8_t = L.i8_type context
and void_t = L.void_type context
(* Create an LLVM module -- this is a "container" into which we'll
generate actual code *)
and the_module = L.create_module context "MicroC" in
Convert MicroC types to types
let ltype_of_typ = function
A.Int -> i32_t
| A.Void -> void_t
| t -> raise (Failure ("Type " ^ A.string_of_typ t ^ " not implemented yet"))
in
(* declare i32 @printf(i8*, ...) *)
let printf_t : L.lltype =
L.var_arg_function_type i32_t [| L.pointer_type i8_t |] in
let printf_func : L.llvalue =
L.declare_function "printf" printf_t the_module in
let to_imp str = raise (Failure ("Not yet implemented: " ^ str)) in
Generate the instructions to define a MicroC function
let build_function fdecl =
(* int main() {} -----> define i32 @main() {} *)
let main_ty = L.function_type (ltype_of_typ fdecl.styp) [||] in
let the_function = L.define_function "main" main_ty the_module in
(* An LLVM "instruction builder" points to a basic block.
* Adding a new instruction mutates both the_module and builder. *)
let builder = L.builder_at_end context (L.entry_block the_function) in
@fmt = < stuff > [ 4 x i8 ] c"%d\0A\00 "
let int_format_str = L.build_global_stringptr "%d\n" "fmt" builder in
let rec expr builder ((_, e) : sexpr) = match e with
42 ----- > i32 42
SLiteral i -> L.const_int i32_t i
print(42 ) ----- > % printf = call i32 ( i8 * , ... ) > , i32 42 )
| SCall ("print", [e]) ->
L.build_call printf_func [| int_format_str ; (expr builder e) |]
"printf" builder
(* Throw an exception for any other expressions *)
| _ -> to_imp (string_of_sexpr (A.Int,e))
in
let rec stmt builder = function
SExpr e -> let _ = expr builder e in builder
| SBlock sl -> List.fold_left stmt builder sl
(* return 0; -----> ret i32 0 *)
| SReturn e -> let _ = match fdecl.styp with
A.Int -> L.build_ret (expr builder e) builder
| _ -> to_imp (A.string_of_typ fdecl.styp)
in builder
| s -> to_imp (string_of_sstmt s)
in ignore (stmt builder (SBlock fdecl.sbody))
Build each function ( there should only be one for Hello World ) ,
and return the final module
and return the final module *)
in List.iter build_function functions; the_module
| null | https://raw.githubusercontent.com/tmprender/texy/e9bf4c9195aa7b590e8c5f3f7291f6e6005071b6/codegen-hello.ml | ocaml | Create an LLVM module -- this is a "container" into which we'll
generate actual code
declare i32 @printf(i8*, ...)
int main() {} -----> define i32 @main() {}
An LLVM "instruction builder" points to a basic block.
* Adding a new instruction mutates both the_module and builder.
Throw an exception for any other expressions
return 0; -----> ret i32 0 | Code generation : translate takes a semantically checked AST and
produces LLVM IR
LLVM tutorial : Make sure to read the OCaml version of the tutorial
Detailed documentation on the OCaml LLVM library :
/
/
produces LLVM IR
LLVM tutorial: Make sure to read the OCaml version of the tutorial
Detailed documentation on the OCaml LLVM library:
/
/
*)
We 'll refer to and Ast constructs with module names
module L = Llvm
module A = Ast
open Sast
module StringMap = Map.Make(String)
Code Generation from the SAST . Returns an LLVM module if successful ,
throws an exception if something is wrong .
throws an exception if something is wrong. *)
let translate (_, functions) =
let context = L.global_context () in
Add types to the context so we can use them in our LLVM code
let i32_t = L.i32_type context
and i8_t = L.i8_type context
and void_t = L.void_type context
and the_module = L.create_module context "MicroC" in
Convert MicroC types to types
let ltype_of_typ = function
A.Int -> i32_t
| A.Void -> void_t
| t -> raise (Failure ("Type " ^ A.string_of_typ t ^ " not implemented yet"))
in
let printf_t : L.lltype =
L.var_arg_function_type i32_t [| L.pointer_type i8_t |] in
let printf_func : L.llvalue =
L.declare_function "printf" printf_t the_module in
let to_imp str = raise (Failure ("Not yet implemented: " ^ str)) in
Generate the instructions to define a MicroC function
let build_function fdecl =
let main_ty = L.function_type (ltype_of_typ fdecl.styp) [||] in
let the_function = L.define_function "main" main_ty the_module in
let builder = L.builder_at_end context (L.entry_block the_function) in
@fmt = < stuff > [ 4 x i8 ] c"%d\0A\00 "
let int_format_str = L.build_global_stringptr "%d\n" "fmt" builder in
let rec expr builder ((_, e) : sexpr) = match e with
42 ----- > i32 42
SLiteral i -> L.const_int i32_t i
print(42 ) ----- > % printf = call i32 ( i8 * , ... ) > , i32 42 )
| SCall ("print", [e]) ->
L.build_call printf_func [| int_format_str ; (expr builder e) |]
"printf" builder
| _ -> to_imp (string_of_sexpr (A.Int,e))
in
let rec stmt builder = function
SExpr e -> let _ = expr builder e in builder
| SBlock sl -> List.fold_left stmt builder sl
| SReturn e -> let _ = match fdecl.styp with
A.Int -> L.build_ret (expr builder e) builder
| _ -> to_imp (A.string_of_typ fdecl.styp)
in builder
| s -> to_imp (string_of_sstmt s)
in ignore (stmt builder (SBlock fdecl.sbody))
Build each function ( there should only be one for Hello World ) ,
and return the final module
and return the final module *)
in List.iter build_function functions; the_module
|
39748a5446d85854232829dcf233557055595b10df1c44d10e26e7e6752f1735 | deadcode/Learning-CL--David-Touretzky | 10.10.lisp | (defun ntack (x sym)
(setf (cdr (last x)) sym))
(let* ((sample-list ''(fee fie foe))
(sym ''(fum))
(test1 (list 'ntack sample-list sym)))
(format t "~&sample-list = ~s, sym = ~s" sample-list sym)
(format t "~&Testing ~s" test1)
(eval test1)
(format t "~&sample-list = ~s, sym = ~s" sample-list sym))
| null | https://raw.githubusercontent.com/deadcode/Learning-CL--David-Touretzky/b4557c33f58e382f765369971e6a4747c27ca692/Chapter%2010/10.10.lisp | lisp | (defun ntack (x sym)
(setf (cdr (last x)) sym))
(let* ((sample-list ''(fee fie foe))
(sym ''(fum))
(test1 (list 'ntack sample-list sym)))
(format t "~&sample-list = ~s, sym = ~s" sample-list sym)
(format t "~&Testing ~s" test1)
(eval test1)
(format t "~&sample-list = ~s, sym = ~s" sample-list sym))
|
|
e2a98c4b4d0a6cba133c610d4124815762977f8eb00165e682e9945f6daef24d | alex-gutev/cl-form-types | block-types.lisp | ;;;; block-types.lisp
;;;;
Copyright 2021 < >
;;;;
;;;; 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.
Determining the type of CL : BLOCK forms
(in-package :cl-form-types)
(defvar *block-name* nil
"The name of the BLOCK of which the type is currently being
determined.")
(defvar *in-block* nil
"Flag for whether RETURN-FROM forms to the block name *BLOCK-NAME*
are treated as returning from the block, of which the type is
currently being determined, (true) or they are treated as returning
from a block nested in it (false).")
(defvar *local-fns* nil
"Association list of the types of values returned from the current
block by RETURN-FROM forms located within functions defined locally
within the block.")
(defmethod special-form-type ((operator (eql 'cl:block)) operands env)
(match-form operands
((list* (and (type symbol) name)
(and (type proper-list) forms))
(flet ((combine (type1 &optional (type2 nil type2-sp))
(if type2-sp
(combine-values-types 'or type1 type2)
type1)))
(-<> (extract-return-from-types name `(progn ,@forms) env)
(remove-duplicates :test #'equal)
(reduce #'combine <> :initial-value (form-type% (lastcar forms) env)))))))
(defun local-function-type (name)
(cdr (assoc name *local-fns* :test #'equal)))
;;; Code Walking
(defvar *block-types* nil
"List containing the list of value types returned by the current
BLOCK form.")
(defun extract-return-from-types (name form env)
"Extract the list of value types returned by a BLOCK form.
*BLOCK-NAME* is the label naming the block.
FORM is a PROGN form representing the block body.
ENV is the environment in which the BLOCK form is contained.
Returns the list of value types which may be returned from the
BLOCK form by an explicit RETURN-FROM form."
(let ((*block-name* name)
(*block-types*)
(*in-block* t)
(*local-fns* nil))
(block-type-walk-form form env)
*block-types*))
(defun block-type-walk-form (form env)
"Walk a subform of a BLOCK form and extract the value types returned
from the block by RETURN-FROM."
(labels ((walk (form env)
(match form
((list* operator operands)
(block-type-walk-list-form operator operands env))
(_ form))))
(walk-form #'walk form env :result-type nil)))
(defgeneric block-type-walk-list-form (operator operands env)
(:documentation
"Extract RETURN-FROM types from a function call expression form
appearing within a BLOCK form."))
(defmethod block-type-walk-list-form (operator operands env)
(when (symbolp operator)
(when (and (special-operator-p operator)
(not (member operator +cl-special-forms+))
(null (macro-function operator env)))
(error 'unknown-special-operator
:operator operator
:operands operands))
(appendf *block-types* (cdr (assoc operator *local-fns*))))
(cons operator operands))
;;; Walker Methods for Special Forms
(defmethod block-type-walk-list-form ((operator (eql 'cl:block)) operands env)
(match-form operands
((list* (and (type symbol) name) forms)
(let ((*in-block* (not (eq name *block-name*))))
(values
(block-type-walk-form `(progn ,@forms) env)
t)))))
(defmethod block-type-walk-list-form ((operator (eql 'cl:return-from)) operands env)
"Method for RETURN-FROM forms.
If the block name is equal to *BLOCK-NAME* and *IN-BLOCK* is true,
the type of the result form as if by FORM-TYPE% is returned, as
well as the types of any nested RETURN-FROM forms."
(match-form operands
((list (and (type symbol) name) result)
(when (and *in-block* (eq name *block-name*))
(push (form-type% result env) *block-types*))
(cons operator operands))))
(defmethod block-type-walk-list-form ((operator (eql 'cl:load-time-value)) operands env)
(declare (ignore operands env))
;; Does nothing, since LOAD-TIME-VALUE forms are evaluated in a null
;; lexical environment, therefore they cannot RETURN-FROM to the
;; BLOCK.
(values nil t))
(defmethod block-type-walk-list-form ((operator (eql 'cl:function)) operands env)
(declare (ignore env))
(match operands
((list (and (type function-name) name))
(appendf *block-types* (local-function-type name))))
(cons operator operands))
;;; Function Definition Forms
(defmethod block-type-walk-list-form ((operator (eql 'cl:flet)) operands env)
(flet ((function-name (binding)
(match-form binding
((list* (and (type function-name) name) _)
name))))
(match-form operands
((list* (and (type proper-list) functions)
body)
(let* ((names (mapcar #'function-name functions))
(ftypes (mapcar (rcurry #'block-type-walk-local-fn env) functions))
(*local-fns* (append ftypes *local-fns*)))
(values
(->> (augment-environment env :function names)
(block-type-walk-form `(cl:locally ,@body)))
t))))))
(defmethod block-type-walk-list-form ((operator (eql 'cl:labels)) operands env)
(flet ((function-name (binding)
(match-form binding
((list* (and (type function-name) name) _)
name))))
(match-form operands
((list* (and (type proper-list) functions)
body)
(let* ((names (mapcar #'function-name functions))
(env (augment-environment env :function names))
(ftypes (local-function-types names functions env))
(*local-fns* (append ftypes *local-fns*)))
(values
(block-type-walk-form `(cl:locally ,@body) env)
t))))))
(defun local-function-types (names functions env)
"Determine the types of the RETURN-FROM forms in lexical functions.
NAMES is the list of the function names.
FUNCTIONS is the list of the function definitions as they appear in
the FLET or LABELS form.
ENV is the environment in which the lexical function definitions occur."
(subst-local-function-types
(let ((*local-fns*
(-> (mapcar
(lambda (name)
`(,name . ((call ,name))))
names)
(append *local-fns*))))
(mapcar (rcurry #'block-type-walk-local-fn env) functions))))
(defun subst-local-function-types (ftypes)
"Substitute (CALL ...) types with actual types returned by the function.
In the types of the RETURN-FROM forms, located within a function,
types which reference the types of the RETURN-FROM forms in another
function `(CALL ...)` are replaced with the actual list of the
types of the RETURN-FROM forms in that function.
FTYPES is an association list with each entry of the form (FN
. TYPES) where FN is the function name and TYPES is the list of
type specifiers.
Returns the association list with the new RETURN-FORM form type
lists."
(labels ((replace-call-fn (ftypes fn)
(let ((types (-> (cdr (assoc fn ftypes))
(remove-call-fn fn))))
(mapcar (rcurry #'replace-calls fn types) ftypes)))
(remove-call-fn (types fn)
(remove `(call ,fn) types :test #'equal))
(replace-calls (entry fn new-types)
(destructuring-bind (name . old-types) entry
(cons name (mappend (rcurry #'replace-call fn new-types) old-types))))
(replace-call (type fn types)
(match type
((list 'call (equal fn))
types)
(_ (list type)))))
(nlet process ((ftypes ftypes) (fns ftypes))
(if fns
(-> (replace-call-fn ftypes (caar fns))
(process (cdr fns)))
ftypes))))
(defun block-type-walk-local-fn (def env)
"Extract RETURN-FROM value types from a local named function definition.
DEF is the list containing the function definition, with the first
element being the function name.
ENV is the environment in which the form is found.
Returns the list of value types which may be returned when the
function is called."
(let ((*block-types* nil))
(destructuring-bind (name &rest def) def
(block-type-walk-form `#'(cl:lambda ,@def) env)
(cons name *block-types*))))
| null | https://raw.githubusercontent.com/alex-gutev/cl-form-types/fc3647c948f060fb0faea4ff4409a589c4e6e168/src/block-types.lisp | lisp | block-types.lisp
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Code Walking
Walker Methods for Special Forms
Does nothing, since LOAD-TIME-VALUE forms are evaluated in a null
lexical environment, therefore they cannot RETURN-FROM to the
BLOCK.
Function Definition Forms | Copyright 2021 < >
files ( the " Software " ) , to deal in the Software without
copies of the Software , and to permit persons to whom the
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
Determining the type of CL : BLOCK forms
(in-package :cl-form-types)
(defvar *block-name* nil
"The name of the BLOCK of which the type is currently being
determined.")
(defvar *in-block* nil
"Flag for whether RETURN-FROM forms to the block name *BLOCK-NAME*
are treated as returning from the block, of which the type is
currently being determined, (true) or they are treated as returning
from a block nested in it (false).")
(defvar *local-fns* nil
"Association list of the types of values returned from the current
block by RETURN-FROM forms located within functions defined locally
within the block.")
(defmethod special-form-type ((operator (eql 'cl:block)) operands env)
(match-form operands
((list* (and (type symbol) name)
(and (type proper-list) forms))
(flet ((combine (type1 &optional (type2 nil type2-sp))
(if type2-sp
(combine-values-types 'or type1 type2)
type1)))
(-<> (extract-return-from-types name `(progn ,@forms) env)
(remove-duplicates :test #'equal)
(reduce #'combine <> :initial-value (form-type% (lastcar forms) env)))))))
(defun local-function-type (name)
(cdr (assoc name *local-fns* :test #'equal)))
(defvar *block-types* nil
"List containing the list of value types returned by the current
BLOCK form.")
(defun extract-return-from-types (name form env)
"Extract the list of value types returned by a BLOCK form.
*BLOCK-NAME* is the label naming the block.
FORM is a PROGN form representing the block body.
ENV is the environment in which the BLOCK form is contained.
Returns the list of value types which may be returned from the
BLOCK form by an explicit RETURN-FROM form."
(let ((*block-name* name)
(*block-types*)
(*in-block* t)
(*local-fns* nil))
(block-type-walk-form form env)
*block-types*))
(defun block-type-walk-form (form env)
"Walk a subform of a BLOCK form and extract the value types returned
from the block by RETURN-FROM."
(labels ((walk (form env)
(match form
((list* operator operands)
(block-type-walk-list-form operator operands env))
(_ form))))
(walk-form #'walk form env :result-type nil)))
(defgeneric block-type-walk-list-form (operator operands env)
(:documentation
"Extract RETURN-FROM types from a function call expression form
appearing within a BLOCK form."))
(defmethod block-type-walk-list-form (operator operands env)
(when (symbolp operator)
(when (and (special-operator-p operator)
(not (member operator +cl-special-forms+))
(null (macro-function operator env)))
(error 'unknown-special-operator
:operator operator
:operands operands))
(appendf *block-types* (cdr (assoc operator *local-fns*))))
(cons operator operands))
(defmethod block-type-walk-list-form ((operator (eql 'cl:block)) operands env)
(match-form operands
((list* (and (type symbol) name) forms)
(let ((*in-block* (not (eq name *block-name*))))
(values
(block-type-walk-form `(progn ,@forms) env)
t)))))
(defmethod block-type-walk-list-form ((operator (eql 'cl:return-from)) operands env)
"Method for RETURN-FROM forms.
If the block name is equal to *BLOCK-NAME* and *IN-BLOCK* is true,
the type of the result form as if by FORM-TYPE% is returned, as
well as the types of any nested RETURN-FROM forms."
(match-form operands
((list (and (type symbol) name) result)
(when (and *in-block* (eq name *block-name*))
(push (form-type% result env) *block-types*))
(cons operator operands))))
(defmethod block-type-walk-list-form ((operator (eql 'cl:load-time-value)) operands env)
(declare (ignore operands env))
(values nil t))
(defmethod block-type-walk-list-form ((operator (eql 'cl:function)) operands env)
(declare (ignore env))
(match operands
((list (and (type function-name) name))
(appendf *block-types* (local-function-type name))))
(cons operator operands))
(defmethod block-type-walk-list-form ((operator (eql 'cl:flet)) operands env)
(flet ((function-name (binding)
(match-form binding
((list* (and (type function-name) name) _)
name))))
(match-form operands
((list* (and (type proper-list) functions)
body)
(let* ((names (mapcar #'function-name functions))
(ftypes (mapcar (rcurry #'block-type-walk-local-fn env) functions))
(*local-fns* (append ftypes *local-fns*)))
(values
(->> (augment-environment env :function names)
(block-type-walk-form `(cl:locally ,@body)))
t))))))
(defmethod block-type-walk-list-form ((operator (eql 'cl:labels)) operands env)
(flet ((function-name (binding)
(match-form binding
((list* (and (type function-name) name) _)
name))))
(match-form operands
((list* (and (type proper-list) functions)
body)
(let* ((names (mapcar #'function-name functions))
(env (augment-environment env :function names))
(ftypes (local-function-types names functions env))
(*local-fns* (append ftypes *local-fns*)))
(values
(block-type-walk-form `(cl:locally ,@body) env)
t))))))
(defun local-function-types (names functions env)
"Determine the types of the RETURN-FROM forms in lexical functions.
NAMES is the list of the function names.
FUNCTIONS is the list of the function definitions as they appear in
the FLET or LABELS form.
ENV is the environment in which the lexical function definitions occur."
(subst-local-function-types
(let ((*local-fns*
(-> (mapcar
(lambda (name)
`(,name . ((call ,name))))
names)
(append *local-fns*))))
(mapcar (rcurry #'block-type-walk-local-fn env) functions))))
(defun subst-local-function-types (ftypes)
"Substitute (CALL ...) types with actual types returned by the function.
In the types of the RETURN-FROM forms, located within a function,
types which reference the types of the RETURN-FROM forms in another
function `(CALL ...)` are replaced with the actual list of the
types of the RETURN-FROM forms in that function.
FTYPES is an association list with each entry of the form (FN
. TYPES) where FN is the function name and TYPES is the list of
type specifiers.
Returns the association list with the new RETURN-FORM form type
lists."
(labels ((replace-call-fn (ftypes fn)
(let ((types (-> (cdr (assoc fn ftypes))
(remove-call-fn fn))))
(mapcar (rcurry #'replace-calls fn types) ftypes)))
(remove-call-fn (types fn)
(remove `(call ,fn) types :test #'equal))
(replace-calls (entry fn new-types)
(destructuring-bind (name . old-types) entry
(cons name (mappend (rcurry #'replace-call fn new-types) old-types))))
(replace-call (type fn types)
(match type
((list 'call (equal fn))
types)
(_ (list type)))))
(nlet process ((ftypes ftypes) (fns ftypes))
(if fns
(-> (replace-call-fn ftypes (caar fns))
(process (cdr fns)))
ftypes))))
(defun block-type-walk-local-fn (def env)
"Extract RETURN-FROM value types from a local named function definition.
DEF is the list containing the function definition, with the first
element being the function name.
ENV is the environment in which the form is found.
Returns the list of value types which may be returned when the
function is called."
(let ((*block-types* nil))
(destructuring-bind (name &rest def) def
(block-type-walk-form `#'(cl:lambda ,@def) env)
(cons name *block-types*))))
|
6b4290481833f5e60c212d4dc9b58ec52a3844e973ee5a13638089b5fe9f81e9 | sixthnormal/clj-3df | core_test.cljc | (ns clj-3df.core-test
(:require
#?(:clj [clojure.test :refer [deftest is testing run-tests]]
:cljs [cljs.test :refer-macros [deftest is testing run-tests]])
[clj-3df.core :as df :refer [exec! create-debug-conn!
create-db-inputs query register interest transact]]))
(defn- debug-conn []
(let [conn (create-debug-conn! "ws:6262")]
conn))
(comment
(def conn (debug-conn))
(def db (df/create-db {:parent/child {:db/valueType :Eid}
:create {:db/valueType :Eid}
:read {:db/valueType :Eid}
:update {:db/valueType :Eid}
:delete {:db/valueType :Eid}}))
(exec! conn
(df/create-db-inputs db))
(def rules
'[[(read? ?user ?obj) (or [?user :read ?obj]
(and [?parent :parent/child ?obj]
(read? ?user ?parent)))]])
(exec! conn
(query
db "rba"
'[:find ?user ?obj :where (read? ?user ?obj)]
rules))
(exec! conn
(transact db [[:db/add 100 :read 901]]))
(exec! conn
(transact db [[:db/add 901 :parent/child 902]]))
(exec! conn
(transact db [[:db/retract 100 :read 901]]))
(exec! conn
(transact db [[:db/retract 901 :parent/child 902]]))
(exec! conn
(transact db [[:db/add 100 :read 901]])
(transact db [[:db/add 901 :parent/child 902]])
(query db "rba" '[:find ?user ?obj :where (read? ?user ?obj)] rules))
)
@TODO until unregister is available , the server has to be restarted
;; between tests to avoid interference
@TODO
;; Naming guidelines: Tests in here should be named in such a way,
that there is a one - to - one correspondence between tests and actual ,
;; user-facing query engine features.
@TODO this test - suite should mirror the datascript tests
(deftest test-basic-conjunction
(let [name "basic-conjunction"
db (df/create-db {:name {:db/valueType :String} :age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find ?e ?age :where [?e :name "Mabel"] [?e :age ?age]])
(transact db [[:db/add 1 :name "Dipper"] [:db/add 1 :age 26]])
(transact db [{:db/id 2 :name "Mabel" :age 26}])
(expect-> out (is (= [name [[[2 26] 1 1]]] out)))
(transact db [[:db/retract 2 :name "Mabel"]])
(expect-> out (is (= [name [[[2 26] 2 -1]]] out))))))
(deftest test-multi-conjunction
(let [name "multi-conjunction"
db (df/create-db {:name {:db/valueType :String} :age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find ?e1 ?e2
:where
[?e1 :name ?name] [?e1 :age ?age]
[?e2 :name ?name] [?e2 :age ?age]])
(transact db [{:db/id 1 :name "Dipper" :age 26}
{:db/id 2 :name "Mabel" :age 26}
{:db/id 3 :name "Soos" :age 32}])
(expect-> out (is (= [name [[[1 1] 0 1] [[2 2] 0 1] [[3 3] 0 1]]] out)))
(transact db [[:db/retract 2 :name "Mabel"]])
(expect-> out (is (= [name [[[2 2] 1 -1]]] out))))))
(deftest test-cartesian
(let [name "cartesian"
db (df/create-db {:name {:db/valueType :String}})]
(exec! (debug-conn)
(create-db-inputs db)
;; (query db name '[:find ?e1 ?e2 :where [?e1 :name ?n1] [?e2 :name ?n2]])
(register db name '{:Project
[[?e1 ?e2]
{:Join [[]
{:MatchA [?e1 :name ?n1]}
{:MatchA [?e2 :name ?n2]}]}]} [])
(interest name)
(transact db [[:db/add 1 :name "Dipper"]
[:db/add 2 :name "Mabel"]])
(expect-> out (is (= [name [[[1 1] 0 1] [[1 2] 0 1] [[2 1] 0 1] [[2 2] 0 1]]] out)))
(transact db [[:db/retract 2 :name "Mabel"]])
(expect-> out (is (= [name [[[1 2] 1 -1] [[2 1] 1 -1] [[2 2] 1 -1]]] out))))))
(deftest test-basic-disjunction
(let [name "basic-disjunction"
db (df/create-db {:name {:db/valueType :String} :age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find ?e :where (or [?e :name "Mabel"] [?e :name "Dipper"])])
(transact db [[:db/add 1 :name "Dipper"] [:db/add 1 :age 26]])
(expect-> out (is (= [name [[[1] 0 1]]] out)))
(transact db [{:db/id 2 :name "Mabel" :age 26}])
(expect-> out (is (= [name [[[2] 1 1]]] out)))
(transact db [[:db/retract 2 :name "Mabel"]])
(expect-> out (is (= [name [[[2] 2 -1]]] out))))))
(deftest test-conjunction-and-disjunction
(let [name "conjunction-and-disjunction"
db (df/create-db {:name {:db/valueType :String} :age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find ?e
:where
[?e :name "Mabel"]
(or [?e :age 14]
[?e :age 12])])
(transact db [[:db/add 1 :name "Dipper"] [:db/add 1 :age 14]
{:db/id 2 :name "Mabel" :age 14}
{:db/id 3 :name "Mabel" :age 12}
{:db/id 4 :name "Mabel" :age 18}])
(expect-> out (is (= [name [[[2] 0 1] [[3] 0 1]]] out)))
(transact db [[:db/retract 2 :name "Mabel"]
[:db/retract 3 :age 12]])
(expect-> out (is (= [name [[[2] 1 -1] [[3] 1 -1]]] out))))))
(deftest test-simple-negation
(let [name "simple-negation"
db (df/create-db {:name {:db/valueType :String} :age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find ?e :where [?e :name "Mabel"] (not [?e :age 25])])
(transact db [{:db/id 1 :name "Mabel" :age 25}])
(transact db [{:db/id 2 :name "Mabel" :age 42}])
(expect-> out (is (= [name [[[2] 1 1]]] out)))
(transact db [[:db/add 2 :age 25]])
(expect-> out (is (= [name [[[2] 2 -1]]] out))))))
(deftest test-min
(let [name "min"
db (df/create-db {:age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find (min ?age) :where [?user :age ?age]])
(transact db [{:db/id 1 :age 12}
{:db/id 2 :age 25}])
(expect-> out (is (= [name [[[12] 0 1]]] out)))
(transact db [[:db/add 3 :age 5]])
(expect-> out (is (= [name [[[5] 1 1] [[12] 1 -1]]] out))))))
(deftest test-max
(let [name "max"
db (df/create-db {:age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find (max ?age) :where [?user :age ?age]])
(transact db [{:db/id 1 :age 12}
{:db/id 2 :age 25}])
(expect-> out (is (= [name [[[25] 0 1]]] out)))
(transact db [[:db/add 3 :age 35]])
(expect-> out (is (= [name [[[35] 1 1] [[25] 1 -1]]] out))))))
(deftest test-count
(let [name "count"
db (df/create-db {:age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find (count ?user) :where [?user :age ?age]])
(transact db [{:db/id 1 :age 12}
{:db/id 2 :age 25}])
(expect-> out (is (= [name [[[2] 0 1]]] out)))
(transact db [[:db/add 3 :age 5]])
(expect-> out (is (= [name [[[2] 1 -1] [[3] 1 1]]] out)))
(transact db [[:db/retract 3 :age 5]])
(expect-> out (is (= [name [[[2] 2 1] [[3] 2 -1]]] out))))))
(deftest test-registration
(testing "queries should produce results for previously transacted data"
(let [name "rba"
db (df/create-db {:parent/child {:db/valueType :Eid}
:create {:db/valueType :Eid}
:read {:db/valueType :Eid}
:update {:db/valueType :Eid}
:delete {:db/valueType :Eid}})
rules '[[(read? ?user ?obj) (or [?user :read ?obj]
(and [?parent :parent/child ?obj]
(read? ?user ?parent)))]]
conn (debug-conn)]
(exec! conn
(create-db-inputs db)
(transact db [[:db/add 100 :read 901]
[:db/add 901 :parent/child 902]]))
(Thread/sleep 1000)
(exec! conn
(query db name '[:find ?user ?obj
:where (read? ?user ?obj)] rules)
(expect-> out (is (= [name [[[100 901] 0 1] [[100 902] 0 1]]] out)))))))
| null | https://raw.githubusercontent.com/sixthnormal/clj-3df/7dfb89a438f9fb1a3c5d0d356f05acf3f9c51177/test/clj_3df/core_test.cljc | clojure | between tests to avoid interference
Naming guidelines: Tests in here should be named in such a way,
user-facing query engine features.
(query db name '[:find ?e1 ?e2 :where [?e1 :name ?n1] [?e2 :name ?n2]]) | (ns clj-3df.core-test
(:require
#?(:clj [clojure.test :refer [deftest is testing run-tests]]
:cljs [cljs.test :refer-macros [deftest is testing run-tests]])
[clj-3df.core :as df :refer [exec! create-debug-conn!
create-db-inputs query register interest transact]]))
(defn- debug-conn []
(let [conn (create-debug-conn! "ws:6262")]
conn))
(comment
(def conn (debug-conn))
(def db (df/create-db {:parent/child {:db/valueType :Eid}
:create {:db/valueType :Eid}
:read {:db/valueType :Eid}
:update {:db/valueType :Eid}
:delete {:db/valueType :Eid}}))
(exec! conn
(df/create-db-inputs db))
(def rules
'[[(read? ?user ?obj) (or [?user :read ?obj]
(and [?parent :parent/child ?obj]
(read? ?user ?parent)))]])
(exec! conn
(query
db "rba"
'[:find ?user ?obj :where (read? ?user ?obj)]
rules))
(exec! conn
(transact db [[:db/add 100 :read 901]]))
(exec! conn
(transact db [[:db/add 901 :parent/child 902]]))
(exec! conn
(transact db [[:db/retract 100 :read 901]]))
(exec! conn
(transact db [[:db/retract 901 :parent/child 902]]))
(exec! conn
(transact db [[:db/add 100 :read 901]])
(transact db [[:db/add 901 :parent/child 902]])
(query db "rba" '[:find ?user ?obj :where (read? ?user ?obj)] rules))
)
@TODO until unregister is available , the server has to be restarted
@TODO
that there is a one - to - one correspondence between tests and actual ,
@TODO this test - suite should mirror the datascript tests
(deftest test-basic-conjunction
(let [name "basic-conjunction"
db (df/create-db {:name {:db/valueType :String} :age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find ?e ?age :where [?e :name "Mabel"] [?e :age ?age]])
(transact db [[:db/add 1 :name "Dipper"] [:db/add 1 :age 26]])
(transact db [{:db/id 2 :name "Mabel" :age 26}])
(expect-> out (is (= [name [[[2 26] 1 1]]] out)))
(transact db [[:db/retract 2 :name "Mabel"]])
(expect-> out (is (= [name [[[2 26] 2 -1]]] out))))))
(deftest test-multi-conjunction
(let [name "multi-conjunction"
db (df/create-db {:name {:db/valueType :String} :age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find ?e1 ?e2
:where
[?e1 :name ?name] [?e1 :age ?age]
[?e2 :name ?name] [?e2 :age ?age]])
(transact db [{:db/id 1 :name "Dipper" :age 26}
{:db/id 2 :name "Mabel" :age 26}
{:db/id 3 :name "Soos" :age 32}])
(expect-> out (is (= [name [[[1 1] 0 1] [[2 2] 0 1] [[3 3] 0 1]]] out)))
(transact db [[:db/retract 2 :name "Mabel"]])
(expect-> out (is (= [name [[[2 2] 1 -1]]] out))))))
(deftest test-cartesian
(let [name "cartesian"
db (df/create-db {:name {:db/valueType :String}})]
(exec! (debug-conn)
(create-db-inputs db)
(register db name '{:Project
[[?e1 ?e2]
{:Join [[]
{:MatchA [?e1 :name ?n1]}
{:MatchA [?e2 :name ?n2]}]}]} [])
(interest name)
(transact db [[:db/add 1 :name "Dipper"]
[:db/add 2 :name "Mabel"]])
(expect-> out (is (= [name [[[1 1] 0 1] [[1 2] 0 1] [[2 1] 0 1] [[2 2] 0 1]]] out)))
(transact db [[:db/retract 2 :name "Mabel"]])
(expect-> out (is (= [name [[[1 2] 1 -1] [[2 1] 1 -1] [[2 2] 1 -1]]] out))))))
(deftest test-basic-disjunction
(let [name "basic-disjunction"
db (df/create-db {:name {:db/valueType :String} :age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find ?e :where (or [?e :name "Mabel"] [?e :name "Dipper"])])
(transact db [[:db/add 1 :name "Dipper"] [:db/add 1 :age 26]])
(expect-> out (is (= [name [[[1] 0 1]]] out)))
(transact db [{:db/id 2 :name "Mabel" :age 26}])
(expect-> out (is (= [name [[[2] 1 1]]] out)))
(transact db [[:db/retract 2 :name "Mabel"]])
(expect-> out (is (= [name [[[2] 2 -1]]] out))))))
(deftest test-conjunction-and-disjunction
(let [name "conjunction-and-disjunction"
db (df/create-db {:name {:db/valueType :String} :age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find ?e
:where
[?e :name "Mabel"]
(or [?e :age 14]
[?e :age 12])])
(transact db [[:db/add 1 :name "Dipper"] [:db/add 1 :age 14]
{:db/id 2 :name "Mabel" :age 14}
{:db/id 3 :name "Mabel" :age 12}
{:db/id 4 :name "Mabel" :age 18}])
(expect-> out (is (= [name [[[2] 0 1] [[3] 0 1]]] out)))
(transact db [[:db/retract 2 :name "Mabel"]
[:db/retract 3 :age 12]])
(expect-> out (is (= [name [[[2] 1 -1] [[3] 1 -1]]] out))))))
(deftest test-simple-negation
(let [name "simple-negation"
db (df/create-db {:name {:db/valueType :String} :age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find ?e :where [?e :name "Mabel"] (not [?e :age 25])])
(transact db [{:db/id 1 :name "Mabel" :age 25}])
(transact db [{:db/id 2 :name "Mabel" :age 42}])
(expect-> out (is (= [name [[[2] 1 1]]] out)))
(transact db [[:db/add 2 :age 25]])
(expect-> out (is (= [name [[[2] 2 -1]]] out))))))
(deftest test-min
(let [name "min"
db (df/create-db {:age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find (min ?age) :where [?user :age ?age]])
(transact db [{:db/id 1 :age 12}
{:db/id 2 :age 25}])
(expect-> out (is (= [name [[[12] 0 1]]] out)))
(transact db [[:db/add 3 :age 5]])
(expect-> out (is (= [name [[[5] 1 1] [[12] 1 -1]]] out))))))
(deftest test-max
(let [name "max"
db (df/create-db {:age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find (max ?age) :where [?user :age ?age]])
(transact db [{:db/id 1 :age 12}
{:db/id 2 :age 25}])
(expect-> out (is (= [name [[[25] 0 1]]] out)))
(transact db [[:db/add 3 :age 35]])
(expect-> out (is (= [name [[[35] 1 1] [[25] 1 -1]]] out))))))
(deftest test-count
(let [name "count"
db (df/create-db {:age {:db/valueType :Number}})]
(exec! (debug-conn)
(create-db-inputs db)
(query db name '[:find (count ?user) :where [?user :age ?age]])
(transact db [{:db/id 1 :age 12}
{:db/id 2 :age 25}])
(expect-> out (is (= [name [[[2] 0 1]]] out)))
(transact db [[:db/add 3 :age 5]])
(expect-> out (is (= [name [[[2] 1 -1] [[3] 1 1]]] out)))
(transact db [[:db/retract 3 :age 5]])
(expect-> out (is (= [name [[[2] 2 1] [[3] 2 -1]]] out))))))
(deftest test-registration
(testing "queries should produce results for previously transacted data"
(let [name "rba"
db (df/create-db {:parent/child {:db/valueType :Eid}
:create {:db/valueType :Eid}
:read {:db/valueType :Eid}
:update {:db/valueType :Eid}
:delete {:db/valueType :Eid}})
rules '[[(read? ?user ?obj) (or [?user :read ?obj]
(and [?parent :parent/child ?obj]
(read? ?user ?parent)))]]
conn (debug-conn)]
(exec! conn
(create-db-inputs db)
(transact db [[:db/add 100 :read 901]
[:db/add 901 :parent/child 902]]))
(Thread/sleep 1000)
(exec! conn
(query db name '[:find ?user ?obj
:where (read? ?user ?obj)] rules)
(expect-> out (is (= [name [[[100 901] 0 1] [[100 902] 0 1]]] out)))))))
|
3721db8bb45100e55e02e226eb6d6d29c7ef9de667e3708508bc94943925b39b | fourmolu/fourmolu | fancy-forall-1-four-out.hs | magnify ::
forall outertag innertag t outer inner m a.
( forall x. Coercible (t m x) (m x)
, forall m'.
(HasReader outertag outer m') =>
HasReader innertag inner (t m')
, HasReader outertag outer m
) =>
(forall m'. (HasReader innertag inner m') => m' a) ->
m a
| null | https://raw.githubusercontent.com/fourmolu/fourmolu/f47860f01cb3cac3b973c5df6ecbae48bbb4c295/data/examples/declaration/value/function/fancy-forall-1-four-out.hs | haskell | magnify ::
forall outertag innertag t outer inner m a.
( forall x. Coercible (t m x) (m x)
, forall m'.
(HasReader outertag outer m') =>
HasReader innertag inner (t m')
, HasReader outertag outer m
) =>
(forall m'. (HasReader innertag inner m') => m' a) ->
m a
|
|
9f9615a5cb3363a53f31a3e876d4250edcfdf2d618887c297e4f6d5ad79e785b | binaryage/chromex | terminal_private.clj | (ns chromex.ext.terminal-private
" * available since Chrome 36"
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro open-terminal-process
"Starts new process.
|process-name| - Name of the process to open. May be 'crosh' or 'vmshell'.
|args| - Command line arguments to pass to the process.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [id] where:
|id| - Id of the launched process.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([process-name args] (gen-call :function ::open-terminal-process &form process-name args))
([process-name] `(open-terminal-process ~process-name :omit)))
(defmacro open-vmshell-process
"Starts new vmshell process.
|args| - Command line arguments to pass to vmshell.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [id] where:
|id| - Id of the launched vmshell process.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([args] (gen-call :function ::open-vmshell-process &form args))
([] `(open-vmshell-process :omit)))
(defmacro close-terminal-process
"Closes previously opened process from either openTerminalProcess or openVmshellProcess.
|id| - Unique id of the process we want to close.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [success] where:
|success| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([id] (gen-call :function ::close-terminal-process &form id)))
(defmacro send-input
"Sends input that will be routed to stdin of the process with the specified id.
|id| - The id of the process to which we want to send input.
|input| - Input we are sending to the process.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [success] where:
|success| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([id input] (gen-call :function ::send-input &form id input)))
(defmacro on-terminal-resize
"Notify the process with the id id that terminal window size has changed.
|id| - The id of the process.
|width| - New window width (as column count).
|height| - New window height (as row count).
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [success] where:
|success| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([id width height] (gen-call :function ::on-terminal-resize &form id width height)))
(defmacro ack-output
"Called from |onProcessOutput| when the event is dispatched to terminal extension. Observing the terminal process output
will be paused after |onProcessOutput| is dispatched until this method is called.
|tab-id| - Tab ID from |onProcessOutput| event.
|id| - The id of the process to which |onProcessOutput| was dispatched."
([tab-id id] (gen-call :function ::ack-output &form tab-id id)))
(defmacro open-window
"Open the Terminal tabbed window.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::open-window &form)))
(defmacro open-options-page
"Open the Terminal Settings page.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::open-options-page &form)))
(defmacro get-settings
"Returns an object (DictionaryValue) containing UI settings such as font style and colors used by terminal and stored as a
syncable pref. The UI currently has ~70 properties and we wish to allow flexibility for these to change in the UI without
updating this API, so we allow any properties.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [settings] where:
|settings| - Settings from prefs.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-settings &form)))
(defmacro set-settings
"Sets terminal UI settings which are stored as a syncable pref.
|settings| - Settings to update into prefs.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([settings] (gen-call :function ::set-settings &form settings)))
(defmacro get-a11y-status
"Returns a boolean indicating whether the accessibility spoken feedback is on.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [a11y-status] where:
|a11y-status| - True if a11y spoken feedback is on.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-a11y-status &form)))
; -- events -----------------------------------------------------------------------------------------------------------------
;
; docs: /#tapping-events
(defmacro tap-on-process-output-events
"Fired when an opened process writes something to its output. Observing further process output will be blocked until
|ackOutput| for the terminal is called. Internally, first event argument will be ID of the tab that contains terminal
instance for which this event is intended. This argument will be stripped before passing the event to the extension.
Events will be put on the |channel| with signature [::on-process-output [id type text]] where:
|id| - Id of the process from which the output came.
|type| - Type of the output stream from which output came. When process exits, output type will be set to exit
|text| - Text that was written to the output stream.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-process-output &form channel args)))
(defmacro tap-on-settings-changed-events
"Fired when terminal UI settings change.
Events will be put on the |channel| with signature [::on-settings-changed [settings]] where:
|settings| - Terminal UI Settings with updated values.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-settings-changed &form channel args)))
(defmacro tap-on-a11y-status-changed-events
"Fired when a11y spoken feedback is enabled/disabled.
Events will be put on the |channel| with signature [::on-a11y-status-changed [status]] where:
|status| - True if a11y spoken feedback is on.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-a11y-status-changed &form channel args)))
; -- convenience ------------------------------------------------------------------------------------------------------------
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.ext.terminal-private namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
; ---------------------------------------------------------------------------------------------------------------------------
; -- API TABLE --------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------------
(def api-table
{:namespace "chrome.terminalPrivate",
:since "36",
:functions
[{:id ::open-terminal-process,
:name "openTerminalProcess",
:callback? true,
:params
[{:name "process-name", :type "string"}
{:name "args", :optional? true, :since "66", :type "[array-of-strings]"}
{:name "callback", :type :callback, :callback {:params [{:name "id", :type "string"}]}}]}
{:id ::open-vmshell-process,
:name "openVmshellProcess",
:since "82",
:callback? true,
:params
[{:name "args", :optional? true, :type "[array-of-strings]"}
{:name "callback", :type :callback, :callback {:params [{:name "id", :type "string"}]}}]}
{:id ::close-terminal-process,
:name "closeTerminalProcess",
:callback? true,
:params
[{:name "id", :since "74", :type "string"}
{:name "callback", :optional? true, :type :callback, :callback {:params [{:name "success", :type "boolean"}]}}]}
{:id ::send-input,
:name "sendInput",
:callback? true,
:params
[{:name "id", :since "74", :type "string"}
{:name "input", :type "string"}
{:name "callback", :optional? true, :type :callback, :callback {:params [{:name "success", :type "boolean"}]}}]}
{:id ::on-terminal-resize,
:name "onTerminalResize",
:callback? true,
:params
[{:name "id", :since "74", :type "string"}
{:name "width", :type "integer"}
{:name "height", :type "integer"}
{:name "callback", :optional? true, :type :callback, :callback {:params [{:name "success", :type "boolean"}]}}]}
{:id ::ack-output,
:name "ackOutput",
:since "49",
:params [{:name "tab-id", :type "integer"} {:name "id", :since "74", :type "string"}]}
{:id ::open-window, :name "openWindow", :since "84", :callback? true, :params [{:name "callback", :type :callback}]}
{:id ::open-options-page,
:name "openOptionsPage",
:since "84",
:callback? true,
:params [{:name "callback", :type :callback}]}
{:id ::get-settings,
:name "getSettings",
:since "80",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "settings", :type "object"}]}}]}
{:id ::set-settings,
:name "setSettings",
:since "80",
:callback? true,
:params [{:name "settings", :type "object"} {:name "callback", :type :callback}]}
{:id ::get-a11y-status,
:name "getA11yStatus",
:since "82",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "a11y-status", :type "boolean"}]}}]}],
:events
[{:id ::on-process-output,
:name "onProcessOutput",
:params
[{:name "id", :since "74", :type "string"}
{:name "type", :type "terminalPrivate.OutputType"}
{:name "text", :type "string"}]}
{:id ::on-settings-changed, :name "onSettingsChanged", :since "80", :params [{:name "settings", :type "object"}]}
{:id ::on-a11y-status-changed,
:name "onA11yStatusChanged",
:since "82",
:params [{:name "status", :type "boolean"}]}]})
; -- helpers ----------------------------------------------------------------------------------------------------------------
; code generation for native API wrapper
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
; code generation for API call-site
(def gen-call (partial gen-call-helper api-table)) | null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/exts_private/chromex/ext/terminal_private.clj | clojure | -- events -----------------------------------------------------------------------------------------------------------------
docs: /#tapping-events
-- convenience ------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- API TABLE --------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- helpers ----------------------------------------------------------------------------------------------------------------
code generation for native API wrapper
code generation for API call-site | (ns chromex.ext.terminal-private
" * available since Chrome 36"
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro open-terminal-process
"Starts new process.
|process-name| - Name of the process to open. May be 'crosh' or 'vmshell'.
|args| - Command line arguments to pass to the process.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [id] where:
|id| - Id of the launched process.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([process-name args] (gen-call :function ::open-terminal-process &form process-name args))
([process-name] `(open-terminal-process ~process-name :omit)))
(defmacro open-vmshell-process
"Starts new vmshell process.
|args| - Command line arguments to pass to vmshell.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [id] where:
|id| - Id of the launched vmshell process.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([args] (gen-call :function ::open-vmshell-process &form args))
([] `(open-vmshell-process :omit)))
(defmacro close-terminal-process
"Closes previously opened process from either openTerminalProcess or openVmshellProcess.
|id| - Unique id of the process we want to close.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [success] where:
|success| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([id] (gen-call :function ::close-terminal-process &form id)))
(defmacro send-input
"Sends input that will be routed to stdin of the process with the specified id.
|id| - The id of the process to which we want to send input.
|input| - Input we are sending to the process.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [success] where:
|success| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([id input] (gen-call :function ::send-input &form id input)))
(defmacro on-terminal-resize
"Notify the process with the id id that terminal window size has changed.
|id| - The id of the process.
|width| - New window width (as column count).
|height| - New window height (as row count).
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [success] where:
|success| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([id width height] (gen-call :function ::on-terminal-resize &form id width height)))
(defmacro ack-output
"Called from |onProcessOutput| when the event is dispatched to terminal extension. Observing the terminal process output
will be paused after |onProcessOutput| is dispatched until this method is called.
|tab-id| - Tab ID from |onProcessOutput| event.
|id| - The id of the process to which |onProcessOutput| was dispatched."
([tab-id id] (gen-call :function ::ack-output &form tab-id id)))
(defmacro open-window
"Open the Terminal tabbed window.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::open-window &form)))
(defmacro open-options-page
"Open the Terminal Settings page.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::open-options-page &form)))
(defmacro get-settings
"Returns an object (DictionaryValue) containing UI settings such as font style and colors used by terminal and stored as a
syncable pref. The UI currently has ~70 properties and we wish to allow flexibility for these to change in the UI without
updating this API, so we allow any properties.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [settings] where:
|settings| - Settings from prefs.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-settings &form)))
(defmacro set-settings
"Sets terminal UI settings which are stored as a syncable pref.
|settings| - Settings to update into prefs.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([settings] (gen-call :function ::set-settings &form settings)))
(defmacro get-a11y-status
"Returns a boolean indicating whether the accessibility spoken feedback is on.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [a11y-status] where:
|a11y-status| - True if a11y spoken feedback is on.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-a11y-status &form)))
(defmacro tap-on-process-output-events
"Fired when an opened process writes something to its output. Observing further process output will be blocked until
|ackOutput| for the terminal is called. Internally, first event argument will be ID of the tab that contains terminal
instance for which this event is intended. This argument will be stripped before passing the event to the extension.
Events will be put on the |channel| with signature [::on-process-output [id type text]] where:
|id| - Id of the process from which the output came.
|type| - Type of the output stream from which output came. When process exits, output type will be set to exit
|text| - Text that was written to the output stream.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-process-output &form channel args)))
(defmacro tap-on-settings-changed-events
"Fired when terminal UI settings change.
Events will be put on the |channel| with signature [::on-settings-changed [settings]] where:
|settings| - Terminal UI Settings with updated values.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-settings-changed &form channel args)))
(defmacro tap-on-a11y-status-changed-events
"Fired when a11y spoken feedback is enabled/disabled.
Events will be put on the |channel| with signature [::on-a11y-status-changed [status]] where:
|status| - True if a11y spoken feedback is on.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-a11y-status-changed &form channel args)))
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.ext.terminal-private namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
(def api-table
{:namespace "chrome.terminalPrivate",
:since "36",
:functions
[{:id ::open-terminal-process,
:name "openTerminalProcess",
:callback? true,
:params
[{:name "process-name", :type "string"}
{:name "args", :optional? true, :since "66", :type "[array-of-strings]"}
{:name "callback", :type :callback, :callback {:params [{:name "id", :type "string"}]}}]}
{:id ::open-vmshell-process,
:name "openVmshellProcess",
:since "82",
:callback? true,
:params
[{:name "args", :optional? true, :type "[array-of-strings]"}
{:name "callback", :type :callback, :callback {:params [{:name "id", :type "string"}]}}]}
{:id ::close-terminal-process,
:name "closeTerminalProcess",
:callback? true,
:params
[{:name "id", :since "74", :type "string"}
{:name "callback", :optional? true, :type :callback, :callback {:params [{:name "success", :type "boolean"}]}}]}
{:id ::send-input,
:name "sendInput",
:callback? true,
:params
[{:name "id", :since "74", :type "string"}
{:name "input", :type "string"}
{:name "callback", :optional? true, :type :callback, :callback {:params [{:name "success", :type "boolean"}]}}]}
{:id ::on-terminal-resize,
:name "onTerminalResize",
:callback? true,
:params
[{:name "id", :since "74", :type "string"}
{:name "width", :type "integer"}
{:name "height", :type "integer"}
{:name "callback", :optional? true, :type :callback, :callback {:params [{:name "success", :type "boolean"}]}}]}
{:id ::ack-output,
:name "ackOutput",
:since "49",
:params [{:name "tab-id", :type "integer"} {:name "id", :since "74", :type "string"}]}
{:id ::open-window, :name "openWindow", :since "84", :callback? true, :params [{:name "callback", :type :callback}]}
{:id ::open-options-page,
:name "openOptionsPage",
:since "84",
:callback? true,
:params [{:name "callback", :type :callback}]}
{:id ::get-settings,
:name "getSettings",
:since "80",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "settings", :type "object"}]}}]}
{:id ::set-settings,
:name "setSettings",
:since "80",
:callback? true,
:params [{:name "settings", :type "object"} {:name "callback", :type :callback}]}
{:id ::get-a11y-status,
:name "getA11yStatus",
:since "82",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "a11y-status", :type "boolean"}]}}]}],
:events
[{:id ::on-process-output,
:name "onProcessOutput",
:params
[{:name "id", :since "74", :type "string"}
{:name "type", :type "terminalPrivate.OutputType"}
{:name "text", :type "string"}]}
{:id ::on-settings-changed, :name "onSettingsChanged", :since "80", :params [{:name "settings", :type "object"}]}
{:id ::on-a11y-status-changed,
:name "onA11yStatusChanged",
:since "82",
:params [{:name "status", :type "boolean"}]}]})
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
(def gen-call (partial gen-call-helper api-table)) |
bf61060ff1de84fb4f2fa8eb3e49ecd0b2904a45e9ae01ee056c9cf26be4557d | jackrusher/geometer | lsystem.cljs | (ns geometer.lsystem
(:require [geometer.turtle :as t]))
This is an example of a classic string re - writing L - System
;; implemented in terms of geometer's 3D turtle. It's included here
;; for completeness, but I personally find coding directly to the
;; turtle using functions to represent rules and higher order
;; functions (map, reduce, &c) to handle recursion much clearer and
;; more satisfying.
;;
;; See: geometer.turtle/plant for an example.
(defn expand-l-system
"Recursively expand a L-System grammar into a sequence of operations."
[rules curr-state depth]
(if (zero? depth)
curr-state
(mapcat #(expand-l-system rules (rules % [%]) (dec depth)) curr-state)))
(defn l-system-to-turtle
"Convert a series of L-System single-letter rules into a "
[length-fn angle-fn grow-fn rules]
(concat [length-fn angle-fn]
(map #(case %
\F grow-fn
\f t/tz
\C t/center
\+ t/ry
\- t/ry-
\& t/rx
\^ t/rx-
\\ t/rz
\/ t/rz-)
rules)))
(defn koch
"Returns a mesh generated by an L-System that produces 3D version of a modified Koch curve."
[]
(->> (expand-l-system {\F "FF-F-F&F-F-F+F"} "F" 2)
(l-system-to-turtle (t/length 4) (t/angle 90) t/cylinder)
t/turtle-mesh))
| null | https://raw.githubusercontent.com/jackrusher/geometer/b854b1d8d2f097d0be29499b1926a664754b516c/src/cljs/geometer/lsystem.cljs | clojure | implemented in terms of geometer's 3D turtle. It's included here
for completeness, but I personally find coding directly to the
turtle using functions to represent rules and higher order
functions (map, reduce, &c) to handle recursion much clearer and
more satisfying.
See: geometer.turtle/plant for an example. | (ns geometer.lsystem
(:require [geometer.turtle :as t]))
This is an example of a classic string re - writing L - System
(defn expand-l-system
"Recursively expand a L-System grammar into a sequence of operations."
[rules curr-state depth]
(if (zero? depth)
curr-state
(mapcat #(expand-l-system rules (rules % [%]) (dec depth)) curr-state)))
(defn l-system-to-turtle
"Convert a series of L-System single-letter rules into a "
[length-fn angle-fn grow-fn rules]
(concat [length-fn angle-fn]
(map #(case %
\F grow-fn
\f t/tz
\C t/center
\+ t/ry
\- t/ry-
\& t/rx
\^ t/rx-
\\ t/rz
\/ t/rz-)
rules)))
(defn koch
"Returns a mesh generated by an L-System that produces 3D version of a modified Koch curve."
[]
(->> (expand-l-system {\F "FF-F-F&F-F-F+F"} "F" 2)
(l-system-to-turtle (t/length 4) (t/angle 90) t/cylinder)
t/turtle-mesh))
|
2d4fd82b2e9a99ff11ff911377440b9799d0c0af8f929dea290ec0958739c614 | gpwwjr/LISA | mycin.lisp | This file is part of LISA , the Lisp - based Intelligent Software
;;; Agents platform.
Copyright ( C ) 2000
;;; 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. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
;;; File: mycin.lisp
Description : An implementation of MYCIN as illustrated in PAIP , pg . 553 . The example
is used to illustrate ( and test ) Lisa 's new support for certainty factors . I did n't do
a faithful port of the PAIP version ; in particular , there 's no interaction with the
operator right now . However , all rules are present and the two scenarios on pgs . 555 and
556 are represented ( by the functions CULTURE-1 and CULTURE-2 ) .
$ I d : mycin.lisp , v 1.8 2006/04/14 16:49:32 youngde Exp $
(in-package :lisa-user)
(clear)
(setf lisa::*allow-duplicate-facts* nil)
(defclass param-mixin ()
((value :initarg :value
:initform nil
:reader value)
(entity :initarg :entity
:initform nil
:reader entity)))
(defclass culture () ())
(defclass culture-site (param-mixin) ())
(defclass culture-age (param-mixin) ())
(defclass patient ()
((name :initarg :name
:initform nil
:reader name)
(sex :initarg :sex
:initform nil
:reader sex)
(age :initarg :age
:initform nil
:reader age)))
(defclass burn (param-mixin) ())
(defclass compromised-host (param-mixin) ())
(defclass organism () ())
(defclass gram (param-mixin) ())
(defclass morphology (param-mixin) ())
(defclass aerobicity (param-mixin) ())
(defclass growth-conformation (param-mixin) ())
(defclass organism-identity (param-mixin) ())
(defrule rule-52 (:belief 0.4)
(culture-site (value blood))
(gram (value neg) (entity ?organism))
(morphology (value rod))
(burn (value serious))
=>
(assert (organism-identity (value pseudomonas) (entity ?organism))))
(defrule rule-71 (:belief 0.7)
(gram (value pos) (entity ?organism))
(morphology (value coccus))
(growth-conformation (value clumps))
=>
(assert (organism-identity (value staphylococcus) (entity ?organism))))
(defrule rule-73 (:belief 0.9)
(culture-site (value blood))
(gram (value neg) (entity ?organism))
(morphology (value rod))
(aerobicity (value anaerobic))
=>
(assert (organism-identity (value bacteroides) (entity ?organism))))
(defrule rule-75 (:belief 0.6)
(gram (value neg) (entity ?organism))
(morphology (value rod))
(compromised-host (value t))
=>
(assert (organism-identity (value pseudomonas) (entity ?organism))))
(defrule rule-107 (:belief 0.8)
(gram (value neg) (organism ?organism))
(morphology (value rod))
(aerobicity (value aerobic))
=>
(assert (organism-identity (value enterobacteriaceae) (entity ?organism))))
(defrule rule-165 (:belief 0.7)
(gram (value pos) (entity ?organism))
(morphology (value coccus))
(growth-conformation (value chains))
=>
(assert (organism-identity (value streptococcus) (entity ?organism))))
(defrule conclusion (:salience -10)
(?identity (organism-identity (value ?value)))
=>
(format t "Identity: ~A (~,3F)~%" ?value (belief:belief-factor ?identity)))
(defun culture-1 (&key (runp t))
(reset)
(let ((?organism (make-instance 'organism))
(?patient (make-instance 'patient
:name "Sylvia Fischer"
:sex 'female
:age 27)))
(assert (compromised-host (value t) (entity ?patient)))
(assert (burn (value serious) (entity ?patient)))
(assert (culture-site (value blood)))
(assert (culture-age (value 3)))
(assert (gram (value neg) (entity ?organism)))
(assert (morphology (value rod) (entity ?organism)))
(assert (aerobicity (value aerobic) (entity ?organism)))
(when runp
(run))))
(defun culture-2 (&key (runp t))
(reset)
(let ((?organism (make-instance 'organism))
(?patient (make-instance 'patient
:name "Sylvia Fischer"
:sex 'female
:age 27)))
(assert (compromised-host (value t) (entity ?patient)))
(assert (burn (value serious) (entity ?patient)))
(assert (culture-site (value blood)))
(assert (culture-age (value 3)))
(assert (gram (value neg) (entity ?organism)) :belief 0.8)
(assert (gram (value pos) (entity ?organism)) :belief 0.2)
(assert (morphology (value rod) (entity ?organism)))
(assert (aerobicity (value anaerobic) (entity ?organism)))
(when runp
(run))))
| null | https://raw.githubusercontent.com/gpwwjr/LISA/bc7f54b3a9b901d5648d7e9de358e29d3b794c78/misc/mycin.lisp | lisp | Agents platform.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
either version 2.1
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
along with this library; if not, write to the Free Software
File: mycin.lisp
in particular , there 's no interaction with the | This file is part of LISA , the Lisp - based Intelligent Software
Copyright ( C ) 2000
of the License , or ( at your option ) any later version .
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
Description : An implementation of MYCIN as illustrated in PAIP , pg . 553 . The example
is used to illustrate ( and test ) Lisa 's new support for certainty factors . I did n't do
operator right now . However , all rules are present and the two scenarios on pgs . 555 and
556 are represented ( by the functions CULTURE-1 and CULTURE-2 ) .
$ I d : mycin.lisp , v 1.8 2006/04/14 16:49:32 youngde Exp $
(in-package :lisa-user)
(clear)
(setf lisa::*allow-duplicate-facts* nil)
(defclass param-mixin ()
((value :initarg :value
:initform nil
:reader value)
(entity :initarg :entity
:initform nil
:reader entity)))
(defclass culture () ())
(defclass culture-site (param-mixin) ())
(defclass culture-age (param-mixin) ())
(defclass patient ()
((name :initarg :name
:initform nil
:reader name)
(sex :initarg :sex
:initform nil
:reader sex)
(age :initarg :age
:initform nil
:reader age)))
(defclass burn (param-mixin) ())
(defclass compromised-host (param-mixin) ())
(defclass organism () ())
(defclass gram (param-mixin) ())
(defclass morphology (param-mixin) ())
(defclass aerobicity (param-mixin) ())
(defclass growth-conformation (param-mixin) ())
(defclass organism-identity (param-mixin) ())
(defrule rule-52 (:belief 0.4)
(culture-site (value blood))
(gram (value neg) (entity ?organism))
(morphology (value rod))
(burn (value serious))
=>
(assert (organism-identity (value pseudomonas) (entity ?organism))))
(defrule rule-71 (:belief 0.7)
(gram (value pos) (entity ?organism))
(morphology (value coccus))
(growth-conformation (value clumps))
=>
(assert (organism-identity (value staphylococcus) (entity ?organism))))
(defrule rule-73 (:belief 0.9)
(culture-site (value blood))
(gram (value neg) (entity ?organism))
(morphology (value rod))
(aerobicity (value anaerobic))
=>
(assert (organism-identity (value bacteroides) (entity ?organism))))
(defrule rule-75 (:belief 0.6)
(gram (value neg) (entity ?organism))
(morphology (value rod))
(compromised-host (value t))
=>
(assert (organism-identity (value pseudomonas) (entity ?organism))))
(defrule rule-107 (:belief 0.8)
(gram (value neg) (organism ?organism))
(morphology (value rod))
(aerobicity (value aerobic))
=>
(assert (organism-identity (value enterobacteriaceae) (entity ?organism))))
(defrule rule-165 (:belief 0.7)
(gram (value pos) (entity ?organism))
(morphology (value coccus))
(growth-conformation (value chains))
=>
(assert (organism-identity (value streptococcus) (entity ?organism))))
(defrule conclusion (:salience -10)
(?identity (organism-identity (value ?value)))
=>
(format t "Identity: ~A (~,3F)~%" ?value (belief:belief-factor ?identity)))
(defun culture-1 (&key (runp t))
(reset)
(let ((?organism (make-instance 'organism))
(?patient (make-instance 'patient
:name "Sylvia Fischer"
:sex 'female
:age 27)))
(assert (compromised-host (value t) (entity ?patient)))
(assert (burn (value serious) (entity ?patient)))
(assert (culture-site (value blood)))
(assert (culture-age (value 3)))
(assert (gram (value neg) (entity ?organism)))
(assert (morphology (value rod) (entity ?organism)))
(assert (aerobicity (value aerobic) (entity ?organism)))
(when runp
(run))))
(defun culture-2 (&key (runp t))
(reset)
(let ((?organism (make-instance 'organism))
(?patient (make-instance 'patient
:name "Sylvia Fischer"
:sex 'female
:age 27)))
(assert (compromised-host (value t) (entity ?patient)))
(assert (burn (value serious) (entity ?patient)))
(assert (culture-site (value blood)))
(assert (culture-age (value 3)))
(assert (gram (value neg) (entity ?organism)) :belief 0.8)
(assert (gram (value pos) (entity ?organism)) :belief 0.2)
(assert (morphology (value rod) (entity ?organism)))
(assert (aerobicity (value anaerobic) (entity ?organism)))
(when runp
(run))))
|
19a7a25d89e4d1fa0ef4e52896db7859396fdf7c4aaec17b29c4b2893b042976 | ryszard/Cl-Couch | conditions.lisp | (in-package :cl-couchdb-client)
(export '(couchdb-condition couchdb-server-error couchdb-conflict couchdb-not-found old-doc-of new-doc-of))
(defcondition* couchdb-condition ()
(number
error
reason)
(:report (lambda (con s)
(format s "CouchDB returned an error: ~a (~a). Reason: ~a." (error-of con) (number-of con) (reason-of con)))))
(defcondition* couchdb-not-found (couchdb-condition)
()
(:documentation "404"))
(defcondition* couchdb-conflict (couchdb-condition)
((old-doc nil)
(new-doc nil)
server
db
(number 412))
(:documentation "412")
(:report (lambda (con s)
(format s "CouchDB returned an error: ~a (~a). Reason: ~a in \"http://~a/~a\".~%~%Document in database~%~%~s~%~%Conflicts with:~%~s"
(error-of con)
(number-of con)
(reason-of con)
(server-of con)
(db-of con)
(old-doc-of con)
(new-doc-of con)))))
(defcondition* couchdb-server-error (couchdb-condition)
()
(:documentation "50x errors."))
Copyright ( C ) 2008
< >
;; This software is provided 'as-is', without any express or implied
;; warranty. In no event will the authors be held liable for any
;; damages arising from the use of this software.
;; Permission is granted to anyone to use this software for any
;; purpose, including commercial applications, and to alter it and
;; redistribute it freely, subject to the following restrictions:
1 . The origin of this software must not be misrepresented ; you must
;; not claim that you wrote the original software. If you use this
;; software in a product, an acknowledgment in the product
;; documentation would be appreciated but is not required.
2 . Altered source versions must be plainly marked as such , and must
;; not be misrepresented as being the original software.
3 . This notice may not be removed or altered from any source
;; distribution. | null | https://raw.githubusercontent.com/ryszard/Cl-Couch/de6900e38395dac3ddce53876b05d5e24c8d8f52/client/conditions.lisp | lisp | This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
not be misrepresented as being the original software.
distribution. | (in-package :cl-couchdb-client)
(export '(couchdb-condition couchdb-server-error couchdb-conflict couchdb-not-found old-doc-of new-doc-of))
(defcondition* couchdb-condition ()
(number
error
reason)
(:report (lambda (con s)
(format s "CouchDB returned an error: ~a (~a). Reason: ~a." (error-of con) (number-of con) (reason-of con)))))
(defcondition* couchdb-not-found (couchdb-condition)
()
(:documentation "404"))
(defcondition* couchdb-conflict (couchdb-condition)
((old-doc nil)
(new-doc nil)
server
db
(number 412))
(:documentation "412")
(:report (lambda (con s)
(format s "CouchDB returned an error: ~a (~a). Reason: ~a in \"http://~a/~a\".~%~%Document in database~%~%~s~%~%Conflicts with:~%~s"
(error-of con)
(number-of con)
(reason-of con)
(server-of con)
(db-of con)
(old-doc-of con)
(new-doc-of con)))))
(defcondition* couchdb-server-error (couchdb-condition)
()
(:documentation "50x errors."))
Copyright ( C ) 2008
< >
2 . Altered source versions must be plainly marked as such , and must
3 . This notice may not be removed or altered from any source |
a5d302f0d43e6aa18c4c61a59210180d8792ae586048a1fd66a0971a8608e383 | openmusic-project/OMChroma | formant-data.lisp | ;=====================================================
; CHROMA
;=====================================================
part of the OMChroma library
- > High - level control of sound synthesis in OM
;=====================================================
;
;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.
;
;See file LICENSE for further informations on licensing terms.
;
;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.
;
;=====================================================
to deal with data from formant analysis ( from AudioSculpt )
;internal format (data) = ((n t)(1 f1 amp1 bw1)...(n fn ampn bwn))
(in-package :cr)
(defclass formant-data (additive-data)
()
(:documentation "Formant analysis data in Ram"))
(defmethod initialize-instance :after ((x formant-data) &rest initargs &key file)
(declare (ignore initargs))
(setf (data x) (load-formant-file file)))
(defun load-formant-file (&optional file)
(if (null file) (setf file (choose-file-dialog)))
(format t "LOADING Formant DATA FROM ~a~%" file)
(let ((curr-list nil)
(result '(x))
(result2 nil)
(truc nil)
(n 0)
(time 0))
(with-open-file (in-stream file :direction :input)
(loop while (not truc)
do (multiple-value-bind(s tr)(read-line in-stream nil)
(setf truc tr)
(setf curr-list
(read-from-string (concatenate 'string "(" s ")")))
(case (length curr-list)
(1 (progn (if (get-gbl 'CTL2-PRINT) (format t "~a~%" curr-list))
(setf time (car curr-list))))
(3 (let ((freq (second curr-list))
(amp (dbtolin (first curr-list)))
(bw (third curr-list)))
(unless (= 0 time)
(progn (push (nreverse result) result2)
(setf result nil n 0)(push time result)
(setf time 0)))
(push (list (incf n) freq amp bw) result))))))
(push (nreverse result) result2)
(nombre-de-formants (cdr (nreverse result2))))
))
(defun nombre-de-formants (l)
(loop for i in l collect (cons (list (1-(length i))(car i)) (cdr i))))
( nombre - de - formants ' ( ( 1 ( 1 2)(3 4))(5 ( 12 13)(14 15)(200 200 ) ) ) )
| null | https://raw.githubusercontent.com/openmusic-project/OMChroma/5ded34f22b59a1a93ea7b87e182c9dbdfa95e047/sources/chroma/models/formant-data.lisp | lisp | =====================================================
CHROMA
=====================================================
=====================================================
This program is free software; you can redistribute it and/or
either version 2
of the License, or (at your option) any later version.
See file LICENSE for further informations on licensing terms.
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.
=====================================================
internal format (data) = ((n t)(1 f1 amp1 bw1)...(n fn ampn bwn)) | part of the OMChroma library
- > High - level control of sound synthesis in OM
modify it under the terms of the GNU General Public License
to deal with data from formant analysis ( from AudioSculpt )
(in-package :cr)
(defclass formant-data (additive-data)
()
(:documentation "Formant analysis data in Ram"))
(defmethod initialize-instance :after ((x formant-data) &rest initargs &key file)
(declare (ignore initargs))
(setf (data x) (load-formant-file file)))
(defun load-formant-file (&optional file)
(if (null file) (setf file (choose-file-dialog)))
(format t "LOADING Formant DATA FROM ~a~%" file)
(let ((curr-list nil)
(result '(x))
(result2 nil)
(truc nil)
(n 0)
(time 0))
(with-open-file (in-stream file :direction :input)
(loop while (not truc)
do (multiple-value-bind(s tr)(read-line in-stream nil)
(setf truc tr)
(setf curr-list
(read-from-string (concatenate 'string "(" s ")")))
(case (length curr-list)
(1 (progn (if (get-gbl 'CTL2-PRINT) (format t "~a~%" curr-list))
(setf time (car curr-list))))
(3 (let ((freq (second curr-list))
(amp (dbtolin (first curr-list)))
(bw (third curr-list)))
(unless (= 0 time)
(progn (push (nreverse result) result2)
(setf result nil n 0)(push time result)
(setf time 0)))
(push (list (incf n) freq amp bw) result))))))
(push (nreverse result) result2)
(nombre-de-formants (cdr (nreverse result2))))
))
(defun nombre-de-formants (l)
(loop for i in l collect (cons (list (1-(length i))(car i)) (cdr i))))
( nombre - de - formants ' ( ( 1 ( 1 2)(3 4))(5 ( 12 13)(14 15)(200 200 ) ) ) )
|
ca5f7ddb3b9c5972ca3fb082395d8cc74d1e92f23b700e7897e603d46bc994fa | sqor/riak-tools | riak_plugin.erl | -module(riak_plugin).
-compile(export_all).
%-export([postcommit_s3/1]).
-include_lib("riak_plugin.hrl").
configure() ->
erlcloud_s3:configure(?ACCESS_KEY, ?SECRET_ACCESS_KEY).
crdt_key_value(RObj) ->
Key = riak_object:key(RObj),
{map,V1} = riak_kv_crdt:value(RObj),
V2 = [{X,Y} || {{X,_Z},Y} <- V1],
V3 = jsx:encode(V2),
{Key, V3}.
basic_key_value(RObj) ->
Key = riak_object:key(RObj),
Value = riak_object:get_value(RObj),
{Key, Value}.
postcommit_s3(RObj) ->
lager:error("postcommit_s3: ~p~n", [RObj]),
case riak_kv_crdt:is_crdt(RObj) of
true ->
{Key,Value} = crdt_key_value(RObj),
s3_write(Key, Value),
RObj;
false ->
{Key,Value} = basic_key_value(RObj),
s3_write(Key, Value),
RObj
end.
s3_write(Key, Value) ->
KeyList = binary_to_list(Key),
A = erlcloud_s3:configure(?ACCESS_KEY, ?SECRET_ACCESS_KEY),
lager:error("~p:~p Settng up AWS ~p to S3 ~n", [?MODULE, ?LINE, A]),
%R = erlcloud_s3:put_object(?BUCKET, Key, Value, [], [{"Content-type", "application/x-gzip"}]),
R = erlcloud_s3:put_object(?BUCKET, KeyList, Value),
lager:error("postcommit_s3 s3_write is complete: Key= ~p, R= ~p ~n", [Key, R]),
{ok, R}.
%% ----------------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/sqor/riak-tools/1d6c964bf789711534f078ba8c8a600a6ab4eda3/plugins/src/riak_plugin.erl | erlang | -export([postcommit_s3/1]).
R = erlcloud_s3:put_object(?BUCKET, Key, Value, [], [{"Content-type", "application/x-gzip"}]),
---------------------------------------------------------------------------------------- | -module(riak_plugin).
-compile(export_all).
-include_lib("riak_plugin.hrl").
configure() ->
erlcloud_s3:configure(?ACCESS_KEY, ?SECRET_ACCESS_KEY).
crdt_key_value(RObj) ->
Key = riak_object:key(RObj),
{map,V1} = riak_kv_crdt:value(RObj),
V2 = [{X,Y} || {{X,_Z},Y} <- V1],
V3 = jsx:encode(V2),
{Key, V3}.
basic_key_value(RObj) ->
Key = riak_object:key(RObj),
Value = riak_object:get_value(RObj),
{Key, Value}.
postcommit_s3(RObj) ->
lager:error("postcommit_s3: ~p~n", [RObj]),
case riak_kv_crdt:is_crdt(RObj) of
true ->
{Key,Value} = crdt_key_value(RObj),
s3_write(Key, Value),
RObj;
false ->
{Key,Value} = basic_key_value(RObj),
s3_write(Key, Value),
RObj
end.
s3_write(Key, Value) ->
KeyList = binary_to_list(Key),
A = erlcloud_s3:configure(?ACCESS_KEY, ?SECRET_ACCESS_KEY),
lager:error("~p:~p Settng up AWS ~p to S3 ~n", [?MODULE, ?LINE, A]),
R = erlcloud_s3:put_object(?BUCKET, KeyList, Value),
lager:error("postcommit_s3 s3_write is complete: Key= ~p, R= ~p ~n", [Key, R]),
{ok, R}.
|
af4910b2544593b9751d48b23d46ce748842ec22910ac773e3ba0af3d50bb434 | jeromesimeon/Galax | resolve_stream_context.mli | (***********************************************************************)
(* *)
(* GALAX *)
(* XQuery Engine *)
(* *)
Copyright 2001 - 2007 .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ I d : resolve_stream_context.mli , v 1.7 2007/08/17 18:28:54 simeon Exp $
(* Module: Type_stream_context
Description:
This module implements a the loading context.
*)
(*****************************)
(* A type for the ts context *)
(*****************************)
type ts_context
(****************************)
(* Creates a new ts context *)
(****************************)
val build_ts_context : unit -> ts_context
(***************************)
(* Accesses the ts context *)
(***************************)
val get_nsenv : ts_context -> Namespace_context.nsenv
val pop_nsenv : ts_context -> unit
(*********************************************)
(* Adds namespace bindings to the ts context *)
(*********************************************)
val push_ns_bindings : ts_context -> Namespace_context.binding_table -> unit
val resolve_element_name : ts_context -> Namespace_context.nsenv -> Namespace_names.uqname -> Namespace_symbols.symbol * bool
val resolve_attribute_name : ts_context -> Namespace_context.nsenv -> Namespace_names.uqname -> Namespace_symbols.symbol
val attr_lookup_count : int ref
val attr_missed_lookup_count : int ref
| null | https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/streaming/resolve_stream_context.mli | ocaml | *********************************************************************
GALAX
XQuery Engine
Distributed only by permission.
*********************************************************************
Module: Type_stream_context
Description:
This module implements a the loading context.
***************************
A type for the ts context
***************************
**************************
Creates a new ts context
**************************
*************************
Accesses the ts context
*************************
*******************************************
Adds namespace bindings to the ts context
******************************************* | Copyright 2001 - 2007 .
$ I d : resolve_stream_context.mli , v 1.7 2007/08/17 18:28:54 simeon Exp $
type ts_context
val build_ts_context : unit -> ts_context
val get_nsenv : ts_context -> Namespace_context.nsenv
val pop_nsenv : ts_context -> unit
val push_ns_bindings : ts_context -> Namespace_context.binding_table -> unit
val resolve_element_name : ts_context -> Namespace_context.nsenv -> Namespace_names.uqname -> Namespace_symbols.symbol * bool
val resolve_attribute_name : ts_context -> Namespace_context.nsenv -> Namespace_names.uqname -> Namespace_symbols.symbol
val attr_lookup_count : int ref
val attr_missed_lookup_count : int ref
|
d93e3598cf9124fce4578f2c69ff66377b15a612a0ef2cd2e563a128cb42bab5 | aspiwack/porcupine | FunflowRemoteCache.hs | {-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
module Data.Locations.FunflowRemoteCache
( locationCacher
, LiftCacher(..)
) where
import Control.Exception.Safe
import Control.Funflow.ContentHashable (ContentHash, hashToPath)
import qualified Control.Funflow.RemoteCache as Remote
import Control.Lens
import Control.Monad.Trans
import Data.Bifunctor (first)
import Data.Locations.Accessors
import Data.Locations.Loc
import Katip
import Path (toFilePath)
import System.FilePath (dropTrailingPathSeparator)
hashToFilePath :: ContentHash -> FilePath
hashToFilePath = dropTrailingPathSeparator . toFilePath . hashToPath
newtype LocationCacher m = LocationCacher (SomeLoc m)
tryS :: (MonadCatch m) => m a -> m (Either String a)
tryS = fmap (over _Left (displayException :: SomeException -> String)) . try
instance (KatipContext m)
=> Remote.Cacher m (LocationCacher m) where
push (LocationCacher (SomeGLoc rootLoc)) = Remote.pushAsArchive aliasPath $ \hash body -> do
let loc = rootLoc `addSubdirToLoc` hashToFilePath hash
katipAddNamespace "remoteCacher" $ logFM DebugS $ logStr $
"Writing to file " ++ show loc
writeLazyByte loc body
pure Remote.PushOK
where
aliasPath from_ to_ = first show <$> tryS
(copy
(rootLoc `addSubdirToLoc` hashToFilePath from_)
(rootLoc `addSubdirToLoc` hashToFilePath to_))
pull (LocationCacher (SomeGLoc rootLoc)) = Remote.pullAsArchive $ \hash ->
katipAddNamespace "remoteCacher" $ do
let loc = rootLoc `addSubdirToLoc` hashToFilePath hash
readResult <- tryS $ readLazyByte loc
case readResult of
Right bs -> do
logFM DebugS $ logStr $ "Found in remote cache " ++ show loc
return $ Remote.PullOK bs
Left err -> do
katipAddContext (sl "errorFromRemoteCache" err) $
logFM DebugS $ logStr $ "Not in remote cache " ++ show loc
return $ Remote.PullError err
locationCacher :: Maybe (SomeLoc m) -> Maybe (LocationCacher m)
locationCacher = fmap LocationCacher
newtype LiftCacher cacher = LiftCacher cacher
instance (MonadTrans t, Remote.Cacher m cacher, Monad (t m)) =>
Remote.Cacher (t m) (LiftCacher cacher) where
push (LiftCacher c) hash hash2 path = lift $ Remote.push c hash hash2 path
pull (LiftCacher c) hash path = lift $ Remote.pull c hash path
| null | https://raw.githubusercontent.com/aspiwack/porcupine/23dcba1523626af0fdf6085f4107987d4bf718d7/porcupine-core/src/Data/Locations/FunflowRemoteCache.hs | haskell | # LANGUAGE FlexibleContexts # | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
module Data.Locations.FunflowRemoteCache
( locationCacher
, LiftCacher(..)
) where
import Control.Exception.Safe
import Control.Funflow.ContentHashable (ContentHash, hashToPath)
import qualified Control.Funflow.RemoteCache as Remote
import Control.Lens
import Control.Monad.Trans
import Data.Bifunctor (first)
import Data.Locations.Accessors
import Data.Locations.Loc
import Katip
import Path (toFilePath)
import System.FilePath (dropTrailingPathSeparator)
hashToFilePath :: ContentHash -> FilePath
hashToFilePath = dropTrailingPathSeparator . toFilePath . hashToPath
newtype LocationCacher m = LocationCacher (SomeLoc m)
tryS :: (MonadCatch m) => m a -> m (Either String a)
tryS = fmap (over _Left (displayException :: SomeException -> String)) . try
instance (KatipContext m)
=> Remote.Cacher m (LocationCacher m) where
push (LocationCacher (SomeGLoc rootLoc)) = Remote.pushAsArchive aliasPath $ \hash body -> do
let loc = rootLoc `addSubdirToLoc` hashToFilePath hash
katipAddNamespace "remoteCacher" $ logFM DebugS $ logStr $
"Writing to file " ++ show loc
writeLazyByte loc body
pure Remote.PushOK
where
aliasPath from_ to_ = first show <$> tryS
(copy
(rootLoc `addSubdirToLoc` hashToFilePath from_)
(rootLoc `addSubdirToLoc` hashToFilePath to_))
pull (LocationCacher (SomeGLoc rootLoc)) = Remote.pullAsArchive $ \hash ->
katipAddNamespace "remoteCacher" $ do
let loc = rootLoc `addSubdirToLoc` hashToFilePath hash
readResult <- tryS $ readLazyByte loc
case readResult of
Right bs -> do
logFM DebugS $ logStr $ "Found in remote cache " ++ show loc
return $ Remote.PullOK bs
Left err -> do
katipAddContext (sl "errorFromRemoteCache" err) $
logFM DebugS $ logStr $ "Not in remote cache " ++ show loc
return $ Remote.PullError err
locationCacher :: Maybe (SomeLoc m) -> Maybe (LocationCacher m)
locationCacher = fmap LocationCacher
newtype LiftCacher cacher = LiftCacher cacher
instance (MonadTrans t, Remote.Cacher m cacher, Monad (t m)) =>
Remote.Cacher (t m) (LiftCacher cacher) where
push (LiftCacher c) hash hash2 path = lift $ Remote.push c hash hash2 path
pull (LiftCacher c) hash path = lift $ Remote.pull c hash path
|
1ea8c5ce578731f0ae533fe42ce8d27ea7d6ef418ff1653c0b2e4aa28b319b59 | racket/scribble | output.rkt | #lang racket/base
(require racket/promise
racket/contract/base)
(provide
special?
outputable/c
(contract-out
[output (->* (outputable/c) (output-port?) void?)]))
;; See also `provide-special` below
;; Outputs values for the `scribble/text' language:
;; - several atomic values are printed as in `display',
;; - promises, thunks, and boxes are indirections for the value they contain
;; (useful in various cases),
;; - some "special" values are used for controlling output (eg, flushing,
;; prefix changes, etc),
;; - specifically, `block's delimit indentation levels, `splice's do not,
;; - lists (more generally, pairs) are like either one depending on the context
;; (same as blocks/splices when inside a `block'/`splice'), at the toplevel
;; they default to blocks.
;;
;; Uses global state because `output' is wrapped around each expression in a
;; scribble/text file so this is much more convenient than wrapping the whole
;; module's body in a `list' (which will be difficult with definitions etc).
;; The state is a pair of prefixes -- one that is the prefix for the current
;; value (which gets extended with nested blocks), and the other is the prefix
;; for the current "line" (which is reset after a newline). The line-prefix is
;; needed because a line can hold a block, which means that the line-prefix
;; will apply for the contents of the block including newlines in it. This
;; state is associated with a port via a hash table. Another state that is
;; used is the port's column position, which is maintained by the system (when
;; line counts are enabled) -- this is used to tell what part of a prefix is
;; already displayed.
;;
;; Each prefix is either an integer (for a number of spaces) or a string. The
;; prefix mechanism can be disabled by using #f for the global prefix, and in
this case the line prefix can have ( cons ) so it can be restored --
;; used by `disable-prefix' and `restore-prefix' resp. (This is different from
;; a 0 prefix -- #f means that no prefix will be accumulated).
;;
(define (output x [p (current-output-port)])
;; these are the global prefix and the one that is local to the current line
(define pfxs (port->state p))
;; the current mode for lists
(define list=block? #t)
;; the low-level string output function (can change with `with-writer')
(define write write-string)
;; to get the output column
(define (getcol) (let-values ([(line col pos) (port-next-location p)]) col))
total size of the two prefixes
(define (2pfx-length pfx1 pfx2)
(if (and pfx1 pfx2)
(+ (if (number? pfx1) pfx1 (string-length pfx1))
(if (number? pfx2) pfx2 (string-length pfx2)))
0))
;; combines a prefix with a target column to get to
(define (pfx+col pfx)
(and pfx (let ([col (getcol)])
(cond [(number? pfx) (max pfx col)]
[(>= (string-length pfx) col) pfx]
[else (string-append
pfx (make-spaces (- col (string-length pfx))))]))))
adds two prefixes
(define (pfx+ pfx1 pfx2)
(and pfx1 pfx2
(if (and (number? pfx1) (number? pfx2)) (+ pfx1 pfx2)
(string-append (if (number? pfx1) (make-spaces pfx1) pfx1)
(if (number? pfx2) (make-spaces pfx2) pfx2)))))
prints two prefixes
(define (output-pfx col pfx1 pfx2)
(define-syntax-rule (->str pfx) (if (number? pfx) (make-spaces pfx) pfx))
(define-syntax-rule (show pfx) ; optimize when not needed
(unless (eq? pfx 0) (write (->str pfx) p)))
(when (and pfx1 pfx2)
(if (eq? 0 col)
(begin (show pfx1) (show pfx2))
(let ([len1 (if (number? pfx1) pfx1 (string-length pfx1))])
(cond [(< col len1) (write (->str pfx1) p col) (show pfx2)]
[(= col len1) (show pfx2)]
[(eq? 0 pfx2)]
[else
(let ([col (- col len1)]
[len2 (if (number? pfx2) pfx2 (string-length pfx2))])
(when (< col len2) (write (->str pfx2) p col)))])))))
;; the basic printing unit: strings
(define (output-string x)
(define pfx (mcar pfxs))
(if (not pfx) ; prefix disabled?
(write x p)
(let ([len (string-length x)]
[nls (regexp-match-positions* #rx"\n" x)])
(let loop ([start 0] [nls nls] [lpfx (mcdr pfxs)] [col (getcol)])
(cond [(pair? nls)
(define nl (car nls))
(if (regexp-match? #rx"^ *$" x start (car nl))
(newline p) ; only spaces before the end of the line
(begin (output-pfx col pfx lpfx)
(write x p start (cdr nl))))
(loop (cdr nl) (cdr nls) 0 0)]
last substring from here ( always set lpfx state when done )
[(start . = . len)
(set-mcdr! pfxs lpfx)]
[(col . > . (2pfx-length pfx lpfx))
(set-mcdr! pfxs lpfx)
;; the prefix was already shown, no accumulation needed
(write x p start)]
[else
(define m (regexp-match-positions #rx"^ +" x start))
accumulate spaces to lpfx , display if it 's not all spaces
(define lpfx* (if m (pfx+ lpfx (- (cdar m) (caar m))) lpfx))
(set-mcdr! pfxs lpfx*)
(unless (and m (= len (cdar m)))
(output-pfx col pfx lpfx*)
the spaces were already added to lpfx
(write x p (if m (cdar m) start)))])))))
;; blocks and splices
(define (output-block c)
(define pfx (mcar pfxs))
(define lpfx (mcdr pfxs))
(define npfx (pfx+col (pfx+ pfx lpfx)))
(set-mcar! pfxs npfx) (set-mcdr! pfxs 0)
(if (list? c)
(for ([c (in-list c)]) (loop c))
(begin (loop (car c)) (loop (cdr c))))
(set-mcar! pfxs pfx) (set-mcdr! pfxs lpfx))
(define (output-splice c)
(for-each loop c))
;; main loop
(define (loop x)
(cond
;; no output for these
[(or (void? x) (not x) (null? x)) (void)]
;; for lists and pairs the current line prefix is added to the global
;; one, then output the contents recursively (no need to change the
;; state, since we pass the values in the loop, and we'd need to restore
;; it afterwards anyway)
[(pair? x) (if list=block? (output-block x) (output-splice x))]
;; delayed values
[(and (procedure? x) (procedure-arity-includes? x 0)) (loop (x))]
[(promise? x) (loop (force x))]
[(box? x) (loop (unbox x))]
;; special output wrappers
[(special? x)
(define c (special-contents x))
(case (special-flag x)
;; preserve tailness & avoid `set!' for blocks/splices if possible
[(block) (if list=block?
(output-block c)
(begin (set! list=block? #t)
(output-block c)
(set! list=block? #f)))]
[(splice) (if list=block?
(begin (set! list=block? #f)
(output-splice c)
(set! list=block? #t))
(output-splice c))]
[(flush) ; useful before `disable-prefix'
(output-pfx (getcol) (mcar pfxs) (mcdr pfxs))]
[(disable-prefix) ; save the previous pfxs
(define pfx (mcar pfxs))
(define lpfx (mcdr pfxs))
(set-mcar! pfxs #f) (set-mcdr! pfxs (cons pfx lpfx))
(for-each loop c)
(set-mcar! pfxs pfx) (set-mcdr! pfxs lpfx)]
[(restore-prefix) ; restore the previous pfxs
(define pfx (mcar pfxs))
(define lpfx (mcdr pfxs))
(define npfx (pfx+col (if (and (not pfx) (pair? lpfx))
(pfx+ (car lpfx) (cdr lpfx))
(pfx+ pfx lpfx))))
(set-mcar! pfxs npfx) (set-mcdr! pfxs 0)
(for-each loop c)
(set-mcar! pfxs pfx) (set-mcdr! pfxs lpfx)]
[(add-prefix) ; add to the current prefix (unless it's #f)
(define pfx (mcar pfxs))
(define lpfx (mcdr pfxs))
(define npfx (pfx+ (pfx+col (pfx+ pfx lpfx)) (car c)))
(set-mcar! pfxs npfx) (set-mcdr! pfxs 0)
(for-each loop (cdr c))
(set-mcar! pfxs pfx) (set-mcdr! pfxs lpfx)]
[(set-prefix)
(define pfx (mcar pfxs))
(define lpfx (mcdr pfxs))
(set-mcar! pfxs (car c)) (set-mcdr! pfxs 0)
(for-each loop (cdr c))
(set-mcar! pfxs pfx) (set-mcdr! pfxs lpfx)]
[(with-writer)
(define old write)
(set! write (or (car c) write-string))
(for-each loop (cdr c))
(set! write old)]
#; ; no need for this hack yet
[(with-writer-change)
;; The function gets the old writer and return a new one (useful to
;; save the current writer and restore it inside). Could also be
;; used to extend a writer, but that shows why a customizable writer
;; is a bad choice: instead, it should be a list of substitutions
;; that can be extended more conveniently. A simple implementation
;; would be to chain functions that do substitutions. But that runs
;; into problems when functions want to substitute the same thing,
and worse : when the output of one function would get substituted
;; again by another. Another approach would be to join matcher
;; regexps with "|" after wrapping each one with parens, then find
;; out which one matched by looking at the result and applying its
;; substitution, but the problem with that is that is that it forbids
;; having parens in the regexps -- this could be fixed by not
;; parenthesizing each expression, and instead running the found
;; match against each of the input regexps to find the matching one,
;; but that can be very inefficient. Yet another issue is that in
;; some cases we might *want* the "worse" feature mentioned earlier:
;; for example, when we want to do some massaging of the input texts
;; yet still have the result encoded for HTML output -- so perhaps
;; the simple approach is still better. The only difference from the
;; current `with-writer' is using a substituting function, so it can
be composed with the current one instead of replacing it
;; completely.
(define old write)
(set! write ((car c) write))
(for-each loop (cdr c))
(set! write old)]
[else (error 'output "unknown special value flag: ~e"
(special-flag x))])]
[else
(output-string
(cond [(string? x) x]
[(bytes? x) (bytes->string/utf-8 x)]
[(symbol? x) (symbol->string x)]
[(path? x) (path->string x)]
[(keyword? x) (keyword->string x)]
[(number? x) (number->string x)]
[(char? x) (string x)]
;; generic fallback: throw an error (could use `display' so new
;; values can define how they're shown, but the same
;; functionality can be achieved with thunks and prop:procedure)
[else (error 'output "don't know how to render value: ~v" x)]))]))
;;
(port-count-lines! p)
(loop x)
(void))
(define port->state
(let ([t (make-weak-hasheq)]
[last '(#f #f)]) ; cache for the last port, to avoid a hash lookup
(λ (p)
(if (eq? p (car last)) (cdr last)
(let ([s (or (hash-ref t p #f)
(let ([s (mcons 0 0)]) (hash-set! t p s) s))])
(set! last (cons p s))
s)))))
;; special constructs
(define-struct special (flag contents))
(define-syntax define/provide-special
(syntax-rules ()
[(_ (name))
(begin (provide (contract-out [name (->* () () #:rest (listof outputable/c) any/c)]))
(define (name . contents)
(make-special 'name contents)))]
[(_ (name [x ctc] ...))
(begin (provide (contract-out [name (->* (ctc ...) () #:rest (listof outputable/c) any/c)]))
(define (name x ... . contents)
(make-special 'name (list* x ... contents))))]
[(_ name)
(begin (provide name)
(define name (make-special 'name #f)))]))
(define/provide-special (block))
(define/provide-special (splice))
(define/provide-special flush)
(define/provide-special (disable-prefix))
(define/provide-special (restore-prefix))
(define/provide-special (add-prefix [pfx (or/c string? exact-nonnegative-integer?)]))
(define/provide-special (set-prefix [pfx (or/c string? exact-nonnegative-integer?)]))
(define/provide-special (with-writer [writer (or/c #f (->* (string? output-port?) (exact-nonnegative-integer? exact-nonnegative-integer?) any/c))]))
#; ; no need for this hack yet
(define/provide-special (with-writer-change writer))
(define make-spaces ; (efficiently)
(let ([t (make-hasheq)] [v (make-vector 200 #f)])
(λ (n)
(or (if (< n 200) (vector-ref v n) (hash-ref t n #f))
(let ([spaces (make-string n #\space)])
(if (< n 200) (vector-set! v n spaces) (hash-set! t n spaces))
spaces)))))
;; Convenient utilities
(provide add-newlines)
(define (add-newlines list #:sep [sep "\n"])
(define r
(let loop ([list list])
(if (null? list)
null
(let ([1st (car list)])
(if (or (not 1st) (void? 1st))
(loop (cdr list))
(list* sep 1st (loop (cdr list))))))))
(if (null? r) r (cdr r)))
(provide split-lines)
(define (split-lines list)
(let loop ([list list] [cur '()] [r '()])
(cond
[(null? list) (reverse (cons (reverse cur) r))]
[(equal? "\n" (car list)) (loop (cdr list) '() (cons (reverse cur) r))]
[else (loop (cdr list) (cons (car list) cur) r)])))
(define outputable/c
(lambda (v) #t)
;; too expensive:
#;
(recursive-contract
(or/c void?
#f
null?
(cons/c outputable/c outputable/c)
(-> outputable/c)
promise?
(box/c outputable/c)
special?
string?
bytes?
symbol?
path?
keyword?
number?
char?)))
| null | https://raw.githubusercontent.com/racket/scribble/beb2d9834169665121d34b5f3195ddf252c3c998/scribble-text-lib/scribble/text/output.rkt | racket | See also `provide-special` below
Outputs values for the `scribble/text' language:
- several atomic values are printed as in `display',
- promises, thunks, and boxes are indirections for the value they contain
(useful in various cases),
- some "special" values are used for controlling output (eg, flushing,
prefix changes, etc),
- specifically, `block's delimit indentation levels, `splice's do not,
- lists (more generally, pairs) are like either one depending on the context
(same as blocks/splices when inside a `block'/`splice'), at the toplevel
they default to blocks.
Uses global state because `output' is wrapped around each expression in a
scribble/text file so this is much more convenient than wrapping the whole
module's body in a `list' (which will be difficult with definitions etc).
The state is a pair of prefixes -- one that is the prefix for the current
value (which gets extended with nested blocks), and the other is the prefix
for the current "line" (which is reset after a newline). The line-prefix is
needed because a line can hold a block, which means that the line-prefix
will apply for the contents of the block including newlines in it. This
state is associated with a port via a hash table. Another state that is
used is the port's column position, which is maintained by the system (when
line counts are enabled) -- this is used to tell what part of a prefix is
already displayed.
Each prefix is either an integer (for a number of spaces) or a string. The
prefix mechanism can be disabled by using #f for the global prefix, and in
used by `disable-prefix' and `restore-prefix' resp. (This is different from
a 0 prefix -- #f means that no prefix will be accumulated).
these are the global prefix and the one that is local to the current line
the current mode for lists
the low-level string output function (can change with `with-writer')
to get the output column
combines a prefix with a target column to get to
optimize when not needed
the basic printing unit: strings
prefix disabled?
only spaces before the end of the line
the prefix was already shown, no accumulation needed
blocks and splices
main loop
no output for these
for lists and pairs the current line prefix is added to the global
one, then output the contents recursively (no need to change the
state, since we pass the values in the loop, and we'd need to restore
it afterwards anyway)
delayed values
special output wrappers
preserve tailness & avoid `set!' for blocks/splices if possible
useful before `disable-prefix'
save the previous pfxs
restore the previous pfxs
add to the current prefix (unless it's #f)
; no need for this hack yet
The function gets the old writer and return a new one (useful to
save the current writer and restore it inside). Could also be
used to extend a writer, but that shows why a customizable writer
is a bad choice: instead, it should be a list of substitutions
that can be extended more conveniently. A simple implementation
would be to chain functions that do substitutions. But that runs
into problems when functions want to substitute the same thing,
again by another. Another approach would be to join matcher
regexps with "|" after wrapping each one with parens, then find
out which one matched by looking at the result and applying its
substitution, but the problem with that is that is that it forbids
having parens in the regexps -- this could be fixed by not
parenthesizing each expression, and instead running the found
match against each of the input regexps to find the matching one,
but that can be very inefficient. Yet another issue is that in
some cases we might *want* the "worse" feature mentioned earlier:
for example, when we want to do some massaging of the input texts
yet still have the result encoded for HTML output -- so perhaps
the simple approach is still better. The only difference from the
current `with-writer' is using a substituting function, so it can
completely.
generic fallback: throw an error (could use `display' so new
values can define how they're shown, but the same
functionality can be achieved with thunks and prop:procedure)
cache for the last port, to avoid a hash lookup
special constructs
; no need for this hack yet
(efficiently)
Convenient utilities
too expensive:
| #lang racket/base
(require racket/promise
racket/contract/base)
(provide
special?
outputable/c
(contract-out
[output (->* (outputable/c) (output-port?) void?)]))
this case the line prefix can have ( cons ) so it can be restored --
(define (output x [p (current-output-port)])
(define pfxs (port->state p))
(define list=block? #t)
(define write write-string)
(define (getcol) (let-values ([(line col pos) (port-next-location p)]) col))
total size of the two prefixes
(define (2pfx-length pfx1 pfx2)
(if (and pfx1 pfx2)
(+ (if (number? pfx1) pfx1 (string-length pfx1))
(if (number? pfx2) pfx2 (string-length pfx2)))
0))
(define (pfx+col pfx)
(and pfx (let ([col (getcol)])
(cond [(number? pfx) (max pfx col)]
[(>= (string-length pfx) col) pfx]
[else (string-append
pfx (make-spaces (- col (string-length pfx))))]))))
adds two prefixes
(define (pfx+ pfx1 pfx2)
(and pfx1 pfx2
(if (and (number? pfx1) (number? pfx2)) (+ pfx1 pfx2)
(string-append (if (number? pfx1) (make-spaces pfx1) pfx1)
(if (number? pfx2) (make-spaces pfx2) pfx2)))))
prints two prefixes
(define (output-pfx col pfx1 pfx2)
(define-syntax-rule (->str pfx) (if (number? pfx) (make-spaces pfx) pfx))
(unless (eq? pfx 0) (write (->str pfx) p)))
(when (and pfx1 pfx2)
(if (eq? 0 col)
(begin (show pfx1) (show pfx2))
(let ([len1 (if (number? pfx1) pfx1 (string-length pfx1))])
(cond [(< col len1) (write (->str pfx1) p col) (show pfx2)]
[(= col len1) (show pfx2)]
[(eq? 0 pfx2)]
[else
(let ([col (- col len1)]
[len2 (if (number? pfx2) pfx2 (string-length pfx2))])
(when (< col len2) (write (->str pfx2) p col)))])))))
(define (output-string x)
(define pfx (mcar pfxs))
(write x p)
(let ([len (string-length x)]
[nls (regexp-match-positions* #rx"\n" x)])
(let loop ([start 0] [nls nls] [lpfx (mcdr pfxs)] [col (getcol)])
(cond [(pair? nls)
(define nl (car nls))
(if (regexp-match? #rx"^ *$" x start (car nl))
(begin (output-pfx col pfx lpfx)
(write x p start (cdr nl))))
(loop (cdr nl) (cdr nls) 0 0)]
last substring from here ( always set lpfx state when done )
[(start . = . len)
(set-mcdr! pfxs lpfx)]
[(col . > . (2pfx-length pfx lpfx))
(set-mcdr! pfxs lpfx)
(write x p start)]
[else
(define m (regexp-match-positions #rx"^ +" x start))
accumulate spaces to lpfx , display if it 's not all spaces
(define lpfx* (if m (pfx+ lpfx (- (cdar m) (caar m))) lpfx))
(set-mcdr! pfxs lpfx*)
(unless (and m (= len (cdar m)))
(output-pfx col pfx lpfx*)
the spaces were already added to lpfx
(write x p (if m (cdar m) start)))])))))
(define (output-block c)
(define pfx (mcar pfxs))
(define lpfx (mcdr pfxs))
(define npfx (pfx+col (pfx+ pfx lpfx)))
(set-mcar! pfxs npfx) (set-mcdr! pfxs 0)
(if (list? c)
(for ([c (in-list c)]) (loop c))
(begin (loop (car c)) (loop (cdr c))))
(set-mcar! pfxs pfx) (set-mcdr! pfxs lpfx))
(define (output-splice c)
(for-each loop c))
(define (loop x)
(cond
[(or (void? x) (not x) (null? x)) (void)]
[(pair? x) (if list=block? (output-block x) (output-splice x))]
[(and (procedure? x) (procedure-arity-includes? x 0)) (loop (x))]
[(promise? x) (loop (force x))]
[(box? x) (loop (unbox x))]
[(special? x)
(define c (special-contents x))
(case (special-flag x)
[(block) (if list=block?
(output-block c)
(begin (set! list=block? #t)
(output-block c)
(set! list=block? #f)))]
[(splice) (if list=block?
(begin (set! list=block? #f)
(output-splice c)
(set! list=block? #t))
(output-splice c))]
(output-pfx (getcol) (mcar pfxs) (mcdr pfxs))]
(define pfx (mcar pfxs))
(define lpfx (mcdr pfxs))
(set-mcar! pfxs #f) (set-mcdr! pfxs (cons pfx lpfx))
(for-each loop c)
(set-mcar! pfxs pfx) (set-mcdr! pfxs lpfx)]
(define pfx (mcar pfxs))
(define lpfx (mcdr pfxs))
(define npfx (pfx+col (if (and (not pfx) (pair? lpfx))
(pfx+ (car lpfx) (cdr lpfx))
(pfx+ pfx lpfx))))
(set-mcar! pfxs npfx) (set-mcdr! pfxs 0)
(for-each loop c)
(set-mcar! pfxs pfx) (set-mcdr! pfxs lpfx)]
(define pfx (mcar pfxs))
(define lpfx (mcdr pfxs))
(define npfx (pfx+ (pfx+col (pfx+ pfx lpfx)) (car c)))
(set-mcar! pfxs npfx) (set-mcdr! pfxs 0)
(for-each loop (cdr c))
(set-mcar! pfxs pfx) (set-mcdr! pfxs lpfx)]
[(set-prefix)
(define pfx (mcar pfxs))
(define lpfx (mcdr pfxs))
(set-mcar! pfxs (car c)) (set-mcdr! pfxs 0)
(for-each loop (cdr c))
(set-mcar! pfxs pfx) (set-mcdr! pfxs lpfx)]
[(with-writer)
(define old write)
(set! write (or (car c) write-string))
(for-each loop (cdr c))
(set! write old)]
[(with-writer-change)
and worse : when the output of one function would get substituted
be composed with the current one instead of replacing it
(define old write)
(set! write ((car c) write))
(for-each loop (cdr c))
(set! write old)]
[else (error 'output "unknown special value flag: ~e"
(special-flag x))])]
[else
(output-string
(cond [(string? x) x]
[(bytes? x) (bytes->string/utf-8 x)]
[(symbol? x) (symbol->string x)]
[(path? x) (path->string x)]
[(keyword? x) (keyword->string x)]
[(number? x) (number->string x)]
[(char? x) (string x)]
[else (error 'output "don't know how to render value: ~v" x)]))]))
(port-count-lines! p)
(loop x)
(void))
(define port->state
(let ([t (make-weak-hasheq)]
(λ (p)
(if (eq? p (car last)) (cdr last)
(let ([s (or (hash-ref t p #f)
(let ([s (mcons 0 0)]) (hash-set! t p s) s))])
(set! last (cons p s))
s)))))
(define-struct special (flag contents))
(define-syntax define/provide-special
(syntax-rules ()
[(_ (name))
(begin (provide (contract-out [name (->* () () #:rest (listof outputable/c) any/c)]))
(define (name . contents)
(make-special 'name contents)))]
[(_ (name [x ctc] ...))
(begin (provide (contract-out [name (->* (ctc ...) () #:rest (listof outputable/c) any/c)]))
(define (name x ... . contents)
(make-special 'name (list* x ... contents))))]
[(_ name)
(begin (provide name)
(define name (make-special 'name #f)))]))
(define/provide-special (block))
(define/provide-special (splice))
(define/provide-special flush)
(define/provide-special (disable-prefix))
(define/provide-special (restore-prefix))
(define/provide-special (add-prefix [pfx (or/c string? exact-nonnegative-integer?)]))
(define/provide-special (set-prefix [pfx (or/c string? exact-nonnegative-integer?)]))
(define/provide-special (with-writer [writer (or/c #f (->* (string? output-port?) (exact-nonnegative-integer? exact-nonnegative-integer?) any/c))]))
(define/provide-special (with-writer-change writer))
(let ([t (make-hasheq)] [v (make-vector 200 #f)])
(λ (n)
(or (if (< n 200) (vector-ref v n) (hash-ref t n #f))
(let ([spaces (make-string n #\space)])
(if (< n 200) (vector-set! v n spaces) (hash-set! t n spaces))
spaces)))))
(provide add-newlines)
(define (add-newlines list #:sep [sep "\n"])
(define r
(let loop ([list list])
(if (null? list)
null
(let ([1st (car list)])
(if (or (not 1st) (void? 1st))
(loop (cdr list))
(list* sep 1st (loop (cdr list))))))))
(if (null? r) r (cdr r)))
(provide split-lines)
(define (split-lines list)
(let loop ([list list] [cur '()] [r '()])
(cond
[(null? list) (reverse (cons (reverse cur) r))]
[(equal? "\n" (car list)) (loop (cdr list) '() (cons (reverse cur) r))]
[else (loop (cdr list) (cons (car list) cur) r)])))
(define outputable/c
(lambda (v) #t)
(recursive-contract
(or/c void?
#f
null?
(cons/c outputable/c outputable/c)
(-> outputable/c)
promise?
(box/c outputable/c)
special?
string?
bytes?
symbol?
path?
keyword?
number?
char?)))
|
24ffb577c134c1822fdee3a7008877ff208ae7e8514e4305c2a0c4f5fc3581b9 | litaocheng/erl-test | util.erl | -module(util).
-compile([export_all]).
do_with_statis(Label, Fun, Acc) ->
do_with_statis(Label, Fun, Acc, 1).
do_with_statis(Label, Fun, Acc, N) ->
erlang:garbage_collect(self()),
{memory, MP1} = erlang:process_info(self(), memory),
MT1 = erlang:memory(total),
T1 = now(),
{_, _} = erlang:statistics(runtime),
{_, _} = erlang:statistics(wall_clock),
{_, _} = erlang:statistics(reductions),
Ret = do_times(Fun, Acc, N),
T2 = now(),
{_, RT} = erlang:statistics(runtime),
{_, WT} = erlang:statistics(wall_clock),
{_, Reds} = erlang:statistics(reductions),
{memory, MP2} = erlang:process_info(self(), memory),
MT2 = erlang:memory(total),
NowT = timer:now_diff(T2, T1),
io:format("==========~p==========\n", [Label]),
io:format("return:~p ~p/sec\n", [Ret, N * 1000 div NowT]),
io:format("reds:~p runtime:~p walktime:~p time:~p\n"
"memory process:~p memory total:~p\n",
[Reds, RT, WT, NowT, MP2 - MP1, MT2 - MT1]).
%% 执行多次
do_times(_F, Acc, 0) ->
Acc;
do_times(F, Acc, N) ->
Acc2 = (catch F(Acc)),
do_times(F, Acc2, N - 1).
| null | https://raw.githubusercontent.com/litaocheng/erl-test/893679fccb1c16dda45d40d2b9e12d78db991b8a/util/util.erl | erlang | 执行多次 | -module(util).
-compile([export_all]).
do_with_statis(Label, Fun, Acc) ->
do_with_statis(Label, Fun, Acc, 1).
do_with_statis(Label, Fun, Acc, N) ->
erlang:garbage_collect(self()),
{memory, MP1} = erlang:process_info(self(), memory),
MT1 = erlang:memory(total),
T1 = now(),
{_, _} = erlang:statistics(runtime),
{_, _} = erlang:statistics(wall_clock),
{_, _} = erlang:statistics(reductions),
Ret = do_times(Fun, Acc, N),
T2 = now(),
{_, RT} = erlang:statistics(runtime),
{_, WT} = erlang:statistics(wall_clock),
{_, Reds} = erlang:statistics(reductions),
{memory, MP2} = erlang:process_info(self(), memory),
MT2 = erlang:memory(total),
NowT = timer:now_diff(T2, T1),
io:format("==========~p==========\n", [Label]),
io:format("return:~p ~p/sec\n", [Ret, N * 1000 div NowT]),
io:format("reds:~p runtime:~p walktime:~p time:~p\n"
"memory process:~p memory total:~p\n",
[Reds, RT, WT, NowT, MP2 - MP1, MT2 - MT1]).
do_times(_F, Acc, 0) ->
Acc;
do_times(F, Acc, N) ->
Acc2 = (catch F(Acc)),
do_times(F, Acc2, N - 1).
|
aa4c5f358ee0946f1c6b8fb9a9415860a70393f5f6cdbf71fabd6cef19d2b799 | vilmibm/murepl | events.clj | (ns murepl.events
(:require [murepl.common :refer :all]
[murepl.core :as core]))
(defn send-msg [player msg]
Invokes player 's send - function function .
(if-let [send-function (:send-function player)]
(send-function msg)))
(defn notify-players [players msg]
(println "Sending:" msg)
(doseq [player players]
(send-msg player msg)))
(defn connect [uuid function]
"Subscribe player to the events framework by giving it a send function,
probably associated with its network connection that will be used to pass
event messages to it."
(let [player (core/find-player-by-uuid uuid)
observers (core/others-in-room player (core/lookup-location player))]
(core/modify-player! (assoc player :send-function function))
(notify-players observers (format "%s slowly fades into existence." (:name player)))))
(defn disconnect [uuid]
"Unsubscribe player identified by uuid from the events framework."
(let [player (core/find-player-by-uuid uuid)
observers (core/logout-player player)]
(core/modify-player! (dissoc player :send-function))
(notify-players observers (format "%s fades slowly away." (:name player)))))
| null | https://raw.githubusercontent.com/vilmibm/murepl/74ee5979ef2f09301103d0281b35a7e226bc1997/src/murepl/events.clj | clojure | (ns murepl.events
(:require [murepl.common :refer :all]
[murepl.core :as core]))
(defn send-msg [player msg]
Invokes player 's send - function function .
(if-let [send-function (:send-function player)]
(send-function msg)))
(defn notify-players [players msg]
(println "Sending:" msg)
(doseq [player players]
(send-msg player msg)))
(defn connect [uuid function]
"Subscribe player to the events framework by giving it a send function,
probably associated with its network connection that will be used to pass
event messages to it."
(let [player (core/find-player-by-uuid uuid)
observers (core/others-in-room player (core/lookup-location player))]
(core/modify-player! (assoc player :send-function function))
(notify-players observers (format "%s slowly fades into existence." (:name player)))))
(defn disconnect [uuid]
"Unsubscribe player identified by uuid from the events framework."
(let [player (core/find-player-by-uuid uuid)
observers (core/logout-player player)]
(core/modify-player! (dissoc player :send-function))
(notify-players observers (format "%s fades slowly away." (:name player)))))
|
|
8aa28eb8bb5f47b3394a5b094bfe3d4b18a9dce648fd7921eb7b3cb98220606f | Quickscript-Competiton/July2020entries | cve-search.rkt | #lang racket/base
(require quickscript)
(require racket/string)
(require net/url)
(require json)
Author :
License : [ Apache License , Version 2.0]( / licenses / LICENSE-2.0 ) or
[ MIT license]( / licenses / MIT ) at your option .
;;; From: -Competiton/July2020entries/issues/12
(script-help-string "A function to help you gather CVE information,
if you use it with a text slection it will try and work out
if there any CVEs referenced by your selection")
(define LAST-30-CVES-ENDPOINT "")
(define SPECIFIC-CVE-ENDPOINT "/") ; e.g. -2010-3333
(define CVE-REGEXP #px"CVE-\\d{4}-\\d{4}")
given : empty string , expect : the latest CVE details
given : " CVE-2017 - 5969 " a valid CVE - ID , expect : CVE report in a message box
(define-script cve-search
#:label "CVE Search"
#:output-to message-box
#:help-string "A function to help you gather CVE information, if you use it with a text slection it will try and work out if there any CVEs referenced by your selection"
(λ (selection)
(if (regexp-match CVE-REGEXP selection)
(cve-details (car (regexp-match CVE-REGEXP selection)))
(latest-cve)
)))
return a string containing the last 30 CVEs ID and their summary
;; I think I could make this more efficient but it seems the vast bulk of the time is in the network request (as you'd expect)
(define (latest-cve)
(define cves (call/input-url (string->url LAST-30-CVES-ENDPOINT)
get-pure-port
read-json))
(define cve-summaries (map (lambda (cve)
(string-append (hash-ref cve 'id) " : " (hash-ref cve 'summary)))
cves))
(car cve-summaries))
return a CVE from a specific CVE i d
;; I'd like to have the references render as links
(define (cve-details cve-id)
(define cve-report (call/input-url (string->url (string-append SPECIFIC-CVE-ENDPOINT cve-id))
get-pure-port
read-json))
(define cve-summary
(string-append "Published: " (hash-ref cve-report 'Published) "\n"
"Summary: " (hash-ref cve-report 'summary) "\n"
"References: " (string-append* (map (lambda (ref) (string-append ref "\n")) (hash-ref cve-report 'references)))))
cve-summary)
| null | https://raw.githubusercontent.com/Quickscript-Competiton/July2020entries/b6406a4f021671bccb6b464042ba6c91221286fe/scripts/cve-search.rkt | racket | From: -Competiton/July2020entries/issues/12
e.g. -2010-3333
I think I could make this more efficient but it seems the vast bulk of the time is in the network request (as you'd expect)
I'd like to have the references render as links | #lang racket/base
(require quickscript)
(require racket/string)
(require net/url)
(require json)
Author :
License : [ Apache License , Version 2.0]( / licenses / LICENSE-2.0 ) or
[ MIT license]( / licenses / MIT ) at your option .
(script-help-string "A function to help you gather CVE information,
if you use it with a text slection it will try and work out
if there any CVEs referenced by your selection")
(define LAST-30-CVES-ENDPOINT "")
(define CVE-REGEXP #px"CVE-\\d{4}-\\d{4}")
given : empty string , expect : the latest CVE details
given : " CVE-2017 - 5969 " a valid CVE - ID , expect : CVE report in a message box
(define-script cve-search
#:label "CVE Search"
#:output-to message-box
#:help-string "A function to help you gather CVE information, if you use it with a text slection it will try and work out if there any CVEs referenced by your selection"
(λ (selection)
(if (regexp-match CVE-REGEXP selection)
(cve-details (car (regexp-match CVE-REGEXP selection)))
(latest-cve)
)))
return a string containing the last 30 CVEs ID and their summary
(define (latest-cve)
(define cves (call/input-url (string->url LAST-30-CVES-ENDPOINT)
get-pure-port
read-json))
(define cve-summaries (map (lambda (cve)
(string-append (hash-ref cve 'id) " : " (hash-ref cve 'summary)))
cves))
(car cve-summaries))
return a CVE from a specific CVE i d
(define (cve-details cve-id)
(define cve-report (call/input-url (string->url (string-append SPECIFIC-CVE-ENDPOINT cve-id))
get-pure-port
read-json))
(define cve-summary
(string-append "Published: " (hash-ref cve-report 'Published) "\n"
"Summary: " (hash-ref cve-report 'summary) "\n"
"References: " (string-append* (map (lambda (ref) (string-append ref "\n")) (hash-ref cve-report 'references)))))
cve-summary)
|
3cae5daf53def2e64870467f1601add1d638be2b5cc8c1e5ecd287a07db961ee | gergoerdi/clash-shake | Intel.hs | # LANGUAGE OverloadedStrings , RecordWildCards , TemplateHaskell #
module Clash.Shake.Intel
( Target(..)
, de0Nano, arrowDeca
, quartus
) where
import Clash.Shake
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import Development.Shake.Config
import Text.Mustache
import qualified Text.Mustache.Compile.TH as TH
import Data.Aeson
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.IO as T
data Target = Target
{ targetFamily :: String
, targetDevice :: String
}
targetMustache Target{..} =
[ "targetFamily" .= T.pack targetFamily
, "targetDevice" .= T.pack targetDevice
]
| Target definition for Terasic DE0 - Nano
de0Nano :: Target
de0Nano = Target "Cyclone IV E" "EP4CE22F17C6"
| Target definition for Arrow DECA
arrowDeca :: Target
arrowDeca = Target "MAX 10" "10M50DAF484C6GES"
quartus :: Target -> SynthRules
quartus fpga kit@ClashKit{..} outDir topName extraGenerated = do
let projectName = topName
rootDir = joinPath . map (const "..") . splitPath $ outDir
let quartus tool args = cmd_ (Cwd outDir) =<< toolchain "QUARTUS" tool args
outDir <//> "*.tcl" %> \out -> do
srcs1 <- manifestSrcs
extraFiles <- findFiles <$> extraGenerated
let srcs2 = extraFiles ["//*.vhdl", "//*.v", "//*.sv"]
tcls = extraFiles ["//*.tcl"]
constrs = extraFiles ["//*.sdc"]
cores = extraFiles ["//*.qip"]
let template = $(TH.compileMustacheFile "template/intel-quartus/project.tcl.mustache")
let values = object . mconcat $
[ [ "project" .= T.pack projectName ]
, [ "top" .= T.pack topName ]
, targetMustache fpga
, [ "srcs" .= [ object [ "fileName" .= (rootDir </> src) ] | src <- srcs1 <> srcs2 ]
]
, [ "tclSrcs" .= [ object [ "fileName" .= (rootDir </> src) ] | src <- tcls ] ]
, [ "ipcores" .= [ object [ "fileName" .= (rootDir </> core) ] | core <- cores ] ]
, [ "constraintSrcs" .= [ object [ "fileName" .= (rootDir </> src) ] | src <- constrs ] ]
]
writeFileChanged out . TL.unpack $ renderMustache template values
let bitfile = outDir </> topName <.> "sof"
bitfile %> \_out -> do
need $ [ outDir </> projectName <.> "tcl" ]
quartus "quartus_sh" ["-t", projectName <.> "tcl"]
outDir </> topName <.> "rbf" %> \out -> do
let sof = out -<.> "sof"
need [sof]
quartus "quartus_cpf"
[ "--option=bitstream_compression=off"
, "-c", makeRelative outDir sof
, makeRelative outDir out
]
return $ SynthKit
{ bitfile = bitfile
, phonies =
[ "quartus" |> do
need [outDir </> projectName <.> "tcl"]
quartus "quartus_sh" ["-t", projectName <.> "tcl"]
, "upload" |> do
need [bitfile]
quartus "quartus_pgm" ["-m", "jtag", "-o", "p;" <> makeRelative outDir bitfile]
]
}
| null | https://raw.githubusercontent.com/gergoerdi/clash-shake/2f58c5522b1db62ab1d4000b06fda0197efc6adf/src/Clash/Shake/Intel.hs | haskell | # LANGUAGE OverloadedStrings , RecordWildCards , TemplateHaskell #
module Clash.Shake.Intel
( Target(..)
, de0Nano, arrowDeca
, quartus
) where
import Clash.Shake
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import Development.Shake.Config
import Text.Mustache
import qualified Text.Mustache.Compile.TH as TH
import Data.Aeson
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.IO as T
data Target = Target
{ targetFamily :: String
, targetDevice :: String
}
targetMustache Target{..} =
[ "targetFamily" .= T.pack targetFamily
, "targetDevice" .= T.pack targetDevice
]
| Target definition for Terasic DE0 - Nano
de0Nano :: Target
de0Nano = Target "Cyclone IV E" "EP4CE22F17C6"
| Target definition for Arrow DECA
arrowDeca :: Target
arrowDeca = Target "MAX 10" "10M50DAF484C6GES"
quartus :: Target -> SynthRules
quartus fpga kit@ClashKit{..} outDir topName extraGenerated = do
let projectName = topName
rootDir = joinPath . map (const "..") . splitPath $ outDir
let quartus tool args = cmd_ (Cwd outDir) =<< toolchain "QUARTUS" tool args
outDir <//> "*.tcl" %> \out -> do
srcs1 <- manifestSrcs
extraFiles <- findFiles <$> extraGenerated
let srcs2 = extraFiles ["//*.vhdl", "//*.v", "//*.sv"]
tcls = extraFiles ["//*.tcl"]
constrs = extraFiles ["//*.sdc"]
cores = extraFiles ["//*.qip"]
let template = $(TH.compileMustacheFile "template/intel-quartus/project.tcl.mustache")
let values = object . mconcat $
[ [ "project" .= T.pack projectName ]
, [ "top" .= T.pack topName ]
, targetMustache fpga
, [ "srcs" .= [ object [ "fileName" .= (rootDir </> src) ] | src <- srcs1 <> srcs2 ]
]
, [ "tclSrcs" .= [ object [ "fileName" .= (rootDir </> src) ] | src <- tcls ] ]
, [ "ipcores" .= [ object [ "fileName" .= (rootDir </> core) ] | core <- cores ] ]
, [ "constraintSrcs" .= [ object [ "fileName" .= (rootDir </> src) ] | src <- constrs ] ]
]
writeFileChanged out . TL.unpack $ renderMustache template values
let bitfile = outDir </> topName <.> "sof"
bitfile %> \_out -> do
need $ [ outDir </> projectName <.> "tcl" ]
quartus "quartus_sh" ["-t", projectName <.> "tcl"]
outDir </> topName <.> "rbf" %> \out -> do
let sof = out -<.> "sof"
need [sof]
quartus "quartus_cpf"
[ "--option=bitstream_compression=off"
, "-c", makeRelative outDir sof
, makeRelative outDir out
]
return $ SynthKit
{ bitfile = bitfile
, phonies =
[ "quartus" |> do
need [outDir </> projectName <.> "tcl"]
quartus "quartus_sh" ["-t", projectName <.> "tcl"]
, "upload" |> do
need [bitfile]
quartus "quartus_pgm" ["-m", "jtag", "-o", "p;" <> makeRelative outDir bitfile]
]
}
|
|
ed0934a6d9603d0f2299ce146f891468ebd4e3e1da23425fc48c354829cd16f4 | ghc/nofib | Rewritefns.hs |
Haskell version of ...
! rewrite functions for benchmark
! Started by on 30 March 1988
! Changes Log
! 08 - 04 - 88 ADK bug fix = rewrite(Atom(x),A ) returns Atom(x ) not Nil
! 25 - 05 - 88 ADK added applysubst to this module and assoclist replaced by LUT
Haskell version :
23 - 06 - 93 JSM initial version
Haskell version of ...
! rewrite functions for Boyer benchmark
! Started by Tony Kitto on 30 March 1988
! Changes Log
! 08-04-88 ADK bug fix = rewrite(Atom(x),A) returns Atom(x) not Nil
! 25-05-88 ADK added applysubst to this module and assoclist replaced by LUT
Haskell version:
23-06-93 JSM initial version
-}
module Rewritefns (applysubst, rewrite) where
import Lisplikefns
applysubst :: Lisplist -> Lisplist -> Lisplist
applysubst alist Nil = Nil
applysubst alist term@(Atom x) =
case assoc (term, alist) of
Cons (yh, yt) -> yt
_ -> term
applysubst alist (Cons (x, y)) = Cons (x, applysubstlst alist y)
applysubstlst :: Lisplist -> Lisplist -> Lisplist
applysubstlst alist Nil = Nil
applysubstlst alist (Atom x) = error "Malformed list"
applysubstlst alist (Cons (x, y)) =
Cons (applysubst alist x, applysubstlst alist y)
rewrite :: Lisplist -> LUT -> Lisplist
rewrite Nil term = Nil
rewrite expr@(Atom x) term = expr
rewrite (Cons (l1, l2)) term =
rewritewithlemmas (Cons (l1, rewriteargs l2 term))
(getLUT (tv l1, term)) term
rewriteargs :: Lisplist -> LUT -> Lisplist
rewriteargs Nil term = Nil
rewriteargs (Atom x) term = error "Malformed list"
rewriteargs (Cons (x, y)) term = Cons (rewrite x term, rewriteargs y term)
rewritewithlemmas :: Lisplist -> [Lisplist] -> LUT -> Lisplist
rewritewithlemmas t [] term = t
rewritewithlemmas t (lh:lt) term
| b = rewrite (applysubst u (caddr lh)) term
| otherwise = rewritewithlemmas t lt term
where (b, u) = onewayunify t (cadr lh)
onewayunify :: Lisplist -> Lisplist -> (Bool, Lisplist)
onewayunify t1 t2 = onewayunify1 t1 t2 Nil
onewayunify1 :: Lisplist -> Lisplist -> Lisplist -> (Bool, Lisplist)
onewayunify1 t1 t2 u | atom t2 = case assoc (t2, u) of
Cons (x, y) -> (t1 == y, u)
_ -> (True, Cons (Cons (t2, t1), u))
| atom t1 = (False, u)
| car t1 == car t2 = onewayunify1lst (cdr t1) (cdr t2) u
| otherwise = (False, u)
onewayunify1lst :: Lisplist -> Lisplist -> Lisplist -> (Bool, Lisplist)
onewayunify1lst Nil _ u = (True, u)
onewayunify1lst l1 l2 u
| b = onewayunify1lst (cdr l1) (cdr l2) u1
| otherwise = (False, u1)
where (b, u1) = onewayunify1 (car l1) (car l2) u
| null | https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/spectral/boyer2/Rewritefns.hs | haskell |
Haskell version of ...
! rewrite functions for benchmark
! Started by on 30 March 1988
! Changes Log
! 08 - 04 - 88 ADK bug fix = rewrite(Atom(x),A ) returns Atom(x ) not Nil
! 25 - 05 - 88 ADK added applysubst to this module and assoclist replaced by LUT
Haskell version :
23 - 06 - 93 JSM initial version
Haskell version of ...
! rewrite functions for Boyer benchmark
! Started by Tony Kitto on 30 March 1988
! Changes Log
! 08-04-88 ADK bug fix = rewrite(Atom(x),A) returns Atom(x) not Nil
! 25-05-88 ADK added applysubst to this module and assoclist replaced by LUT
Haskell version:
23-06-93 JSM initial version
-}
module Rewritefns (applysubst, rewrite) where
import Lisplikefns
applysubst :: Lisplist -> Lisplist -> Lisplist
applysubst alist Nil = Nil
applysubst alist term@(Atom x) =
case assoc (term, alist) of
Cons (yh, yt) -> yt
_ -> term
applysubst alist (Cons (x, y)) = Cons (x, applysubstlst alist y)
applysubstlst :: Lisplist -> Lisplist -> Lisplist
applysubstlst alist Nil = Nil
applysubstlst alist (Atom x) = error "Malformed list"
applysubstlst alist (Cons (x, y)) =
Cons (applysubst alist x, applysubstlst alist y)
rewrite :: Lisplist -> LUT -> Lisplist
rewrite Nil term = Nil
rewrite expr@(Atom x) term = expr
rewrite (Cons (l1, l2)) term =
rewritewithlemmas (Cons (l1, rewriteargs l2 term))
(getLUT (tv l1, term)) term
rewriteargs :: Lisplist -> LUT -> Lisplist
rewriteargs Nil term = Nil
rewriteargs (Atom x) term = error "Malformed list"
rewriteargs (Cons (x, y)) term = Cons (rewrite x term, rewriteargs y term)
rewritewithlemmas :: Lisplist -> [Lisplist] -> LUT -> Lisplist
rewritewithlemmas t [] term = t
rewritewithlemmas t (lh:lt) term
| b = rewrite (applysubst u (caddr lh)) term
| otherwise = rewritewithlemmas t lt term
where (b, u) = onewayunify t (cadr lh)
onewayunify :: Lisplist -> Lisplist -> (Bool, Lisplist)
onewayunify t1 t2 = onewayunify1 t1 t2 Nil
onewayunify1 :: Lisplist -> Lisplist -> Lisplist -> (Bool, Lisplist)
onewayunify1 t1 t2 u | atom t2 = case assoc (t2, u) of
Cons (x, y) -> (t1 == y, u)
_ -> (True, Cons (Cons (t2, t1), u))
| atom t1 = (False, u)
| car t1 == car t2 = onewayunify1lst (cdr t1) (cdr t2) u
| otherwise = (False, u)
onewayunify1lst :: Lisplist -> Lisplist -> Lisplist -> (Bool, Lisplist)
onewayunify1lst Nil _ u = (True, u)
onewayunify1lst l1 l2 u
| b = onewayunify1lst (cdr l1) (cdr l2) u1
| otherwise = (False, u1)
where (b, u1) = onewayunify1 (car l1) (car l2) u
|
|
e758c15e3e251f1005e38346197dcd3fb71af0c1fad3129d5e8f8622d40c33d4 | larcenists/larceny | while3.scm | (text
(while (< edx 20)
(begin
(iter (seq (pop ebx)
(!= ebx 4)
(add eax ebx)))
(add edx eax))))
; iter is sometimes better for inner loops, since both
; while and until always generate a jmp at their start
; to the test (the test is placed after their body).
; When while or until start the body of an outer while/until
; that means a jmp or jcc to a jmp will be generated.
; Using iter for the inner loop fixes this.
00000000 EB0C short 0xe
00000002 5B pop ebx
00000003 83FB04 cmp ebx , byte +0x4
00000006 7404 jz 0xc
00000008 01D8 add eax , ebx
0000000A EBF6 jmp short 0x2
0000000C 01C2 add edx , eax
0000000E 83FA14 cmp edx , byte +0x14
00000011 7CEF jl 0x2
| null | https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/src/Lib/Sassy/tests/prims/while3.scm | scheme | iter is sometimes better for inner loops, since both
while and until always generate a jmp at their start
to the test (the test is placed after their body).
When while or until start the body of an outer while/until
that means a jmp or jcc to a jmp will be generated.
Using iter for the inner loop fixes this.
| (text
(while (< edx 20)
(begin
(iter (seq (pop ebx)
(!= ebx 4)
(add eax ebx)))
(add edx eax))))
00000000 EB0C short 0xe
00000002 5B pop ebx
00000003 83FB04 cmp ebx , byte +0x4
00000006 7404 jz 0xc
00000008 01D8 add eax , ebx
0000000A EBF6 jmp short 0x2
0000000C 01C2 add edx , eax
0000000E 83FA14 cmp edx , byte +0x14
00000011 7CEF jl 0x2
|
841beeb481bac376a21edcb64492e7f9a0cd25db7f1a12eafeb23a4db1a374a6 | tonyday567/chart-unit | Core.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE NegativeLiterals #
# OPTIONS_GHC -Wall #
# OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE CPP #
# LANGUAGE DeriveGeneric #
# LANGUAGE ViewPatterns #
#if ( __GLASGOW_HASKELL__ < 820 )
# OPTIONS_GHC -fno - warn - incomplete - patterns #
#endif
| In making a chart , there are three main size domains you have to be concerned about :
--
- the range of the data being charted . This range is often projected onto chart elements such as axes and labels . A data range in two dimensions is a ' Rect ' a.
--
- the scale of various chart primitives and elements . The overall dimensions of the chart canvas - the rectangular shape on which the data is represented - is referred to as an ' Aspect ' in the api , and is a wrapped ' ' to distinguish aspects from rect ranges . The default chart options tend to be callibrated to Aspects around widths of one .
--
-- - the size of the chart rendered as an image. Backends tend to shrink charts to fit the rectangle shape specified in the render function, and a loose sympathy is expected between the aspect and a chart's ultimate physical size.
--
Jumping ahead a bit , the code snippet below draws vertical lines using a data range of " Rect 0 12 0 0.2 " ( slightly different to the actual data range ) , using a widescreen ( 3:1 ) aspect , and renders the chart as a 300 by 120 pixel svg :
--
> scaleExample : : IO ( )
> scaleExample =
> fileSvg " other / scaleExample.svg " ( # size .~ Pair 300 120 $ def ) $
-- > withHud
-- > defaultHudOptions
-- > widescreen
> ( 0 12 0 0.2 )
> ( lineChart ( repeat def ) )
> ( vlineOneD ( ( 0.01 * ) < $ > [ 0 .. 10 ] ) )
--
-- 
--
module Chart.Core
( -- * Chart types
Chart
-- * Scaling
, range
, projectss
, aspect
, asquare
, sixbyfour
, golden
, widescreen
, skinny
, AlignH(..)
, AlignV(..)
, alignHU
, alignHTU
, alignVU
, alignVTU
-- * Types
, Orientation(..)
, Place(..)
-- * Combinators
--
| The concept of a point on a chart is the polymorphic ' R2 ' from the ' linear ' library . Diagrams most often uses ' Point ' , which is a wrapped ' V2 ' . The ' Pair ' type from ' numhask - range ' is often used as a point reference .
, positioned
, p_
, r_
, stack
, vert
, hori
, sepVert
, sepHori
-- * Color
--
-- | chart-unit exposes the 'colour' and 'palette' libraries for color combinators
, UColor(..)
, acolor
, ucolor
, ccolor
, ublue
, ugrey
, utrans
, ublack
, uwhite
-- * Compatability
, scaleX
, scaleY
, scale
) where
import Diagrams.Prelude
hiding (Color, D, aspect, project, scale, scaleX, scaleY, zero, over)
import qualified Diagrams.Prelude as Diagrams
import qualified Diagrams.TwoD.Text
import NumHask.Pair
import NumHask.Prelude
import NumHask.Rect
import NumHask.Range
import NumHask.Space
import Data.Colour (over)
| A Chart is simply a type synonym for a typical Diagrams object . A close relation to this type is ' Diagram ' ' B ' , but this usage tends to force a single backend ( B comes from the backend libraries ) , so making Chart b 's maintains backend polymorphism .
--
Just about everything - text , circles , lines , triangles , charts , axes , titles , legends etc - are ' Chart 's , which means that most things are amenable to full use of the combinatorially - inclined diagrams - lib .
type Chart b =
( Renderable (Path V2 Double) b
, Renderable (Diagrams.TwoD.Text.Text Double) b) =>
QDiagram b V2 Double Any
| project a double - containered set of data to a new Rect range
projectss ::
(Functor f, Functor g)
=> Rect Double
-> Rect Double
-> g (f (Pair Double))
-> g (f (Pair Double))
projectss r0 r1 xyss = map (project r0 r1) <$> xyss
-- | determine the range of a double-containered set of data
range :: (Foldable f, Foldable g) => g (f (Pair Double)) -> Rect Double
range xyss = foldMap space xyss
-- | the aspect of a chart expressed as a ratio of x-plane : y-plane.
aspect :: (CanRange a, Multiplicative a) => a -> Rect a
aspect a = Ranges ((a *) <$> one) one
| a 1:1 aspect
asquare :: Rect Double
asquare = aspect 1
| a 1.5:1 aspect
sixbyfour :: Rect Double
sixbyfour = aspect 1.5
-- | golden ratio
golden :: Rect Double
golden = aspect 1.61803398875
-- | a 3:1 aspect
widescreen :: Rect Double
widescreen = aspect 3
| a skinny 5:1 aspect
skinny :: Rect Double
skinny = aspect 5
-- | horizontal alignment
data AlignH
= AlignLeft
| AlignCenter
| AlignRight
deriving (Show, Eq, Generic)
-- | vertical alignment
data AlignV
= AlignTop
| AlignMid
| AlignBottom
deriving (Show, Eq, Generic)
-- | conversion of horizontal alignment to (one :: Range Double) limits
alignHU :: AlignH -> Double
alignHU a =
case a of
AlignLeft -> 0.5
AlignCenter -> 0
AlignRight -> -0.5
-- | svg text is forced to be lower left (-0.5) by default
alignHTU :: AlignH -> Double
alignHTU a =
case a of
AlignLeft -> 0
AlignCenter -> -0.5
AlignRight -> -1
-- | conversion of vertical alignment to (one :: Range Double) limits
alignVU :: AlignV -> Double
alignVU a =
case a of
AlignTop -> -0.5
AlignMid -> 0
AlignBottom -> 0.5
-- | svg text is lower by default
alignVTU :: AlignV -> Double
alignVTU a =
case a of
AlignTop -> 0.5
AlignMid -> 0
AlignBottom -> -0.5
-- | Orientation for an element. Watch this space for curvature!
data Orientation
= Hori
| Vert
deriving (Show, Eq, Generic)
-- | Placement of elements around (what is implicity but maybe shouldn't just be) a rectangular canvas
data Place
= PlaceLeft
| PlaceRight
| PlaceTop
| PlaceBottom
deriving (Show, Eq, Generic)
-- | position an element at a point
positioned :: (R2 r) => r Double -> Chart b -> Chart b
positioned p = moveTo (p_ p)
| convert an R2 to a diagrams Point
p_ :: (R2 r) => r Double -> Point V2 Double
p_ r = curry p2 (r ^. _x) (r ^. _y)
| convert an R2 to a V2
r_ :: R2 r => r a -> V2 a
r_ r = V2 (r ^. _x) (r ^. _y)
-- | foldMap for beside; stacking chart elements in a direction, with a premap
stack ::
( R2 r
, V a ~ V2
, Foldable t
, Juxtaposable a
, Semigroup a
, N a ~ Double
, Monoid a
)
=> r Double
-> (b -> a)
-> t b
-> a
stack dir f xs = foldr (\a x -> beside (r_ dir) (f a) x) mempty xs
-- | combine elements vertically, with a premap
vert ::
(V a ~ V2, Foldable t, Juxtaposable a, Semigroup a, N a ~ Double, Monoid a)
=> (b -> a)
-> t b
-> a
vert = stack (Pair 0 -1)
-- | combine elements horizontally, with a premap
hori ::
(V a ~ V2, Foldable t, Juxtaposable a, Semigroup a, N a ~ Double, Monoid a)
=> (b -> a)
-> t b
-> a
hori = stack (Pair 1 0)
-- | horizontal separator
sepHori :: Double -> Chart b -> Chart b
sepHori s x = beside (r2 (0, -1)) x (strutX s)
-- | vertical separator
sepVert :: Double -> Chart b -> Chart b
sepVert s x = beside (r2 (1, 0)) x (strutY s)
data UColor a =
UColor
{ ucred :: a
, ucgreen :: a
, ucblue :: a
, ucopacity :: a
} deriving (Eq, Ord, Show, Generic)
| convert a UColor to an AlphaColour
acolor :: (Floating a, Num a, Ord a) => UColor a -> AlphaColour a
acolor (UColor r g b o) = withOpacity (sRGB r g b) o
| convert an AlphaColour to a UColor
ucolor :: (Floating a, Num a, Ord a) => AlphaColour a -> UColor a
ucolor a = let (RGB r g b) = toSRGB (a `over` black) in UColor r g b (alphaChannel a)
| convert a Colour to a UColor
ccolor :: (Floating a, Num a, Ord a) => Colour a -> UColor a
ccolor (toSRGB -> RGB r g b) = UColor r g b 1
-- | the official chart-unit blue
ublue :: UColor Double
ublue = UColor 0.365 0.647 0.855 0.5
-- | the official chart-unit grey
ugrey :: UColor Double
ugrey = UColor 0.4 0.4 0.4 1
-- | transparent
utrans :: UColor Double
utrans = UColor 0 0 0 0
-- | black
ublack :: UColor Double
ublack = UColor 0 0 0 1
-- | white
uwhite :: UColor Double
uwhite = UColor 1 1 1 1
-- | These are difficult to avoid
instance R1 Pair where
_x f (Pair a b) = (`Pair` b) <$> f a
instance R2 Pair where
_y f (Pair a b) = Pair a <$> f b
_xy f p = fmap (\(V2 a b) -> Pair a b) . f . (\(Pair a b) -> V2 a b) $ p
eps :: N [Point V2 Double]
eps = 1e-8
| the diagrams scaleX with a zero divide guard to avoid error throws
scaleX ::
(N t ~ Double, Transformable t, R2 (V t), Diagrams.Additive (V t))
=> Double
-> t
-> t
scaleX s =
Diagrams.scaleX
(if s == zero
then eps
else s)
| the diagrams scaleY with a zero divide guard to avoid error throws
scaleY ::
(N t ~ Double, Transformable t, R2 (V t), Diagrams.Additive (V t))
=> Double
-> t
-> t
scaleY s =
Diagrams.scaleY
(if s == zero
then eps
else s)
| the diagrams scale with a zero divide guard to avoid error throws
scale ::
(N t ~ Double, Transformable t, R2 (V t), Diagrams.Additive (V t))
=> Double
-> t
-> t
scale s =
Diagrams.scale
(if s == zero
then eps
else s)
| null | https://raw.githubusercontent.com/tonyday567/chart-unit/5c0aefee55383b7f2dc3d0745dc92f0bd9b0f24a/chart-unit/src/Chart/Core.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE GADTs #
- the size of the chart rendered as an image. Backends tend to shrink charts to fit the rectangle shape specified in the render function, and a loose sympathy is expected between the aspect and a chart's ultimate physical size.
> withHud
> defaultHudOptions
> widescreen

* Chart types
* Scaling
* Types
* Combinators
* Color
| chart-unit exposes the 'colour' and 'palette' libraries for color combinators
* Compatability
| determine the range of a double-containered set of data
| the aspect of a chart expressed as a ratio of x-plane : y-plane.
| golden ratio
| a 3:1 aspect
| horizontal alignment
| vertical alignment
| conversion of horizontal alignment to (one :: Range Double) limits
| svg text is forced to be lower left (-0.5) by default
| conversion of vertical alignment to (one :: Range Double) limits
| svg text is lower by default
| Orientation for an element. Watch this space for curvature!
| Placement of elements around (what is implicity but maybe shouldn't just be) a rectangular canvas
| position an element at a point
| foldMap for beside; stacking chart elements in a direction, with a premap
| combine elements vertically, with a premap
| combine elements horizontally, with a premap
| horizontal separator
| vertical separator
| the official chart-unit blue
| the official chart-unit grey
| transparent
| black
| white
| These are difficult to avoid | # LANGUAGE NoImplicitPrelude #
# LANGUAGE FlexibleContexts #
# LANGUAGE NegativeLiterals #
# OPTIONS_GHC -Wall #
# OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE CPP #
# LANGUAGE DeriveGeneric #
# LANGUAGE ViewPatterns #
#if ( __GLASGOW_HASKELL__ < 820 )
# OPTIONS_GHC -fno - warn - incomplete - patterns #
#endif
| In making a chart , there are three main size domains you have to be concerned about :
- the range of the data being charted . This range is often projected onto chart elements such as axes and labels . A data range in two dimensions is a ' Rect ' a.
- the scale of various chart primitives and elements . The overall dimensions of the chart canvas - the rectangular shape on which the data is represented - is referred to as an ' Aspect ' in the api , and is a wrapped ' ' to distinguish aspects from rect ranges . The default chart options tend to be callibrated to Aspects around widths of one .
Jumping ahead a bit , the code snippet below draws vertical lines using a data range of " Rect 0 12 0 0.2 " ( slightly different to the actual data range ) , using a widescreen ( 3:1 ) aspect , and renders the chart as a 300 by 120 pixel svg :
> scaleExample : : IO ( )
> scaleExample =
> fileSvg " other / scaleExample.svg " ( # size .~ Pair 300 120 $ def ) $
> ( 0 12 0 0.2 )
> ( lineChart ( repeat def ) )
> ( vlineOneD ( ( 0.01 * ) < $ > [ 0 .. 10 ] ) )
module Chart.Core
Chart
, range
, projectss
, aspect
, asquare
, sixbyfour
, golden
, widescreen
, skinny
, AlignH(..)
, AlignV(..)
, alignHU
, alignHTU
, alignVU
, alignVTU
, Orientation(..)
, Place(..)
| The concept of a point on a chart is the polymorphic ' R2 ' from the ' linear ' library . Diagrams most often uses ' Point ' , which is a wrapped ' V2 ' . The ' Pair ' type from ' numhask - range ' is often used as a point reference .
, positioned
, p_
, r_
, stack
, vert
, hori
, sepVert
, sepHori
, UColor(..)
, acolor
, ucolor
, ccolor
, ublue
, ugrey
, utrans
, ublack
, uwhite
, scaleX
, scaleY
, scale
) where
import Diagrams.Prelude
hiding (Color, D, aspect, project, scale, scaleX, scaleY, zero, over)
import qualified Diagrams.Prelude as Diagrams
import qualified Diagrams.TwoD.Text
import NumHask.Pair
import NumHask.Prelude
import NumHask.Rect
import NumHask.Range
import NumHask.Space
import Data.Colour (over)
| A Chart is simply a type synonym for a typical Diagrams object . A close relation to this type is ' Diagram ' ' B ' , but this usage tends to force a single backend ( B comes from the backend libraries ) , so making Chart b 's maintains backend polymorphism .
Just about everything - text , circles , lines , triangles , charts , axes , titles , legends etc - are ' Chart 's , which means that most things are amenable to full use of the combinatorially - inclined diagrams - lib .
type Chart b =
( Renderable (Path V2 Double) b
, Renderable (Diagrams.TwoD.Text.Text Double) b) =>
QDiagram b V2 Double Any
| project a double - containered set of data to a new Rect range
projectss ::
(Functor f, Functor g)
=> Rect Double
-> Rect Double
-> g (f (Pair Double))
-> g (f (Pair Double))
projectss r0 r1 xyss = map (project r0 r1) <$> xyss
range :: (Foldable f, Foldable g) => g (f (Pair Double)) -> Rect Double
range xyss = foldMap space xyss
aspect :: (CanRange a, Multiplicative a) => a -> Rect a
aspect a = Ranges ((a *) <$> one) one
| a 1:1 aspect
asquare :: Rect Double
asquare = aspect 1
| a 1.5:1 aspect
sixbyfour :: Rect Double
sixbyfour = aspect 1.5
golden :: Rect Double
golden = aspect 1.61803398875
widescreen :: Rect Double
widescreen = aspect 3
| a skinny 5:1 aspect
skinny :: Rect Double
skinny = aspect 5
data AlignH
= AlignLeft
| AlignCenter
| AlignRight
deriving (Show, Eq, Generic)
data AlignV
= AlignTop
| AlignMid
| AlignBottom
deriving (Show, Eq, Generic)
alignHU :: AlignH -> Double
alignHU a =
case a of
AlignLeft -> 0.5
AlignCenter -> 0
AlignRight -> -0.5
alignHTU :: AlignH -> Double
alignHTU a =
case a of
AlignLeft -> 0
AlignCenter -> -0.5
AlignRight -> -1
alignVU :: AlignV -> Double
alignVU a =
case a of
AlignTop -> -0.5
AlignMid -> 0
AlignBottom -> 0.5
alignVTU :: AlignV -> Double
alignVTU a =
case a of
AlignTop -> 0.5
AlignMid -> 0
AlignBottom -> -0.5
data Orientation
= Hori
| Vert
deriving (Show, Eq, Generic)
data Place
= PlaceLeft
| PlaceRight
| PlaceTop
| PlaceBottom
deriving (Show, Eq, Generic)
positioned :: (R2 r) => r Double -> Chart b -> Chart b
positioned p = moveTo (p_ p)
| convert an R2 to a diagrams Point
p_ :: (R2 r) => r Double -> Point V2 Double
p_ r = curry p2 (r ^. _x) (r ^. _y)
| convert an R2 to a V2
r_ :: R2 r => r a -> V2 a
r_ r = V2 (r ^. _x) (r ^. _y)
stack ::
( R2 r
, V a ~ V2
, Foldable t
, Juxtaposable a
, Semigroup a
, N a ~ Double
, Monoid a
)
=> r Double
-> (b -> a)
-> t b
-> a
stack dir f xs = foldr (\a x -> beside (r_ dir) (f a) x) mempty xs
vert ::
(V a ~ V2, Foldable t, Juxtaposable a, Semigroup a, N a ~ Double, Monoid a)
=> (b -> a)
-> t b
-> a
vert = stack (Pair 0 -1)
hori ::
(V a ~ V2, Foldable t, Juxtaposable a, Semigroup a, N a ~ Double, Monoid a)
=> (b -> a)
-> t b
-> a
hori = stack (Pair 1 0)
sepHori :: Double -> Chart b -> Chart b
sepHori s x = beside (r2 (0, -1)) x (strutX s)
sepVert :: Double -> Chart b -> Chart b
sepVert s x = beside (r2 (1, 0)) x (strutY s)
data UColor a =
UColor
{ ucred :: a
, ucgreen :: a
, ucblue :: a
, ucopacity :: a
} deriving (Eq, Ord, Show, Generic)
| convert a UColor to an AlphaColour
acolor :: (Floating a, Num a, Ord a) => UColor a -> AlphaColour a
acolor (UColor r g b o) = withOpacity (sRGB r g b) o
| convert an AlphaColour to a UColor
ucolor :: (Floating a, Num a, Ord a) => AlphaColour a -> UColor a
ucolor a = let (RGB r g b) = toSRGB (a `over` black) in UColor r g b (alphaChannel a)
| convert a Colour to a UColor
ccolor :: (Floating a, Num a, Ord a) => Colour a -> UColor a
ccolor (toSRGB -> RGB r g b) = UColor r g b 1
ublue :: UColor Double
ublue = UColor 0.365 0.647 0.855 0.5
ugrey :: UColor Double
ugrey = UColor 0.4 0.4 0.4 1
utrans :: UColor Double
utrans = UColor 0 0 0 0
ublack :: UColor Double
ublack = UColor 0 0 0 1
uwhite :: UColor Double
uwhite = UColor 1 1 1 1
instance R1 Pair where
_x f (Pair a b) = (`Pair` b) <$> f a
instance R2 Pair where
_y f (Pair a b) = Pair a <$> f b
_xy f p = fmap (\(V2 a b) -> Pair a b) . f . (\(Pair a b) -> V2 a b) $ p
eps :: N [Point V2 Double]
eps = 1e-8
| the diagrams scaleX with a zero divide guard to avoid error throws
scaleX ::
(N t ~ Double, Transformable t, R2 (V t), Diagrams.Additive (V t))
=> Double
-> t
-> t
scaleX s =
Diagrams.scaleX
(if s == zero
then eps
else s)
| the diagrams scaleY with a zero divide guard to avoid error throws
scaleY ::
(N t ~ Double, Transformable t, R2 (V t), Diagrams.Additive (V t))
=> Double
-> t
-> t
scaleY s =
Diagrams.scaleY
(if s == zero
then eps
else s)
| the diagrams scale with a zero divide guard to avoid error throws
scale ::
(N t ~ Double, Transformable t, R2 (V t), Diagrams.Additive (V t))
=> Double
-> t
-> t
scale s =
Diagrams.scale
(if s == zero
then eps
else s)
|
78d09fb53c11a41056cac6f040d18a3d33d056351205c161444551395a30ea9e | fogus/bacwn | magic.cljs | Copyright ( c ) . All rights reserved . The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; magic.clj
;;
A Clojure implementation of Datalog -- Magic Sets
;;
straszheimjeffrey ( gmail )
Created 18 Feburary 2009
Converted to Clojure1.4 by 2012 .
(ns fogus.datalog.bacwn.impl.magic
(:require [fogus.datalog.bacwn.impl.util :as util]
[fogus.datalog.bacwn.impl.literals :as literal]
[fogus.datalog.bacwn.impl.rules :as rule]
clojure.set))
;; =============================
;; Adornment
(defn adorn-query
"Adorn a query"
[q]
(literal/adorned-literal q (literal/get-self-bound-cs q)))
(defn adorn-rules-set
"Adorns the given rules-set for the given query. (rs) is a
rules-set, (q) is an adorned query."
[rs q]
(let [i-preds (rule/all-predicates rs)
p-map (rule/predicate-map rs)]
(loop [nrs rule/empty-rules-set ; The rules set being built
needed #{(literal/literal-predicate q)}]
(if (empty? needed)
nrs
(let [pred (first needed)
remaining (disj needed pred)
base-pred (literal/get-base-predicate pred)
bindings (literal/get-adorned-bindings pred)
new-rules (p-map base-pred)
new-adorned-rules (map (partial rule/compute-sip bindings i-preds)
new-rules)
new-nrs (reduce conj nrs new-adorned-rules)
current-preds (rule/all-predicates new-nrs)
not-needed? (fn [pred]
(or (current-preds pred)
(-> pred literal/get-base-predicate i-preds not)))
add-pred (fn [np pred]
(if (not-needed? pred) np (conj np pred)))
add-preds (fn [np rule]
(reduce add-pred np (map literal/literal-predicate (:body rule))))
new-needed (reduce add-preds remaining new-adorned-rules)]
(recur new-nrs new-needed))))))
;; =============================
Magic !
(defn seed-relation
"Given a magic form of a query, give back the literal form of its seed
relation"
[q]
(let [pred (-> q literal/literal-predicate literal/get-base-predicate)
bnds (-> q literal/literal-predicate literal/get-adorned-bindings)]
(with-meta (assoc q :predicate [pred :magic-seed bnds]) {})))
(defn seed-rule
"Given an adorned query, give back its seed rule"
[q]
(let [mq (literal/build-seed-bindings (literal/magic-literal q))
sr (seed-relation mq)]
(rule/build-rule mq [sr])))
(defn build-partial-tuple
"Given a query and a set of bindings, build a partial tuple needed
to extract the relation from the database."
[q bindings]
(into {} (remove nil? (map (fn [[k v :as pair]]
(if (util/is-var? v)
nil
(if (util/is-query-var? v)
[k (bindings v)]
pair)))
(:term-bindings q)))))
(defn seed-predicate-for-insertion
"Given a query, return the predicate to use for database insertion."
[q]
(let [seed (-> q seed-rule :body first)
columns (-> seed :term-bindings keys)
new-term-bindings (-> q :term-bindings (select-keys columns))]
(assoc seed :term-bindings new-term-bindings)))
(defn magic-transform
"Return a magic transformation of an adorned rules-set (rs). The
(i-preds) are the predicates of the intension database. These
default to the predicates within the rules-set."
([rs]
(magic-transform rs (rule/all-predicates rs)))
([rs i-preds]
(let [not-duplicate? (fn [l mh bd]
(or (not (empty? bd))
(not (= (literal/magic-literal l)
mh))))
xr (fn [rs rule]
(let [head (:head rule)
body (:body rule)
mh (literal/magic-literal head)
answer-rule (rule/build-rule head
(concat [mh] body))
step (fn [[rs bd] l]
(if (and (i-preds (literal/literal-predicate l))
(not-duplicate? l mh bd))
(let [nr (rule/build-rule (literal/magic-literal l)
(concat [mh] bd))]
[(conj rs nr) (conj bd l)])
[rs (conj bd l)]))
[nrs _] (reduce step [rs []] body)]
(conj nrs answer-rule)))]
(reduce xr rule/empty-rules-set rs))))
| null | https://raw.githubusercontent.com/fogus/bacwn/8aa39b6683db1772aedb7a0ecd7aa6372b72b231/src/clojurescript/fogus/datalog/bacwn/impl/magic.cljs | clojure | distribution terms for this software are covered by the Eclipse Public
License 1.0 (-1.0.php) which can
be found in the file epl-v10.html at the root of this distribution. By
using this software in any fashion, you are agreeing to be bound by the
terms of this license. You must not remove this notice, or any other,
from this software.
magic.clj
=============================
Adornment
The rules set being built
============================= | Copyright ( c ) . All rights reserved . The use and
A Clojure implementation of Datalog -- Magic Sets
straszheimjeffrey ( gmail )
Created 18 Feburary 2009
Converted to Clojure1.4 by 2012 .
(ns fogus.datalog.bacwn.impl.magic
(:require [fogus.datalog.bacwn.impl.util :as util]
[fogus.datalog.bacwn.impl.literals :as literal]
[fogus.datalog.bacwn.impl.rules :as rule]
clojure.set))
(defn adorn-query
"Adorn a query"
[q]
(literal/adorned-literal q (literal/get-self-bound-cs q)))
(defn adorn-rules-set
"Adorns the given rules-set for the given query. (rs) is a
rules-set, (q) is an adorned query."
[rs q]
(let [i-preds (rule/all-predicates rs)
p-map (rule/predicate-map rs)]
needed #{(literal/literal-predicate q)}]
(if (empty? needed)
nrs
(let [pred (first needed)
remaining (disj needed pred)
base-pred (literal/get-base-predicate pred)
bindings (literal/get-adorned-bindings pred)
new-rules (p-map base-pred)
new-adorned-rules (map (partial rule/compute-sip bindings i-preds)
new-rules)
new-nrs (reduce conj nrs new-adorned-rules)
current-preds (rule/all-predicates new-nrs)
not-needed? (fn [pred]
(or (current-preds pred)
(-> pred literal/get-base-predicate i-preds not)))
add-pred (fn [np pred]
(if (not-needed? pred) np (conj np pred)))
add-preds (fn [np rule]
(reduce add-pred np (map literal/literal-predicate (:body rule))))
new-needed (reduce add-preds remaining new-adorned-rules)]
(recur new-nrs new-needed))))))
Magic !
(defn seed-relation
"Given a magic form of a query, give back the literal form of its seed
relation"
[q]
(let [pred (-> q literal/literal-predicate literal/get-base-predicate)
bnds (-> q literal/literal-predicate literal/get-adorned-bindings)]
(with-meta (assoc q :predicate [pred :magic-seed bnds]) {})))
(defn seed-rule
"Given an adorned query, give back its seed rule"
[q]
(let [mq (literal/build-seed-bindings (literal/magic-literal q))
sr (seed-relation mq)]
(rule/build-rule mq [sr])))
(defn build-partial-tuple
"Given a query and a set of bindings, build a partial tuple needed
to extract the relation from the database."
[q bindings]
(into {} (remove nil? (map (fn [[k v :as pair]]
(if (util/is-var? v)
nil
(if (util/is-query-var? v)
[k (bindings v)]
pair)))
(:term-bindings q)))))
(defn seed-predicate-for-insertion
"Given a query, return the predicate to use for database insertion."
[q]
(let [seed (-> q seed-rule :body first)
columns (-> seed :term-bindings keys)
new-term-bindings (-> q :term-bindings (select-keys columns))]
(assoc seed :term-bindings new-term-bindings)))
(defn magic-transform
"Return a magic transformation of an adorned rules-set (rs). The
(i-preds) are the predicates of the intension database. These
default to the predicates within the rules-set."
([rs]
(magic-transform rs (rule/all-predicates rs)))
([rs i-preds]
(let [not-duplicate? (fn [l mh bd]
(or (not (empty? bd))
(not (= (literal/magic-literal l)
mh))))
xr (fn [rs rule]
(let [head (:head rule)
body (:body rule)
mh (literal/magic-literal head)
answer-rule (rule/build-rule head
(concat [mh] body))
step (fn [[rs bd] l]
(if (and (i-preds (literal/literal-predicate l))
(not-duplicate? l mh bd))
(let [nr (rule/build-rule (literal/magic-literal l)
(concat [mh] bd))]
[(conj rs nr) (conj bd l)])
[rs (conj bd l)]))
[nrs _] (reduce step [rs []] body)]
(conj nrs answer-rule)))]
(reduce xr rule/empty-rules-set rs))))
|
855626025d91efe47f28f7790d2622744279db17a59587b3caf3ff127f1885ad | plewto/Cadejo | matrix_editor.clj | (ns cadejo.instruments.alias.editor.matrix-editor
(:require [cadejo.instruments.alias.constants :as constants])
(:require [cadejo.ui.instruments.subedit :as subedit])
(:require [cadejo.ui.util.lnf :as lnf])
(:require [cadejo.ui.util.sgwr-factory :as sfactory])
(:require [cadejo.util.math :as math])
(:require [sgwr.tools.multistate-button :as msb])
(:require [sgwr.components.text :as text])
(:require [sgwr.util.color :as uc])
(:require [seesaw.core :as ss]))
(def ^:private c1 (lnf/text))
(def ^:private c2 (lnf/text))
(def ^:private c3 (uc/color :red))
(def ^:private general-bus-states
[[:con "CON" c1]
[:a " A " c2][:b " B " c2][:c " C " c2][:d " D " c2]
[:e " E " c2][:f " F " c2][:g " G " c2][:h " H " c2]
[:off "OFF" c1]])
(def ^:private control-bus-states
[[:con " ONE " c1]
[:env1 "ENV 1 " c2][:env2 "ENV 2 " c2][:env3 "ENV 3 " c2]
[:lfo1 "LFO 1 " c2][:lfo2 "LFO 2 " c2][:lfo3 "LFO 3 " c2]
[:stp1 "STEP 1" c2][:stp2 "STEP 2" c2]
[:div1 "DIV 1 " c2][:div2 "DIV 2 " c2][:div "DIV " c2]
[:lfnse "LFNSE " c2][:sh " SH " c2]
[:freq " FREQ " c2][:period "Period" c2][:note " Note " c2]
[:prss " Prss " c2][:vel " Vel " c2]
[:cca " CCA " c2][:ccb " CCB " c2][:ccc " CCC " c2][:ccd " CCD " c2]
[:a " A " c3][:b " B " c3][:c " C " c3][:d " D " c3]
[:e " E " c3][:f " F " c3][:g " G " c3][:h " H " c3]
[:gate " Gate " c2][:off " OFF " c1]])
;; Returns sgwr multi-state button for selection of general matrix bus
;;
(defn source-button [drw ieditor id p0]
(let [w 40
h 40
c1 ( lnf / text )
c2 ( lnf / selected - text )
action (fn [b _]
(let [state (msb/current-multistate-button-state b)]
(.set-param! ieditor id (first state))
(.status! ieditor (format "[%s] -> %s" id (second state)))))
msb (msb/text-multistate-button (.tool-root drw) p0 general-bus-states
:click-action action
:w w :h h
:gap 4)]
msb))
Returns button for bus selection within control block
;;
(defn control-source-button [drw ieditor id p0]
(let [w 50
h 40
action (fn [b _]
(let [state (msb/current-multistate-button-state b)]
(.set-param! ieditor id (first state))
(.status! ieditor (format "[%s] -> %s" id (second state)))))
msb (msb/text-multistate-button (.tool-root drw) p0 control-bus-states
:click-action action
:text-size 6.0
:rim-color (lnf/button-border)
:w w :h h :gap 4)]
msb))
;; Places matrix routing overview onto sgwr drawing
;; Returns function to update overview
;;
(defn matrix-overview [drw p0]
(let[[x0 y0] p0
delta-y 20
c (lnf/selected-text)
txobj (fn [pos bus]
(let [obj (text/text (.root drw)
[x0 (+ y0 (* pos delta-y))]
""
:id :matrix-overview
:style :mono
:size 6
:color (lnf/text))]
(.put-property! obj :bus-name (.toUpperCase bus))
(.put-property! obj :bus bus)
obj))
txa (txobj 0 "a")
txb (txobj 1 "b")
txc (txobj 2 "c")
txd (txobj 3 "d")
txe (txobj 4 "e")
txf (txobj 5 "f")
txg (txobj 6 "g")
txh (txobj 7 "h")
sync-txtobj (fn [obj dmap]
(let [bus (.get-property obj :bus)
param-s1 (keyword (format "%s-source1" bus))
param-s2 (keyword (format "%s-source2" bus))]
(.put-property! obj :text
(format "%s <-- %-8s %-8s"
(.get-property obj :bus-name)
(constants/reverse-control-bus-map (param-s1 dmap))
(constants/reverse-control-bus-map (param-s2 dmap))))))
sync-fn (fn [dmap]
(doseq [tx [txa txb txc txd txe txf txg txh]]
(sync-txtobj tx dmap)))]
sync-fn))
(def ^:private src->button-state {0 0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 6,
7 7, 8 8, 9 9, 10 10, 11 11,
12 12, 13 13, 14 14, 15 15, 16 16, 17 17,
18 18, 19 19, 20 20, 21 21, 22 22,
31 23, 32 24})
(def ^:private width 2200)
(def ^:private height 550)
(declare draw-background)
(defn matrix-editor [ied]
(let [p0 [0 height]
drw (sfactory/sgwr-drawing width height)
x0 100
x-space 100
y-space 50
y0 100
y-text (+ y0 120)
states (let [acc* (atom [])]
(doseq [n (filter (fn [q](or (< q 23)(>= q 31)))(range 0 33 1))]
(swap! acc* (fn [q](conj q [(keyword (str n)) (name (constants/reverse-control-bus-map n)) (lnf/text)]))))
@acc*)
action (fn [b _]
(let [param (.get-property b :param)
state (math/str->int (name (second (msb/current-multistate-button-state b))))]
(.set-param! ied param state)))
assignments (let [acc* (atom [])
x* (atom x0)]
(doseq [bus '[a b c d e f g h]]
(sfactory/label drw [@x* y-text] (format "%s" (.toUpperCase (str bus))) :size 8.0 :offset [35 0])
(doseq [n [0 1]]
(let [param (keyword (format "%s-source%s" bus (inc n)))
b (msb/text-multistate-button (.tool-root drw)
[@x* (+ y0 (* n y-space))]
states
:click-action action
:text-color (lnf/text)
:rim-color (lnf/button-border)
:rim-radius 4
:w 80 :h 40 :gap 8)]
(.put-property! b :param param)
(swap! acc* (fn [q](conj q b)))))
(swap! x* (fn [q](+ q x-space))))
@acc*)
pan-main (ss/scrollable (ss/vertical-panel :items [(.canvas drw)]))
widget-map {:pan-main pan-main
:drawing drw}
ed (reify subedit/InstrumentSubEditor
(widgets [this] widget-map)
(widget [this key](key widget-map))
(parent [this] ied)
(parent! [this _] ied) ;;' ignore
(status! [this msg](.status! ied msg))
(warning! [this msg](.warning! ied msg))
(set-param! [this param value](.set-param! ied param value))
(init! [this] ) ;; not implemented
(sync-ui! [this]
(let [dmap (.current-data (.bank (.parent-performance ied)))]
(doseq [b assignments]
(let [param (.get-property b :param)
srcnum (param dmap)
state-index (get src->button-state srcnum)]
(msb/set-multistate-button-state! b state-index false)))
(.render drw))))]
(sfactory/label drw [x0 y-text] "Bus" :offset [-50 0])
(let [x 900
y* (atom y0)
y-delta 15]
(sfactory/label drw [x @y*] "Legend:")
(doseq [s ["con - Constant 1"
"env1 - Envelope 1"
"env2 - Envelope 2"
"env3 - Envelope 3 (main amp envelope)"
"lfo1 - LFO 1 (default vibrato)"
"lfo2 - LFO 2"
"lfo3 - LFO 3"
"step1 - Step counter 1"
"step2 - Step counter 2"
"div1 - Frequency Divider (odd)"
"div2 - Frequency Divider (even)"
"div - Sum div1 + div2"
"lfnse - Low Frequency Noise"
"sh - Sample & Hold"
"freq - Key frequency (hz)"
"period - 1/freq"
"keynum - MIDI key number"
"press - MIDI Pressure"
"vel - MIDI Velocity"
"cca - MIDI cc a (default 1)"
"ccb - MIDI cc b"
"ccc - MIDI cc c"
"ccd - MIDI cc d"
"gate - Key gate signal"
"off - Disable bus"]]
(sfactory/label drw [x @y*] s :offset [10 y-delta])
(swap! y* (fn [q](+ q y-delta)))))
(sfactory/title drw [(- x0 0)(- y0 40)] "Matrix Bus Assignments")
ed))
| null | https://raw.githubusercontent.com/plewto/Cadejo/2a98610ce1f5fe01dce5f28d986a38c86677fd67/src/cadejo/instruments/alias/editor/matrix_editor.clj | clojure | Returns sgwr multi-state button for selection of general matrix bus
Places matrix routing overview onto sgwr drawing
Returns function to update overview
' ignore
not implemented | (ns cadejo.instruments.alias.editor.matrix-editor
(:require [cadejo.instruments.alias.constants :as constants])
(:require [cadejo.ui.instruments.subedit :as subedit])
(:require [cadejo.ui.util.lnf :as lnf])
(:require [cadejo.ui.util.sgwr-factory :as sfactory])
(:require [cadejo.util.math :as math])
(:require [sgwr.tools.multistate-button :as msb])
(:require [sgwr.components.text :as text])
(:require [sgwr.util.color :as uc])
(:require [seesaw.core :as ss]))
(def ^:private c1 (lnf/text))
(def ^:private c2 (lnf/text))
(def ^:private c3 (uc/color :red))
(def ^:private general-bus-states
[[:con "CON" c1]
[:a " A " c2][:b " B " c2][:c " C " c2][:d " D " c2]
[:e " E " c2][:f " F " c2][:g " G " c2][:h " H " c2]
[:off "OFF" c1]])
(def ^:private control-bus-states
[[:con " ONE " c1]
[:env1 "ENV 1 " c2][:env2 "ENV 2 " c2][:env3 "ENV 3 " c2]
[:lfo1 "LFO 1 " c2][:lfo2 "LFO 2 " c2][:lfo3 "LFO 3 " c2]
[:stp1 "STEP 1" c2][:stp2 "STEP 2" c2]
[:div1 "DIV 1 " c2][:div2 "DIV 2 " c2][:div "DIV " c2]
[:lfnse "LFNSE " c2][:sh " SH " c2]
[:freq " FREQ " c2][:period "Period" c2][:note " Note " c2]
[:prss " Prss " c2][:vel " Vel " c2]
[:cca " CCA " c2][:ccb " CCB " c2][:ccc " CCC " c2][:ccd " CCD " c2]
[:a " A " c3][:b " B " c3][:c " C " c3][:d " D " c3]
[:e " E " c3][:f " F " c3][:g " G " c3][:h " H " c3]
[:gate " Gate " c2][:off " OFF " c1]])
(defn source-button [drw ieditor id p0]
(let [w 40
h 40
c1 ( lnf / text )
c2 ( lnf / selected - text )
action (fn [b _]
(let [state (msb/current-multistate-button-state b)]
(.set-param! ieditor id (first state))
(.status! ieditor (format "[%s] -> %s" id (second state)))))
msb (msb/text-multistate-button (.tool-root drw) p0 general-bus-states
:click-action action
:w w :h h
:gap 4)]
msb))
Returns button for bus selection within control block
(defn control-source-button [drw ieditor id p0]
(let [w 50
h 40
action (fn [b _]
(let [state (msb/current-multistate-button-state b)]
(.set-param! ieditor id (first state))
(.status! ieditor (format "[%s] -> %s" id (second state)))))
msb (msb/text-multistate-button (.tool-root drw) p0 control-bus-states
:click-action action
:text-size 6.0
:rim-color (lnf/button-border)
:w w :h h :gap 4)]
msb))
(defn matrix-overview [drw p0]
(let[[x0 y0] p0
delta-y 20
c (lnf/selected-text)
txobj (fn [pos bus]
(let [obj (text/text (.root drw)
[x0 (+ y0 (* pos delta-y))]
""
:id :matrix-overview
:style :mono
:size 6
:color (lnf/text))]
(.put-property! obj :bus-name (.toUpperCase bus))
(.put-property! obj :bus bus)
obj))
txa (txobj 0 "a")
txb (txobj 1 "b")
txc (txobj 2 "c")
txd (txobj 3 "d")
txe (txobj 4 "e")
txf (txobj 5 "f")
txg (txobj 6 "g")
txh (txobj 7 "h")
sync-txtobj (fn [obj dmap]
(let [bus (.get-property obj :bus)
param-s1 (keyword (format "%s-source1" bus))
param-s2 (keyword (format "%s-source2" bus))]
(.put-property! obj :text
(format "%s <-- %-8s %-8s"
(.get-property obj :bus-name)
(constants/reverse-control-bus-map (param-s1 dmap))
(constants/reverse-control-bus-map (param-s2 dmap))))))
sync-fn (fn [dmap]
(doseq [tx [txa txb txc txd txe txf txg txh]]
(sync-txtobj tx dmap)))]
sync-fn))
(def ^:private src->button-state {0 0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 6,
7 7, 8 8, 9 9, 10 10, 11 11,
12 12, 13 13, 14 14, 15 15, 16 16, 17 17,
18 18, 19 19, 20 20, 21 21, 22 22,
31 23, 32 24})
(def ^:private width 2200)
(def ^:private height 550)
(declare draw-background)
(defn matrix-editor [ied]
(let [p0 [0 height]
drw (sfactory/sgwr-drawing width height)
x0 100
x-space 100
y-space 50
y0 100
y-text (+ y0 120)
states (let [acc* (atom [])]
(doseq [n (filter (fn [q](or (< q 23)(>= q 31)))(range 0 33 1))]
(swap! acc* (fn [q](conj q [(keyword (str n)) (name (constants/reverse-control-bus-map n)) (lnf/text)]))))
@acc*)
action (fn [b _]
(let [param (.get-property b :param)
state (math/str->int (name (second (msb/current-multistate-button-state b))))]
(.set-param! ied param state)))
assignments (let [acc* (atom [])
x* (atom x0)]
(doseq [bus '[a b c d e f g h]]
(sfactory/label drw [@x* y-text] (format "%s" (.toUpperCase (str bus))) :size 8.0 :offset [35 0])
(doseq [n [0 1]]
(let [param (keyword (format "%s-source%s" bus (inc n)))
b (msb/text-multistate-button (.tool-root drw)
[@x* (+ y0 (* n y-space))]
states
:click-action action
:text-color (lnf/text)
:rim-color (lnf/button-border)
:rim-radius 4
:w 80 :h 40 :gap 8)]
(.put-property! b :param param)
(swap! acc* (fn [q](conj q b)))))
(swap! x* (fn [q](+ q x-space))))
@acc*)
pan-main (ss/scrollable (ss/vertical-panel :items [(.canvas drw)]))
widget-map {:pan-main pan-main
:drawing drw}
ed (reify subedit/InstrumentSubEditor
(widgets [this] widget-map)
(widget [this key](key widget-map))
(parent [this] ied)
(status! [this msg](.status! ied msg))
(warning! [this msg](.warning! ied msg))
(set-param! [this param value](.set-param! ied param value))
(sync-ui! [this]
(let [dmap (.current-data (.bank (.parent-performance ied)))]
(doseq [b assignments]
(let [param (.get-property b :param)
srcnum (param dmap)
state-index (get src->button-state srcnum)]
(msb/set-multistate-button-state! b state-index false)))
(.render drw))))]
(sfactory/label drw [x0 y-text] "Bus" :offset [-50 0])
(let [x 900
y* (atom y0)
y-delta 15]
(sfactory/label drw [x @y*] "Legend:")
(doseq [s ["con - Constant 1"
"env1 - Envelope 1"
"env2 - Envelope 2"
"env3 - Envelope 3 (main amp envelope)"
"lfo1 - LFO 1 (default vibrato)"
"lfo2 - LFO 2"
"lfo3 - LFO 3"
"step1 - Step counter 1"
"step2 - Step counter 2"
"div1 - Frequency Divider (odd)"
"div2 - Frequency Divider (even)"
"div - Sum div1 + div2"
"lfnse - Low Frequency Noise"
"sh - Sample & Hold"
"freq - Key frequency (hz)"
"period - 1/freq"
"keynum - MIDI key number"
"press - MIDI Pressure"
"vel - MIDI Velocity"
"cca - MIDI cc a (default 1)"
"ccb - MIDI cc b"
"ccc - MIDI cc c"
"ccd - MIDI cc d"
"gate - Key gate signal"
"off - Disable bus"]]
(sfactory/label drw [x @y*] s :offset [10 y-delta])
(swap! y* (fn [q](+ q y-delta)))))
(sfactory/title drw [(- x0 0)(- y0 40)] "Matrix Bus Assignments")
ed))
|
a7bf077860cffad375b68400c684f003ee80d12ce8b6a3a05a605e92010dbc43 | andys8/git-brunch | Spec.hs | import Data.Text (Text)
import Git
import Test.Hspec
main :: IO ()
main = hspec $
describe "Git.toBranch" $ do
it "returns a remote branch is starts with remote" $ do
toBranches "remotes/origin/master" `shouldBe` [BranchRemote "origin" "master"]
it "ignores leading spaces" $ do
toBranches " master" `shouldBe` [BranchLocal "master"]
it "detects current branch by asterik" $ do
toBranches "* master" `shouldBe` [BranchCurrent "master"]
it "returns a local branch" $ do
toBranches "master" `shouldBe` [BranchLocal "master"]
it "returns a branch with head in name" $ do
toBranches "updateHead" `shouldBe` [BranchLocal "updateHead"]
it "ignores HEAD" $ do
toBranches "HEAD" `shouldBe` []
it "ignores empty" $ do
toBranches "" `shouldBe` []
it "ignores origin/HEAD" $ do
toBranches "origin/HEAD" `shouldBe` []
it "ignores detatched HEAD" $ do
toBranches "* (HEAD detached at f01a202)" `shouldBe` []
it "ignores 'no branch' during rebase" $ do
toBranches "* (no branch, rebasing branch-name)" `shouldBe` []
it "parses sample output" $ do
toBranches sampleOutput
`shouldBe` [ BranchLocal "experimental/failing-debug-log-demo"
, BranchLocal "gh-pages"
, BranchLocal "master"
, BranchLocal "wip/delete-as-action"
, BranchRemote "origin" "experimental/failing-debug-log-demo"
, BranchRemote "origin" "gh-pages"
, BranchRemote "origin" "master"
]
sampleOutput :: Text
sampleOutput =
"* (HEAD detached at f01a202)\n"
<> " experimental/failing-debug-log-demo\n"
<> " gh-pages\n"
<> " master\n"
<> " wip/delete-as-action\n"
<> " remotes/origin/HEAD -> origin/master\n"
<> " remotes/origin/experimental/failing-debug-log-demo\n"
<> " remotes/origin/gh-pages\n"
<> " remotes/origin/master"
| null | https://raw.githubusercontent.com/andys8/git-brunch/fe1989c82a912d689cd23bf8fbdd4cb6927d40a9/test/Spec.hs | haskell | import Data.Text (Text)
import Git
import Test.Hspec
main :: IO ()
main = hspec $
describe "Git.toBranch" $ do
it "returns a remote branch is starts with remote" $ do
toBranches "remotes/origin/master" `shouldBe` [BranchRemote "origin" "master"]
it "ignores leading spaces" $ do
toBranches " master" `shouldBe` [BranchLocal "master"]
it "detects current branch by asterik" $ do
toBranches "* master" `shouldBe` [BranchCurrent "master"]
it "returns a local branch" $ do
toBranches "master" `shouldBe` [BranchLocal "master"]
it "returns a branch with head in name" $ do
toBranches "updateHead" `shouldBe` [BranchLocal "updateHead"]
it "ignores HEAD" $ do
toBranches "HEAD" `shouldBe` []
it "ignores empty" $ do
toBranches "" `shouldBe` []
it "ignores origin/HEAD" $ do
toBranches "origin/HEAD" `shouldBe` []
it "ignores detatched HEAD" $ do
toBranches "* (HEAD detached at f01a202)" `shouldBe` []
it "ignores 'no branch' during rebase" $ do
toBranches "* (no branch, rebasing branch-name)" `shouldBe` []
it "parses sample output" $ do
toBranches sampleOutput
`shouldBe` [ BranchLocal "experimental/failing-debug-log-demo"
, BranchLocal "gh-pages"
, BranchLocal "master"
, BranchLocal "wip/delete-as-action"
, BranchRemote "origin" "experimental/failing-debug-log-demo"
, BranchRemote "origin" "gh-pages"
, BranchRemote "origin" "master"
]
sampleOutput :: Text
sampleOutput =
"* (HEAD detached at f01a202)\n"
<> " experimental/failing-debug-log-demo\n"
<> " gh-pages\n"
<> " master\n"
<> " wip/delete-as-action\n"
<> " remotes/origin/HEAD -> origin/master\n"
<> " remotes/origin/experimental/failing-debug-log-demo\n"
<> " remotes/origin/gh-pages\n"
<> " remotes/origin/master"
|
|
68e9ee67396a5efb961c6323377b7975dbcaac93bda413b0d051f61317ca8c4a | erlware/erlware_commons | ec_git_vsn.erl | %%% vi:ts=4 sw=4 et
%%%-------------------------------------------------------------------
@author < >
2011 Erlware , LLC .
%%% @doc
%%% This provides an implementation of the ec_vsn for git. That is
%%% it is capable of returning a semver for a git repository
%%% see ec_vsn
%%% see ec_semver
%%% @end
%%%-------------------------------------------------------------------
-module(ec_git_vsn).
-behaviour(ec_vsn).
%% API
-export([new/0,
vsn/1]).
-export_type([t/0]).
%%%===================================================================
%%% Types
%%%===================================================================
%% This should be opaque, but that kills dialyzer so for now we export it
%% however you should not rely on the internal representation here
-type t() :: {}.
%%%===================================================================
%%% API
%%%===================================================================
-spec new() -> t().
new() ->
{}.
-spec vsn(t()|string()) -> {ok, string()} | {error, Reason::any()}.
vsn(Data) ->
{Vsn, RawRef, RawCount} = collect_default_refcount(Data),
{ok, build_vsn_string(Vsn, RawRef, RawCount)}.
%%%===================================================================
%%% Internal Functions
%%%===================================================================
collect_default_refcount(Data) ->
%% Get the tag timestamp and minimal ref from the system. The
%% timestamp is really important from an ordering perspective.
RawRef = os:cmd("git log -n 1 --pretty=format:'%h\n' "),
{Tag, TagVsn} = parse_tags(Data),
RawCount =
case Tag of
undefined ->
os:cmd("git rev-list --count HEAD");
_ ->
get_patch_count(Tag)
end,
{TagVsn, RawRef, RawCount}.
build_vsn_string(Vsn, RawRef, RawCount) ->
Cleanup the tag and the Ref information . Basically leading ' v 's and
%% whitespace needs to go away.
RefTag = [".ref", re:replace(RawRef, "\\s", "", [global])],
Count = erlang:iolist_to_binary(re:replace(RawCount, "\\s", "", [global])),
%% Create the valid [semver]() version from the tag
case Count of
<<"0">> ->
erlang:binary_to_list(erlang:iolist_to_binary(Vsn));
_ ->
erlang:binary_to_list(erlang:iolist_to_binary([Vsn, "+build.",
Count, RefTag]))
end.
get_patch_count(RawRef) ->
Ref = re:replace(RawRef, "\\s", "", [global]),
Cmd = io_lib:format("git rev-list --count ~ts..HEAD",
[Ref]),
case os:cmd(Cmd) of
"fatal: " ++ _ ->
0;
Count ->
Count
end.
-spec parse_tags(t()|string()) -> {string()|undefined, ec_semver:version_string()}.
parse_tags({}) ->
parse_tags("");
parse_tags(Pattern) ->
Cmd = io_lib:format("git describe --abbrev=0 --tags --match \"~ts*\"", [Pattern]),
Tag = os:cmd(Cmd),
case Tag of
"fatal: " ++ _ ->
{undefined, ""};
_ ->
Vsn = slice(Tag, len(Pattern)),
Vsn1 = trim(trim(Vsn, left, "v"), right, "\n"),
{Tag, Vsn1}
end.
-ifdef(unicode_str).
len(Str) -> string:length(Str).
trim(Str, right, Chars) -> string:trim(Str, trailing, Chars);
trim(Str, left, Chars) -> string:trim(Str, leading, Chars).
slice(Str, Len) -> string:slice(Str, Len).
-else.
len(Str) -> string:len(Str).
trim(Str, Dir, [Chars|_]) -> string:strip(Str, Dir, Chars).
slice(Str, Len) -> string:substr(Str, Len + 1).
-endif.
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
parse_tags_test() ->
?assertEqual({undefined, ""}, parse_tags("a.b.c")).
get_patch_count_test() ->
?assertEqual(0, get_patch_count("a.b.c")).
collect_default_refcount_test() ->
?assertMatch({"", _, _}, collect_default_refcount("a.b.c")).
-endif.
| null | https://raw.githubusercontent.com/erlware/erlware_commons/ad559ae1f5f4cabdcc59899e20f4d3db78177574/src/ec_git_vsn.erl | erlang | vi:ts=4 sw=4 et
-------------------------------------------------------------------
@doc
This provides an implementation of the ec_vsn for git. That is
it is capable of returning a semver for a git repository
see ec_vsn
see ec_semver
@end
-------------------------------------------------------------------
API
===================================================================
Types
===================================================================
This should be opaque, but that kills dialyzer so for now we export it
however you should not rely on the internal representation here
===================================================================
API
===================================================================
===================================================================
Internal Functions
===================================================================
Get the tag timestamp and minimal ref from the system. The
timestamp is really important from an ordering perspective.
whitespace needs to go away.
Create the valid [semver]() version from the tag | @author < >
2011 Erlware , LLC .
-module(ec_git_vsn).
-behaviour(ec_vsn).
-export([new/0,
vsn/1]).
-export_type([t/0]).
-type t() :: {}.
-spec new() -> t().
new() ->
{}.
-spec vsn(t()|string()) -> {ok, string()} | {error, Reason::any()}.
vsn(Data) ->
{Vsn, RawRef, RawCount} = collect_default_refcount(Data),
{ok, build_vsn_string(Vsn, RawRef, RawCount)}.
collect_default_refcount(Data) ->
RawRef = os:cmd("git log -n 1 --pretty=format:'%h\n' "),
{Tag, TagVsn} = parse_tags(Data),
RawCount =
case Tag of
undefined ->
os:cmd("git rev-list --count HEAD");
_ ->
get_patch_count(Tag)
end,
{TagVsn, RawRef, RawCount}.
build_vsn_string(Vsn, RawRef, RawCount) ->
Cleanup the tag and the Ref information . Basically leading ' v 's and
RefTag = [".ref", re:replace(RawRef, "\\s", "", [global])],
Count = erlang:iolist_to_binary(re:replace(RawCount, "\\s", "", [global])),
case Count of
<<"0">> ->
erlang:binary_to_list(erlang:iolist_to_binary(Vsn));
_ ->
erlang:binary_to_list(erlang:iolist_to_binary([Vsn, "+build.",
Count, RefTag]))
end.
get_patch_count(RawRef) ->
Ref = re:replace(RawRef, "\\s", "", [global]),
Cmd = io_lib:format("git rev-list --count ~ts..HEAD",
[Ref]),
case os:cmd(Cmd) of
"fatal: " ++ _ ->
0;
Count ->
Count
end.
-spec parse_tags(t()|string()) -> {string()|undefined, ec_semver:version_string()}.
parse_tags({}) ->
parse_tags("");
parse_tags(Pattern) ->
Cmd = io_lib:format("git describe --abbrev=0 --tags --match \"~ts*\"", [Pattern]),
Tag = os:cmd(Cmd),
case Tag of
"fatal: " ++ _ ->
{undefined, ""};
_ ->
Vsn = slice(Tag, len(Pattern)),
Vsn1 = trim(trim(Vsn, left, "v"), right, "\n"),
{Tag, Vsn1}
end.
-ifdef(unicode_str).
len(Str) -> string:length(Str).
trim(Str, right, Chars) -> string:trim(Str, trailing, Chars);
trim(Str, left, Chars) -> string:trim(Str, leading, Chars).
slice(Str, Len) -> string:slice(Str, Len).
-else.
len(Str) -> string:len(Str).
trim(Str, Dir, [Chars|_]) -> string:strip(Str, Dir, Chars).
slice(Str, Len) -> string:substr(Str, Len + 1).
-endif.
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
parse_tags_test() ->
?assertEqual({undefined, ""}, parse_tags("a.b.c")).
get_patch_count_test() ->
?assertEqual(0, get_patch_count("a.b.c")).
collect_default_refcount_test() ->
?assertMatch({"", _, _}, collect_default_refcount("a.b.c")).
-endif.
|
693969586eab37028ac0b9957ce589a44240ac1ccd8537f8d9959f0511341d86 | UChicago-PL/smyth | timer.mli | (** A collection of timers used to cut off program execution early. *)
module Single : sig
(** The available single timers. *)
type t =
| Total (** The timer for the total synthesis time. *)
| Eval (** The timer for live evaluation and resumption. *)
val start : t -> unit
(** Starts the timer. *)
val elapsed : t -> float
(** Returns how much time has elapsed since starting the timer. *)
val check : t -> bool
(** Returns [true] if the timer is still running, and [false] if the elapsed
time is greater than the cutoff. *)
end
(** A countdown timer that, once started, continues to completion. *)
module Multi : sig
(** The available multi timers. *)
type t =
| Guess (** The timer for raw term enumeration. *)
val reset : t -> unit
(** Resets the timer. *)
val accumulate : t -> (unit -> 'a) -> 'a
(** Accumulates additional time on the timer. *)
val check : t -> bool
(** Returns [true] if the timer is still running, and [false] if the elapsed
time is greater than the cutoff. *)
end
(** A resettable countdown timer that accumulates time every time the {!accumulate}
function is called. *)
val itimer_timeout :
string ->
float ->
('a -> 'b) ->
'a ->
'b ->
'b * float * bool
(** A fragile hard-cutoff timer that uses Unix itimers. *)
| null | https://raw.githubusercontent.com/UChicago-PL/smyth/08fea281f70d3ee604fde9dde140c8a570d6905d/lib/smyth/timer.mli | ocaml | * A collection of timers used to cut off program execution early.
* The available single timers.
* The timer for the total synthesis time.
* The timer for live evaluation and resumption.
* Starts the timer.
* Returns how much time has elapsed since starting the timer.
* Returns [true] if the timer is still running, and [false] if the elapsed
time is greater than the cutoff.
* A countdown timer that, once started, continues to completion.
* The available multi timers.
* The timer for raw term enumeration.
* Resets the timer.
* Accumulates additional time on the timer.
* Returns [true] if the timer is still running, and [false] if the elapsed
time is greater than the cutoff.
* A resettable countdown timer that accumulates time every time the {!accumulate}
function is called.
* A fragile hard-cutoff timer that uses Unix itimers. |
module Single : sig
type t =
val start : t -> unit
val elapsed : t -> float
val check : t -> bool
end
module Multi : sig
type t =
val reset : t -> unit
val accumulate : t -> (unit -> 'a) -> 'a
val check : t -> bool
end
val itimer_timeout :
string ->
float ->
('a -> 'b) ->
'a ->
'b ->
'b * float * bool
|
b52f9e5f391d97cfc80d609311348acbb03f935b93b37d7bb181f99d96894219 | input-output-hk/plutus | Mark.hs | -- editorconfig-checker-disable-file
module PlutusCore.Mark
( markNonFreshTerm
, markNonFreshType
, markNonFreshProgram
) where
import Data.Set.Lens (setOf)
import PlutusCore.Core
import PlutusCore.Name
import PlutusCore.Quote
-- | Marks all the 'Unique's in a type as used, so they will not be generated in future. Useful if you
-- have a type which was not generated in 'Quote'.
markNonFreshType
:: (HasUniques (Type tyname uni ann), MonadQuote m)
=> Type tyname uni ann -> m ()
markNonFreshType = markNonFreshMax . setOf typeUniquesDeep
-- | Marks all the 'Unique's in a term as used, so they will not be generated in future. Useful if you
-- have a term which was not generated in 'Quote'.
markNonFreshTerm
:: (HasUniques (Term tyname name uni fun ann), MonadQuote m)
=> Term tyname name uni fun ann -> m ()
markNonFreshTerm = markNonFreshMax . setOf termUniquesDeep
-- | Marks all the 'Unique's in a program as used, so they will not be generated in future. Useful if you
-- have a program which was not generated in 'Quote'.
markNonFreshProgram
:: (HasUnique tyname TypeUnique, HasUnique name TermUnique, MonadQuote m)
=> Program tyname name uni fun ann
-> m ()
markNonFreshProgram (Program _ _ body) = markNonFreshTerm body
| null | https://raw.githubusercontent.com/input-output-hk/plutus/cbd5f37288eb06738be28fc49af6a6b612e6c5fc/plutus-core/plutus-core/src/PlutusCore/Mark.hs | haskell | editorconfig-checker-disable-file
| Marks all the 'Unique's in a type as used, so they will not be generated in future. Useful if you
have a type which was not generated in 'Quote'.
| Marks all the 'Unique's in a term as used, so they will not be generated in future. Useful if you
have a term which was not generated in 'Quote'.
| Marks all the 'Unique's in a program as used, so they will not be generated in future. Useful if you
have a program which was not generated in 'Quote'. | module PlutusCore.Mark
( markNonFreshTerm
, markNonFreshType
, markNonFreshProgram
) where
import Data.Set.Lens (setOf)
import PlutusCore.Core
import PlutusCore.Name
import PlutusCore.Quote
markNonFreshType
:: (HasUniques (Type tyname uni ann), MonadQuote m)
=> Type tyname uni ann -> m ()
markNonFreshType = markNonFreshMax . setOf typeUniquesDeep
markNonFreshTerm
:: (HasUniques (Term tyname name uni fun ann), MonadQuote m)
=> Term tyname name uni fun ann -> m ()
markNonFreshTerm = markNonFreshMax . setOf termUniquesDeep
markNonFreshProgram
:: (HasUnique tyname TypeUnique, HasUnique name TermUnique, MonadQuote m)
=> Program tyname name uni fun ann
-> m ()
markNonFreshProgram (Program _ _ body) = markNonFreshTerm body
|
09f0f258444f5767b5fb6186ebe92419c9f5965ad294a70bb64f67c29fae7fde | haskell-repa/repa | Chunked.hs |
module Data.Repa.Eval.Generic.Seq.Chunked
( fillLinear
, fillBlock2)
where
import GHC.Exts
-------------------------------------------------------------------------------
-- | Fill something sequentially.
--
-- * The array is filled linearly from start to finish.
--
fillLinear
:: (Int# -> a -> IO ()) -- ^ Update function to write into result buffer.
-> (Int# -> a) -- ^ Function to get the value at a given index.
-> Int# -- ^ Number of elements to fill.
-> IO ()
fillLinear write getElem len
= fill 0#
where fill !ix
| 1# <- ix >=# len = return ()
| otherwise
= do write ix (getElem ix)
fill (ix +# 1#)
{-# INLINE [0] fillLinear #-}
-------------------------------------------------------------------------------
-- | Fill a block in a rank-2 array, sequentially.
--
-- * Blockwise filling can be more cache-efficient than linear filling for
-- rank-2 arrays.
--
-- * The block is filled in row major order from top to bottom.
--
fillBlock2
:: (Int# -> a -> IO ()) -- ^ Update function to write into result buffer.
-> (Int# -> Int# -> a) -- ^ Function to get the value at an (x, y) index.
-> Int# -- ^ Width of the whole array.
-> Int# -- ^ x0 lower left corner of block to fill.
-> Int# -- ^ y0
-> Int# -- ^ w0 width of block to fill
-> Int# -- ^ h0 height of block to fill
-> IO ()
fillBlock2
write getElem
!imageWidth !x0 !y0 !w0 h0
= do fillBlock y0 ix0
where !x1 = x0 +# w0
!y1 = y0 +# h0
!ix0 = x0 +# (y0 *# imageWidth)
{-# INLINE fillBlock #-}
fillBlock !y !ix
| 1# <- y >=# y1 = return ()
| otherwise
= do fillLine1 x0 ix
fillBlock (y +# 1#) (ix +# imageWidth)
# INLINE fillLine1 #
fillLine1 !x !ix'
| 1# <- x >=# x1 = return ()
| otherwise
= do write ix' (getElem x y)
fillLine1 (x +# 1#) (ix' +# 1#)
{-# INLINE [0] fillBlock2 #-}
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-eval/Data/Repa/Eval/Generic/Seq/Chunked.hs | haskell | -----------------------------------------------------------------------------
| Fill something sequentially.
* The array is filled linearly from start to finish.
^ Update function to write into result buffer.
^ Function to get the value at a given index.
^ Number of elements to fill.
# INLINE [0] fillLinear #
-----------------------------------------------------------------------------
| Fill a block in a rank-2 array, sequentially.
* Blockwise filling can be more cache-efficient than linear filling for
rank-2 arrays.
* The block is filled in row major order from top to bottom.
^ Update function to write into result buffer.
^ Function to get the value at an (x, y) index.
^ Width of the whole array.
^ x0 lower left corner of block to fill.
^ y0
^ w0 width of block to fill
^ h0 height of block to fill
# INLINE fillBlock #
# INLINE [0] fillBlock2 # |
module Data.Repa.Eval.Generic.Seq.Chunked
( fillLinear
, fillBlock2)
where
import GHC.Exts
fillLinear
-> IO ()
fillLinear write getElem len
= fill 0#
where fill !ix
| 1# <- ix >=# len = return ()
| otherwise
= do write ix (getElem ix)
fill (ix +# 1#)
fillBlock2
-> IO ()
fillBlock2
write getElem
!imageWidth !x0 !y0 !w0 h0
= do fillBlock y0 ix0
where !x1 = x0 +# w0
!y1 = y0 +# h0
!ix0 = x0 +# (y0 *# imageWidth)
fillBlock !y !ix
| 1# <- y >=# y1 = return ()
| otherwise
= do fillLine1 x0 ix
fillBlock (y +# 1#) (ix +# imageWidth)
# INLINE fillLine1 #
fillLine1 !x !ix'
| 1# <- x >=# x1 = return ()
| otherwise
= do write ix' (getElem x y)
fillLine1 (x +# 1#) (ix' +# 1#)
|
35914e283feac15adc69a6add0caf99fa6590c373ab66c03fd11c080d765cc3b | paulbutcher/lein-lambda | handler_test.clj | (ns {{name}}.handler-test
(:require [clojure.test :refer :all]
[ring.mock.request :as mock]
[{{name}}.handler :refer :all]))
(deftest test-app
(testing "main route"
(let [response (app (mock/request :get "/hello"))]
(is (= (:status response) 200))
(is (= (:body response) "{\"message\":\"Hello World\"}"))))
(testing "not-found route"
(let [response (app (mock/request :get "/invalid"))]
(is (= (:status response) 404)))))
| null | https://raw.githubusercontent.com/paulbutcher/lein-lambda/20398b6dadeb9679d7eb258d4c47b60cd8485ff7/template/resources/leiningen/new/lambda_api/handler_test.clj | clojure | (ns {{name}}.handler-test
(:require [clojure.test :refer :all]
[ring.mock.request :as mock]
[{{name}}.handler :refer :all]))
(deftest test-app
(testing "main route"
(let [response (app (mock/request :get "/hello"))]
(is (= (:status response) 200))
(is (= (:body response) "{\"message\":\"Hello World\"}"))))
(testing "not-found route"
(let [response (app (mock/request :get "/invalid"))]
(is (= (:status response) 404)))))
|
|
678627fa29921b0830f1ef569d7ab94263fbc4dcfbedf6495921944a67e67081 | thepower/tpnode | genesis.erl | -module(genesis).
-export([genesis/0, new/2, new/1, settings/0, settings/1]).
genesis() ->
case file:consult(application:get_env(tpnode,genesis,"genesis.txt")) of
{ok, [Genesis]} ->
Genesis;
{error,enoent} ->
case file:read_file("genesis.bin") of
{ok, Bin} ->
block:unpack(Bin);
{error, enoent} ->
case application:get_env(tpnode,replica,false) of
true ->
case application:get_env(tpnode,upstream,[]) of
[Ups|_] -> %URL of file, to download
tpnode_repl_worker:genesis(#{uri=>Ups});
false ->
throw({error, "genesis file not found"})
end
end
end
end.
new(HPrivKey) ->
PrivKeys=case HPrivKey of
[E|_] when is_list(E) ->
[ hex:parse(E1) || E1 <- HPrivKey];
[<<_:32/binary>> |_] ->
HPrivKey;
[E|_] when is_binary(E) ->
[ hex:parse(E1) || E1 <- HPrivKey];
E1 when is_list(E1) ->
[hex:parse(E1)];
E1 when is_binary(E1) ->
[hex:parse(E1)]
end,
Set0=case PrivKeys of
[_] ->
settings();
[_,_|_] ->
settings(
lists:map(
fun(Priv) ->
Pub=tpecdsa:calc_pub(Priv,true),
<<Ni:8/binary,_/binary>>=nodekey:node_id(Pub),
{<<"node_",Ni/binary>>,Pub}
end, PrivKeys)
)
end,
new(HPrivKey, Set0).
new(HPrivKey, Set0) ->
PrivKeys=case HPrivKey of
[E|_] when is_list(E) ->
[ hex:parse(E1) || E1 <- HPrivKey];
[<<_:32/binary>> |_] ->
HPrivKey;
[E|_] when is_binary(E) ->
[ hex:parse(E1) || E1 <- HPrivKey];
E1 when is_list(E1) ->
[hex:parse(E1)];
E1 when is_binary(E1) ->
[hex:parse(E1)]
end,
Patch=lists:foldl(
fun(PrivKey, Acc) ->
tx:sign(Acc, PrivKey)
end, Set0, PrivKeys),
Settings=[ { bin2hex:dbin2hex(crypto:hash(md5,maps:get(body,Set0))), Patch } ],
Blk0=block:mkblock2(
#{ parent=><<0, 0, 0, 0, 0, 0, 0, 0>>,
height=>0,
txs=>[],
bals=>#{},
mychain=>1,
settings=>Settings,
sign=>[]
}),
Genesis=lists:foldl(
fun(PrivKey, Acc) ->
block:sign(
Acc,
[{timestamp, os:system_time(millisecond)}],
PrivKey)
end, Blk0, PrivKeys),
file:write_file("genesis.txt", io_lib:format("~p.~n", [Genesis])),
{ok, Genesis}.
settings() ->
settings(
[
{<<"nodeb1">>,base64:decode("AganOY4DcSMZ078U9tR9+p0PkwDzwnoKZH2SWl7Io9Xb")},
{<<"nodeb2">>,base64:decode("AzHXdEk2GymQDUy30Q/uPefemnQloXGfAiWCpoywM7eq")},
{<<"nodeb3">>,base64:decode("AujH2xsSnOCVJ5mtVy7MQPcCfNEEnKghX0P9V+E+Vfo/")}
]
).
settings(Keys) ->
lists:foldl(
fun({Name,Key},Acc) ->
[ #{t=>set, p=>[keys,Name], v=>Key} | Acc]
end,
[
#{t=>set, p=>[<<"current">>,chain, patchsigs], v=>2},
#{t=>set, p=>[<<"current">>,chain, minsig], v=>2},
#{t=>set, p=>[<<"current">>,chain, blocktime], v=>2},
#{t=>set, p=>[<<"current">>,chain, <<"allowempty">>], v=>0},
#{t=>set, p=>[chains], v=>[1,2,3,4]},
#{t=>set, p=>[nodechain], v=>
lists:foldl(fun({NN,_},Acc) ->
maps:put(NN,4,Acc)
end, #{}, Keys)
}
],
Keys).
| null | https://raw.githubusercontent.com/thepower/tpnode/8eb38eb7f6def0edcd12c63ff77cce1866dcdf4d/apps/tpnode/src/genesis.erl | erlang | URL of file, to download | -module(genesis).
-export([genesis/0, new/2, new/1, settings/0, settings/1]).
genesis() ->
case file:consult(application:get_env(tpnode,genesis,"genesis.txt")) of
{ok, [Genesis]} ->
Genesis;
{error,enoent} ->
case file:read_file("genesis.bin") of
{ok, Bin} ->
block:unpack(Bin);
{error, enoent} ->
case application:get_env(tpnode,replica,false) of
true ->
case application:get_env(tpnode,upstream,[]) of
tpnode_repl_worker:genesis(#{uri=>Ups});
false ->
throw({error, "genesis file not found"})
end
end
end
end.
new(HPrivKey) ->
PrivKeys=case HPrivKey of
[E|_] when is_list(E) ->
[ hex:parse(E1) || E1 <- HPrivKey];
[<<_:32/binary>> |_] ->
HPrivKey;
[E|_] when is_binary(E) ->
[ hex:parse(E1) || E1 <- HPrivKey];
E1 when is_list(E1) ->
[hex:parse(E1)];
E1 when is_binary(E1) ->
[hex:parse(E1)]
end,
Set0=case PrivKeys of
[_] ->
settings();
[_,_|_] ->
settings(
lists:map(
fun(Priv) ->
Pub=tpecdsa:calc_pub(Priv,true),
<<Ni:8/binary,_/binary>>=nodekey:node_id(Pub),
{<<"node_",Ni/binary>>,Pub}
end, PrivKeys)
)
end,
new(HPrivKey, Set0).
new(HPrivKey, Set0) ->
PrivKeys=case HPrivKey of
[E|_] when is_list(E) ->
[ hex:parse(E1) || E1 <- HPrivKey];
[<<_:32/binary>> |_] ->
HPrivKey;
[E|_] when is_binary(E) ->
[ hex:parse(E1) || E1 <- HPrivKey];
E1 when is_list(E1) ->
[hex:parse(E1)];
E1 when is_binary(E1) ->
[hex:parse(E1)]
end,
Patch=lists:foldl(
fun(PrivKey, Acc) ->
tx:sign(Acc, PrivKey)
end, Set0, PrivKeys),
Settings=[ { bin2hex:dbin2hex(crypto:hash(md5,maps:get(body,Set0))), Patch } ],
Blk0=block:mkblock2(
#{ parent=><<0, 0, 0, 0, 0, 0, 0, 0>>,
height=>0,
txs=>[],
bals=>#{},
mychain=>1,
settings=>Settings,
sign=>[]
}),
Genesis=lists:foldl(
fun(PrivKey, Acc) ->
block:sign(
Acc,
[{timestamp, os:system_time(millisecond)}],
PrivKey)
end, Blk0, PrivKeys),
file:write_file("genesis.txt", io_lib:format("~p.~n", [Genesis])),
{ok, Genesis}.
settings() ->
settings(
[
{<<"nodeb1">>,base64:decode("AganOY4DcSMZ078U9tR9+p0PkwDzwnoKZH2SWl7Io9Xb")},
{<<"nodeb2">>,base64:decode("AzHXdEk2GymQDUy30Q/uPefemnQloXGfAiWCpoywM7eq")},
{<<"nodeb3">>,base64:decode("AujH2xsSnOCVJ5mtVy7MQPcCfNEEnKghX0P9V+E+Vfo/")}
]
).
settings(Keys) ->
lists:foldl(
fun({Name,Key},Acc) ->
[ #{t=>set, p=>[keys,Name], v=>Key} | Acc]
end,
[
#{t=>set, p=>[<<"current">>,chain, patchsigs], v=>2},
#{t=>set, p=>[<<"current">>,chain, minsig], v=>2},
#{t=>set, p=>[<<"current">>,chain, blocktime], v=>2},
#{t=>set, p=>[<<"current">>,chain, <<"allowempty">>], v=>0},
#{t=>set, p=>[chains], v=>[1,2,3,4]},
#{t=>set, p=>[nodechain], v=>
lists:foldl(fun({NN,_},Acc) ->
maps:put(NN,4,Acc)
end, #{}, Keys)
}
],
Keys).
|
77ded6962d03abc0c94f54f6bc9692c4d1457801554e9fab9fe69a6dabf72a8e | ocamllabs/ocaml-modular-implicits | emitcode.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 Q Public License version 1.0 .
(* *)
(***********************************************************************)
Generation of bytecode for .cmo files
open Cmo_format
open Instruct
val to_file: out_channel -> string -> string -> instruction list -> unit
(* Arguments:
channel on output file
name of compilation unit implemented
path of cmo file being written
list of instructions to emit *)
val to_memory: instruction list -> instruction list ->
bytes * int * (reloc_info * int) list
(* Arguments:
initialization code (terminated by STOP)
function code
Results:
block of relocatable bytecode
size of this block
relocation information *)
val to_packed_file:
out_channel -> instruction list -> (reloc_info * int) list
(* Arguments:
channel on output file
list of instructions to emit
Result:
relocation information (reversed) *)
val reset: unit -> unit
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/bytecomp/emitcode.mli | ocaml | *********************************************************************
OCaml
*********************************************************************
Arguments:
channel on output file
name of compilation unit implemented
path of cmo file being written
list of instructions to emit
Arguments:
initialization code (terminated by STOP)
function code
Results:
block of relocatable bytecode
size of this block
relocation information
Arguments:
channel on output file
list of instructions to emit
Result:
relocation information (reversed) | , 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 Q Public License version 1.0 .
Generation of bytecode for .cmo files
open Cmo_format
open Instruct
val to_file: out_channel -> string -> string -> instruction list -> unit
val to_memory: instruction list -> instruction list ->
bytes * int * (reloc_info * int) list
val to_packed_file:
out_channel -> instruction list -> (reloc_info * int) list
val reset: unit -> unit
|
23a70b1190cf5c7a208b18cbf62aea8a31e6d14105ff7952de7e16ed3577bc5a | charlieg/Sparser | extend-edge.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(CTI-source LISP) -*-
copyright ( c ) 1991 Content Technologies Inc. -- all rights reserved
;;;
;;; File: "extend edge"
Module : " : names : companies "
version : 1.2 April 1991 ( v1.8.1 )
1.1 ( 4/3 ) Changed call to adapt to new company indexing protocol
1.2 ( 4/4 ) fixed complications in the appending of extended and old
;; edges.
(in-package :CTI-source)
(defun extend-company-edge (edge extensions)
;; construct a new edge, canibalizing the original
(let ((leftmost-edge (first extensions))
total-treetop-sequence )
(let ((new-edge (next-edge-from-resource))
(starting-vector (edge-starts-at leftmost-edge))
(ending-vector (edge-ends-at edge))
(category (edge-category edge)))
(knit-edge-into-positions new-edge
starting-vector
ending-vector)
(setf (edge-category new-edge) category)
(setf (edge-starts-at new-edge) starting-vector)
(setf (edge-ends-at new-edge) ending-vector)
(setf (edge-rule new-edge) :CA-extension-of-edge)
(setf (edge-used-in new-edge) nil)
(setf (edge-left-daughter new-edge)
(setq total-treetop-sequence
(extend-name-sequence
extensions (edge-left-daughter edge) category)))
(setf (edge-right-daughter new-edge) :CA-extended-edge)
(dolist (e extensions) (de-activate-edge e))
(setf (edge-form new-edge) (edge-form edge))
(setf (edge-referent new-edge)
(establish-referent-of-a-company
total-treetop-sequence new-edge))
(when *trace-edge-creation*
(format t "~&~%creating ~A from ~A~% rule: ~A"
new-edge edge :CA-extension-of-edge))
(complete new-edge)
(assess-edge-label category new-edge)
new-edge )))
(defun extend-name-sequence (extension-list tail tail-category)
;; the extension is a list of name edges or their equivalent,
;; the tail may be a non-terminal name, in which case it has to be
;; unpacked. The pathway to look through for the unpacking may
;; depend on the category of edge involved
(cond ((listp tail)
(append extension-list tail))
((typep tail 'edge)
(case (cat-symbol tail-category)
(category::company
(let ((daughters-of-original (edge-left-daughter tail)))
(when (typep daughters-of-original 'edge)
;; it's a non-terminal
(setq daughters-of-original
(edge-left-daughter daughters-of-original)))
(append extension-list
daughters-of-original)))
(otherwise
(break/debug "Extend-name-sequence: the tail being ~
extended has a new~% category: ~A~%"
tail-category))))
(t
(break/debug "Extend-name-sequence: unexpected kind of ~
object passed in as~% the tail: ~A~%"
tail))))
| null | https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/grammar/model/core/companies/extend-edge.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:(CTI-source LISP) -*-
File: "extend edge"
edges.
construct a new edge, canibalizing the original
the extension is a list of name edges or their equivalent,
the tail may be a non-terminal name, in which case it has to be
unpacked. The pathway to look through for the unpacking may
depend on the category of edge involved
it's a non-terminal | copyright ( c ) 1991 Content Technologies Inc. -- all rights reserved
Module : " : names : companies "
version : 1.2 April 1991 ( v1.8.1 )
1.1 ( 4/3 ) Changed call to adapt to new company indexing protocol
1.2 ( 4/4 ) fixed complications in the appending of extended and old
(in-package :CTI-source)
(defun extend-company-edge (edge extensions)
(let ((leftmost-edge (first extensions))
total-treetop-sequence )
(let ((new-edge (next-edge-from-resource))
(starting-vector (edge-starts-at leftmost-edge))
(ending-vector (edge-ends-at edge))
(category (edge-category edge)))
(knit-edge-into-positions new-edge
starting-vector
ending-vector)
(setf (edge-category new-edge) category)
(setf (edge-starts-at new-edge) starting-vector)
(setf (edge-ends-at new-edge) ending-vector)
(setf (edge-rule new-edge) :CA-extension-of-edge)
(setf (edge-used-in new-edge) nil)
(setf (edge-left-daughter new-edge)
(setq total-treetop-sequence
(extend-name-sequence
extensions (edge-left-daughter edge) category)))
(setf (edge-right-daughter new-edge) :CA-extended-edge)
(dolist (e extensions) (de-activate-edge e))
(setf (edge-form new-edge) (edge-form edge))
(setf (edge-referent new-edge)
(establish-referent-of-a-company
total-treetop-sequence new-edge))
(when *trace-edge-creation*
(format t "~&~%creating ~A from ~A~% rule: ~A"
new-edge edge :CA-extension-of-edge))
(complete new-edge)
(assess-edge-label category new-edge)
new-edge )))
(defun extend-name-sequence (extension-list tail tail-category)
(cond ((listp tail)
(append extension-list tail))
((typep tail 'edge)
(case (cat-symbol tail-category)
(category::company
(let ((daughters-of-original (edge-left-daughter tail)))
(when (typep daughters-of-original 'edge)
(setq daughters-of-original
(edge-left-daughter daughters-of-original)))
(append extension-list
daughters-of-original)))
(otherwise
(break/debug "Extend-name-sequence: the tail being ~
extended has a new~% category: ~A~%"
tail-category))))
(t
(break/debug "Extend-name-sequence: unexpected kind of ~
object passed in as~% the tail: ~A~%"
tail))))
|
ad33f7aac8c79d98db4c32f0abe467aaf62d57cc63804400f1523df7a9662521 | haskell-nix/hnix-store | Parsers.hs | # language AllowAmbiguousTypes #
{-# language ScopedTypeVariables #-}
# language RankNTypes #
# language DataKinds #
module System.Nix.Store.Remote.Parsers
( parseContentAddressableAddress
)
where
import Data.Attoparsec.ByteString.Char8
import System.Nix.Hash
import System.Nix.StorePath ( ContentAddressableAddress(..)
, NarHashMode(..)
)
import Crypto.Hash ( SHA256 )
| Parse ` ContentAddressableAddress ` from ` ByteString `
parseContentAddressableAddress
:: ByteString -> Either String ContentAddressableAddress
parseContentAddressableAddress =
Data.Attoparsec.ByteString.Char8.parseOnly contentAddressableAddressParser
-- | Parser for content addressable field
contentAddressableAddressParser :: Parser ContentAddressableAddress
contentAddressableAddressParser = caText <|> caFixed
| Parser for @text : sha256:<h>@
caText :: Parser ContentAddressableAddress
caText = do
_ <- "text:sha256:"
digest <- decodeDigestWith @SHA256 NixBase32 <$> parseHash
either fail pure $ Text <$> digest
-- | Parser for @fixed:<r?>:<ht>:<h>@
caFixed :: Parser ContentAddressableAddress
caFixed = do
_ <- "fixed:"
narHashMode <- (Recursive <$ "r:") <|> (RegularFile <$ "")
digest <- parseTypedDigest
either fail pure $ Fixed narHashMode <$> digest
parseTypedDigest :: Parser (Either String SomeNamedDigest)
parseTypedDigest = mkNamedDigest <$> parseHashType <*> parseHash
parseHashType :: Parser Text
parseHashType =
decodeUtf8 <$> ("sha256" <|> "sha512" <|> "sha1" <|> "md5") <* (":" <|> "-")
parseHash :: Parser Text
parseHash = decodeUtf8 <$> takeWhile1 (/= ':')
| null | https://raw.githubusercontent.com/haskell-nix/hnix-store/5e55781516178939bf9a86f943e120e6ad775b9d/hnix-store-remote/src/System/Nix/Store/Remote/Parsers.hs | haskell | # language ScopedTypeVariables #
| Parser for content addressable field
| Parser for @fixed:<r?>:<ht>:<h>@ | # language AllowAmbiguousTypes #
# language RankNTypes #
# language DataKinds #
module System.Nix.Store.Remote.Parsers
( parseContentAddressableAddress
)
where
import Data.Attoparsec.ByteString.Char8
import System.Nix.Hash
import System.Nix.StorePath ( ContentAddressableAddress(..)
, NarHashMode(..)
)
import Crypto.Hash ( SHA256 )
| Parse ` ContentAddressableAddress ` from ` ByteString `
parseContentAddressableAddress
:: ByteString -> Either String ContentAddressableAddress
parseContentAddressableAddress =
Data.Attoparsec.ByteString.Char8.parseOnly contentAddressableAddressParser
contentAddressableAddressParser :: Parser ContentAddressableAddress
contentAddressableAddressParser = caText <|> caFixed
| Parser for @text : sha256:<h>@
caText :: Parser ContentAddressableAddress
caText = do
_ <- "text:sha256:"
digest <- decodeDigestWith @SHA256 NixBase32 <$> parseHash
either fail pure $ Text <$> digest
caFixed :: Parser ContentAddressableAddress
caFixed = do
_ <- "fixed:"
narHashMode <- (Recursive <$ "r:") <|> (RegularFile <$ "")
digest <- parseTypedDigest
either fail pure $ Fixed narHashMode <$> digest
parseTypedDigest :: Parser (Either String SomeNamedDigest)
parseTypedDigest = mkNamedDigest <$> parseHashType <*> parseHash
parseHashType :: Parser Text
parseHashType =
decodeUtf8 <$> ("sha256" <|> "sha512" <|> "sha1" <|> "md5") <* (":" <|> "-")
parseHash :: Parser Text
parseHash = decodeUtf8 <$> takeWhile1 (/= ':')
|
601faa130a1dd44dc1824d5a23eb8870641f1f71296aeebb089f634e82779c81 | life0fun/clojure-idiom | ants.clj | Ant sim ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Common Public License 1.0 ()
; which can be found in the file CPL.TXT at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;dimensions of square world
(def dim 80)
;number of ants = nants-sqrt^2
(def nants-sqrt 7)
;number of places with food
(def food-places 35)
;range of amount of food at a place
(def food-range 100)
;scale factor for pheromone drawing
(def pher-scale 20.0)
;scale factor for food drawing
(def food-scale 30.0)
;evaporation rate
(def evap-rate 0.99)
(def animation-sleep-ms 100)
(def ant-sleep-ms 40)
(def evap-sleep-ms 1000)
(def running true)
(defstruct cell :food :pher) ;may also have :ant and :home
; Send action to agent, the action takes in agent's current state(x, y), make agent
; to do some computation, and use that result to update agent's state(x, y)
; the word is a map of cells, with each cell addressable by x,y and holds state of
; which ant in it. Each ant is an agent whose state indicates which cell it is in.
; we create a list of ants belong to cells. Bi-direction refers between cells and ants.
; when sending action to ant agent to move it(update its x,y), atomically update (cell, ant) state.
; use a ref var and Agent to encapsulate cell's state and ant's state.
alter ref 's state(cell 's state ) and send fn to Agent to change ant 's state .
;
1 . A map with cells addressable by x , , y ] IS a ref state that holds ref to ant .
2 . an ant is an Agent whose state is ant 's coord(x , y ) . from x , y , find the cell that ant 's props stored .
3 . ant agent has x , y , store ant 's prop map at cell[x , y ] .
4 . from cell[x , y ] , get the ant prop . can not or no need to get ref to ant agent .
5 . to change ant prop , just send action to ant agent , from agent x , y , can access ref state at the cell .
6 . inside action fn send to agent , find new cell ant can move to , update cell 's state .
7 . return the new cell at the end of fn that sent to Agent . This update Agent 's state , which is ant 's state .
8 . for conitnuous move , send fn to Ant 's Agent to change ant 's state . inside fn , send the fn to agent again .
;world is a 2d vector of refs to cells
(def world
(apply vector
(map (fn [_]
(apply vector (map (fn [_] (ref (struct cell 0 0)))
(range dim))))
(range dim))))
(defn place [[x y]]
(-> world (nth x) (nth y)))
(defstruct ant :dir) ;may also have :food
(defn create-ant
"create ant an at the location, returning an ant agent on the location"
[loc dir]
(sync nil
(let [p (place loc)
a (struct ant dir)]
(alter p assoc :ant a)
(agent loc))))
(def home-off (/ dim 4))
(def home-range (range home-off (+ nants-sqrt home-off)))
(defn setup
"places initial food and ants, returns seq of ant agents"
[]
(sync nil
(dotimes [i food-places]
(let [p (place [(rand-int dim) (rand-int dim)])]
(alter p assoc :food (rand-int food-range))))
(doall
(for [x home-range y home-range]
(do
(alter (place [x y])
assoc :home true)
(create-ant [x y] (rand-int 8)))))))
(defn bound
"returns n wrapped into range 0-b"
[b n]
(let [n (rem n b)]
(if (neg? n)
(+ n b)
n)))
(defn wrand
"given a vector of slice sizes, returns the index of a slice given a
random spin of a roulette wheel with compartments proportional to
slices."
[slices]
(let [total (reduce + slices)
r (rand total)]
(loop [i 0 sum 0]
(if (< r (+ (slices i) sum))
i
(recur (inc i) (+ (slices i) sum))))))
dirs are 0 - 7 , starting at north and going clockwise
these are the deltas in order to move one step in given dir
(def dir-delta {0 [0 -1]
1 [1 -1]
2 [1 0]
3 [1 1]
4 [0 1]
5 [-1 1]
6 [-1 0]
7 [-1 -1]})
(defn delta-loc
"returns the location one step in the given dir. Note the world is a torus"
[[x y] dir]
(let [[dx dy] (dir-delta (bound 8 dir))]
[(bound dim (+ x dx)) (bound dim (+ y dy))]))
( [ & body ]
; `(sync nil ~@body))
;ant agent functions
;an ant agent tracks the location of an ant, and controls the behavior of
;the ant at that location
(defn turn
"turns the ant at the location by the given amount"
[loc amt]
(dosync
(let [p (place loc)
ant (:ant @p)]
(alter p assoc :ant (assoc ant :dir (bound 8 (+ (:dir ant) amt))))))
loc)
(defn move
"moves the ant in the direction it is heading. Must be called in a
transaction that has verified the way is clear"
[loc]
(let [oldp (place loc)
ant (:ant @oldp)
newloc (delta-loc loc (:dir ant))
p (place newloc)]
;move the ant
(alter p assoc :ant ant)
(alter oldp dissoc :ant)
;leave pheromone trail
(when-not (:home @oldp)
(alter oldp assoc :pher (inc (:pher @oldp))))
newloc))
(defn take-food [loc]
"Takes one food from current location. Must be called in a
transaction that has verified there is food available"
(let [p (place loc)
ant (:ant @p)]
(alter p assoc
:food (dec (:food @p))
:ant (assoc ant :food true))
loc))
(defn drop-food [loc]
"Drops food at current location. Must be called in a
transaction that has verified the ant has food"
(let [p (place loc)
ant (:ant @p)]
(alter p assoc
:food (inc (:food @p))
:ant (dissoc ant :food))
loc))
(defn rank-by
"returns a map of xs to their 1-based rank when sorted by keyfn"
[keyfn xs]
(let [sorted (sort-by (comp float keyfn) xs)]
(reduce (fn [ret i] (assoc ret (nth sorted i) (inc i)))
{} (range (count sorted)))))
(defn behave
"the main function for the ant agent"
[loc]
(let [p (place loc)
ant (:ant @p)
ahead (place (delta-loc loc (:dir ant)))
ahead-left (place (delta-loc loc (dec (:dir ant))))
ahead-right (place (delta-loc loc (inc (:dir ant))))
places [ahead ahead-left ahead-right]]
(. Thread (sleep ant-sleep-ms))
(dosync
(when running
(send-off *agent* #'behave))
(if (:food ant)
;going home
(cond
(:home @p)
(-> loc drop-food (turn 4))
(and (:home @ahead) (not (:ant @ahead)))
(move loc)
:else
(let [ranks (merge-with +
(rank-by (comp #(if (:home %) 1 0) deref) places)
(rank-by (comp :pher deref) places))]
(([move #(turn % -1) #(turn % 1)]
(wrand [(if (:ant @ahead) 0 (ranks ahead))
(ranks ahead-left) (ranks ahead-right)]))
loc)))
;foraging
(cond
(and (pos? (:food @p)) (not (:home @p)))
(-> loc take-food (turn 4))
(and (pos? (:food @ahead)) (not (:home @ahead)) (not (:ant @ahead)))
(move loc)
:else
(let [ranks (merge-with +
(rank-by (comp :food deref) places)
(rank-by (comp :pher deref) places))]
(([move #(turn % -1) #(turn % 1)]
(wrand [(if (:ant @ahead) 0 (ranks ahead))
(ranks ahead-left) (ranks ahead-right)]))
loc)))))))
(defn evaporate
"causes all the pheromones to evaporate a bit"
[]
(dorun
(for [x (range dim) y (range dim)]
(dosync
(let [p (place [x y])]
(alter p assoc :pher (* evap-rate (:pher @p))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; UI ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(import
'(java.awt Color Graphics Dimension)
'(java.awt.image BufferedImage)
'(javax.swing JPanel JFrame))
;pixels per world cell
(def scale 5)
(defn fill-cell [#^Graphics g x y c]
(doto g
(.setColor c)
(.fillRect (* x scale) (* y scale) scale scale)))
(defn render-ant [ant #^Graphics g x y]
(let [black (. (new Color 0 0 0 255) (getRGB))
gray (. (new Color 100 100 100 255) (getRGB))
red (. (new Color 255 0 0 255) (getRGB))
[hx hy tx ty] ({0 [2 0 2 4]
1 [4 0 0 4]
2 [4 2 0 2]
3 [4 4 0 0]
4 [2 4 2 0]
5 [0 4 4 0]
6 [0 2 4 2]
7 [0 0 4 4]}
(:dir ant))]
(doto g
(.setColor (if (:food ant)
(new Color 255 0 0 255)
(new Color 0 0 0 255)))
(.drawLine (+ hx (* x scale)) (+ hy (* y scale))
(+ tx (* x scale)) (+ ty (* y scale))))))
(defn render-place [g p x y]
(when (pos? (:pher p))
(fill-cell g x y (new Color 0 255 0
(int (min 255 (* 255 (/ (:pher p) pher-scale)))))))
(when (pos? (:food p))
(fill-cell g x y (new Color 255 0 0
(int (min 255 (* 255 (/ (:food p) food-scale)))))))
(when (:ant p)
(render-ant (:ant p) g x y)))
(defn render [g]
(let [v (dosync (apply vector (for [x (range dim) y (range dim)]
@(place [x y]))))
img (new BufferedImage (* scale dim) (* scale dim)
(. BufferedImage TYPE_INT_ARGB))
bg (. img (getGraphics))]
(doto bg
(.setColor (. Color white))
(.fillRect 0 0 (. img (getWidth)) (. img (getHeight))))
(dorun
(for [x (range dim) y (range dim)]
(render-place bg (v (+ (* x dim) y)) x y)))
(doto bg
(.setColor (. Color blue))
(.drawRect (* scale home-off) (* scale home-off)
(* scale nants-sqrt) (* scale nants-sqrt)))
(. g (drawImage img 0 0 nil))
(. bg (dispose))))
(def panel (doto (proxy [JPanel] []
(paint [g] (render g)))
(.setPreferredSize (new Dimension
(* scale dim)
(* scale dim)))))
(def frame (doto (new JFrame) (.add panel) .pack .show))
(def animator (agent nil))
(defn animation [x]
(when running
(send-off *agent* #'animation))
(. panel (repaint))
(. Thread (sleep animation-sleep-ms))
nil)
(def evaporator (agent nil))
(defn evaporation [x]
(when running
(send-off *agent* #'evaporation))
(evaporate)
(. Thread (sleep evap-sleep-ms))
nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; use ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (comment
;demo
;; (load-file "/Users/rich/dev/clojure/ants.clj")
(def ants (setup))
(send-off animator animation)
(dorun (map #(send-off % behave) ants))
(send-off evaporator evaporation)
;; )
;;
;; nodejs version
;;
class Ant
; constructor: (@name, @loc, @options) ->
@interval = 1000
; @totcnt = 0
; console.log "Ant construction at #{ @loc } "
@create : ( name , loc , opts ) - >
console.log ' creating Ant '
return new Ant(name , loc )
; setAntTimeout : ->
; self = @ # when fn invoked, this passed, cache it to self.
; # on push timeout closes context var pushIdx
; onAntTimeout = =>
self.totcnt + = 1
@totcnt + = 1 # use fat arrow together with @
# console.log ' onAntTimeout # { self.totcnt } ' , self.totcnt
console.log " onAntTimeout # { self.totcnt } " ,
if @totcnt > 10
; console.log 'timed out done !'
; return
; # reset the timer in timeout handler
; setTimeout onAntTimeout, self.interval
; # setup timer
; console.log 'setting up timer every ', self.interval
; setTimeout onAntTimeout, self.interval
; run : ->
; console.log 'running....'
; @setAntTimeout()
; exports.Ant = Ant
; exports.create = Ant.create
ant = Ant.create("ant1 " , 1 )
; ant.run()
| null | https://raw.githubusercontent.com/life0fun/clojure-idiom/481b297eeabea917a68b492b1fb78b8151408507/ants.clj | clojure | ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
The use and distribution terms for this software are covered by the
Common Public License 1.0 ()
which can be found in the file CPL.TXT at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
dimensions of square world
number of ants = nants-sqrt^2
number of places with food
range of amount of food at a place
scale factor for pheromone drawing
scale factor for food drawing
evaporation rate
may also have :ant and :home
Send action to agent, the action takes in agent's current state(x, y), make agent
to do some computation, and use that result to update agent's state(x, y)
the word is a map of cells, with each cell addressable by x,y and holds state of
which ant in it. Each ant is an agent whose state indicates which cell it is in.
we create a list of ants belong to cells. Bi-direction refers between cells and ants.
when sending action to ant agent to move it(update its x,y), atomically update (cell, ant) state.
use a ref var and Agent to encapsulate cell's state and ant's state.
world is a 2d vector of refs to cells
may also have :food
`(sync nil ~@body))
ant agent functions
an ant agent tracks the location of an ant, and controls the behavior of
the ant at that location
move the ant
leave pheromone trail
going home
foraging
UI ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pixels per world cell
use ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(comment
demo
(load-file "/Users/rich/dev/clojure/ants.clj")
)
nodejs version
constructor: (@name, @loc, @options) ->
@totcnt = 0
console.log "Ant construction at #{ @loc } "
setAntTimeout : ->
self = @ # when fn invoked, this passed, cache it to self.
# on push timeout closes context var pushIdx
onAntTimeout = =>
console.log 'timed out done !'
return
# reset the timer in timeout handler
setTimeout onAntTimeout, self.interval
# setup timer
console.log 'setting up timer every ', self.interval
setTimeout onAntTimeout, self.interval
run : ->
console.log 'running....'
@setAntTimeout()
exports.Ant = Ant
exports.create = Ant.create
ant.run() | Copyright ( c ) . All rights reserved .
(def dim 80)
(def nants-sqrt 7)
(def food-places 35)
(def food-range 100)
(def pher-scale 20.0)
(def food-scale 30.0)
(def evap-rate 0.99)
(def animation-sleep-ms 100)
(def ant-sleep-ms 40)
(def evap-sleep-ms 1000)
(def running true)
alter ref 's state(cell 's state ) and send fn to Agent to change ant 's state .
1 . A map with cells addressable by x , , y ] IS a ref state that holds ref to ant .
2 . an ant is an Agent whose state is ant 's coord(x , y ) . from x , y , find the cell that ant 's props stored .
3 . ant agent has x , y , store ant 's prop map at cell[x , y ] .
4 . from cell[x , y ] , get the ant prop . can not or no need to get ref to ant agent .
5 . to change ant prop , just send action to ant agent , from agent x , y , can access ref state at the cell .
6 . inside action fn send to agent , find new cell ant can move to , update cell 's state .
7 . return the new cell at the end of fn that sent to Agent . This update Agent 's state , which is ant 's state .
8 . for conitnuous move , send fn to Ant 's Agent to change ant 's state . inside fn , send the fn to agent again .
(def world
(apply vector
(map (fn [_]
(apply vector (map (fn [_] (ref (struct cell 0 0)))
(range dim))))
(range dim))))
(defn place [[x y]]
(-> world (nth x) (nth y)))
(defn create-ant
"create ant an at the location, returning an ant agent on the location"
[loc dir]
(sync nil
(let [p (place loc)
a (struct ant dir)]
(alter p assoc :ant a)
(agent loc))))
(def home-off (/ dim 4))
(def home-range (range home-off (+ nants-sqrt home-off)))
(defn setup
"places initial food and ants, returns seq of ant agents"
[]
(sync nil
(dotimes [i food-places]
(let [p (place [(rand-int dim) (rand-int dim)])]
(alter p assoc :food (rand-int food-range))))
(doall
(for [x home-range y home-range]
(do
(alter (place [x y])
assoc :home true)
(create-ant [x y] (rand-int 8)))))))
(defn bound
"returns n wrapped into range 0-b"
[b n]
(let [n (rem n b)]
(if (neg? n)
(+ n b)
n)))
(defn wrand
"given a vector of slice sizes, returns the index of a slice given a
random spin of a roulette wheel with compartments proportional to
slices."
[slices]
(let [total (reduce + slices)
r (rand total)]
(loop [i 0 sum 0]
(if (< r (+ (slices i) sum))
i
(recur (inc i) (+ (slices i) sum))))))
dirs are 0 - 7 , starting at north and going clockwise
these are the deltas in order to move one step in given dir
(def dir-delta {0 [0 -1]
1 [1 -1]
2 [1 0]
3 [1 1]
4 [0 1]
5 [-1 1]
6 [-1 0]
7 [-1 -1]})
(defn delta-loc
"returns the location one step in the given dir. Note the world is a torus"
[[x y] dir]
(let [[dx dy] (dir-delta (bound 8 dir))]
[(bound dim (+ x dx)) (bound dim (+ y dy))]))
( [ & body ]
(defn turn
"turns the ant at the location by the given amount"
[loc amt]
(dosync
(let [p (place loc)
ant (:ant @p)]
(alter p assoc :ant (assoc ant :dir (bound 8 (+ (:dir ant) amt))))))
loc)
(defn move
"moves the ant in the direction it is heading. Must be called in a
transaction that has verified the way is clear"
[loc]
(let [oldp (place loc)
ant (:ant @oldp)
newloc (delta-loc loc (:dir ant))
p (place newloc)]
(alter p assoc :ant ant)
(alter oldp dissoc :ant)
(when-not (:home @oldp)
(alter oldp assoc :pher (inc (:pher @oldp))))
newloc))
(defn take-food [loc]
"Takes one food from current location. Must be called in a
transaction that has verified there is food available"
(let [p (place loc)
ant (:ant @p)]
(alter p assoc
:food (dec (:food @p))
:ant (assoc ant :food true))
loc))
(defn drop-food [loc]
"Drops food at current location. Must be called in a
transaction that has verified the ant has food"
(let [p (place loc)
ant (:ant @p)]
(alter p assoc
:food (inc (:food @p))
:ant (dissoc ant :food))
loc))
(defn rank-by
"returns a map of xs to their 1-based rank when sorted by keyfn"
[keyfn xs]
(let [sorted (sort-by (comp float keyfn) xs)]
(reduce (fn [ret i] (assoc ret (nth sorted i) (inc i)))
{} (range (count sorted)))))
(defn behave
"the main function for the ant agent"
[loc]
(let [p (place loc)
ant (:ant @p)
ahead (place (delta-loc loc (:dir ant)))
ahead-left (place (delta-loc loc (dec (:dir ant))))
ahead-right (place (delta-loc loc (inc (:dir ant))))
places [ahead ahead-left ahead-right]]
(. Thread (sleep ant-sleep-ms))
(dosync
(when running
(send-off *agent* #'behave))
(if (:food ant)
(cond
(:home @p)
(-> loc drop-food (turn 4))
(and (:home @ahead) (not (:ant @ahead)))
(move loc)
:else
(let [ranks (merge-with +
(rank-by (comp #(if (:home %) 1 0) deref) places)
(rank-by (comp :pher deref) places))]
(([move #(turn % -1) #(turn % 1)]
(wrand [(if (:ant @ahead) 0 (ranks ahead))
(ranks ahead-left) (ranks ahead-right)]))
loc)))
(cond
(and (pos? (:food @p)) (not (:home @p)))
(-> loc take-food (turn 4))
(and (pos? (:food @ahead)) (not (:home @ahead)) (not (:ant @ahead)))
(move loc)
:else
(let [ranks (merge-with +
(rank-by (comp :food deref) places)
(rank-by (comp :pher deref) places))]
(([move #(turn % -1) #(turn % 1)]
(wrand [(if (:ant @ahead) 0 (ranks ahead))
(ranks ahead-left) (ranks ahead-right)]))
loc)))))))
(defn evaporate
"causes all the pheromones to evaporate a bit"
[]
(dorun
(for [x (range dim) y (range dim)]
(dosync
(let [p (place [x y])]
(alter p assoc :pher (* evap-rate (:pher @p))))))))
(import
'(java.awt Color Graphics Dimension)
'(java.awt.image BufferedImage)
'(javax.swing JPanel JFrame))
(def scale 5)
(defn fill-cell [#^Graphics g x y c]
(doto g
(.setColor c)
(.fillRect (* x scale) (* y scale) scale scale)))
(defn render-ant [ant #^Graphics g x y]
(let [black (. (new Color 0 0 0 255) (getRGB))
gray (. (new Color 100 100 100 255) (getRGB))
red (. (new Color 255 0 0 255) (getRGB))
[hx hy tx ty] ({0 [2 0 2 4]
1 [4 0 0 4]
2 [4 2 0 2]
3 [4 4 0 0]
4 [2 4 2 0]
5 [0 4 4 0]
6 [0 2 4 2]
7 [0 0 4 4]}
(:dir ant))]
(doto g
(.setColor (if (:food ant)
(new Color 255 0 0 255)
(new Color 0 0 0 255)))
(.drawLine (+ hx (* x scale)) (+ hy (* y scale))
(+ tx (* x scale)) (+ ty (* y scale))))))
(defn render-place [g p x y]
(when (pos? (:pher p))
(fill-cell g x y (new Color 0 255 0
(int (min 255 (* 255 (/ (:pher p) pher-scale)))))))
(when (pos? (:food p))
(fill-cell g x y (new Color 255 0 0
(int (min 255 (* 255 (/ (:food p) food-scale)))))))
(when (:ant p)
(render-ant (:ant p) g x y)))
(defn render [g]
(let [v (dosync (apply vector (for [x (range dim) y (range dim)]
@(place [x y]))))
img (new BufferedImage (* scale dim) (* scale dim)
(. BufferedImage TYPE_INT_ARGB))
bg (. img (getGraphics))]
(doto bg
(.setColor (. Color white))
(.fillRect 0 0 (. img (getWidth)) (. img (getHeight))))
(dorun
(for [x (range dim) y (range dim)]
(render-place bg (v (+ (* x dim) y)) x y)))
(doto bg
(.setColor (. Color blue))
(.drawRect (* scale home-off) (* scale home-off)
(* scale nants-sqrt) (* scale nants-sqrt)))
(. g (drawImage img 0 0 nil))
(. bg (dispose))))
(def panel (doto (proxy [JPanel] []
(paint [g] (render g)))
(.setPreferredSize (new Dimension
(* scale dim)
(* scale dim)))))
(def frame (doto (new JFrame) (.add panel) .pack .show))
(def animator (agent nil))
(defn animation [x]
(when running
(send-off *agent* #'animation))
(. panel (repaint))
(. Thread (sleep animation-sleep-ms))
nil)
(def evaporator (agent nil))
(defn evaporation [x]
(when running
(send-off *agent* #'evaporation))
(evaporate)
(. Thread (sleep evap-sleep-ms))
nil)
(def ants (setup))
(send-off animator animation)
(dorun (map #(send-off % behave) ants))
(send-off evaporator evaporation)
class Ant
@interval = 1000
@create : ( name , loc , opts ) - >
console.log ' creating Ant '
return new Ant(name , loc )
self.totcnt + = 1
@totcnt + = 1 # use fat arrow together with @
# console.log ' onAntTimeout # { self.totcnt } ' , self.totcnt
console.log " onAntTimeout # { self.totcnt } " ,
if @totcnt > 10
ant = Ant.create("ant1 " , 1 )
|
ec25a783caa966d5799565ad27c14a1e2326e21571f1ab3993e393a092500204 | Carnap/Carnap | Goldfarb.hs | # LANGUAGE FlexibleContexts , FlexibleInstances , MultiParamTypeClasses #
module Carnap.Languages.PureFirstOrder.Logic.Goldfarb where
import Text.Parsec
import Control.Lens (view)
import Carnap.Core.Data.Types (Form,Term)
import Carnap.Core.Data.Classes (lhs)
import Carnap.Languages.Util.LanguageClasses
import Carnap.Languages.Util.GenericParsers
import Carnap.Languages.PureFirstOrder.Syntax (PureLanguageFOL, PureLexiconFOL,fogamma)
import Carnap.Languages.PureFirstOrder.Parser
import qualified Carnap.Languages.PurePropositional.Logic.Rules as P
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.ClassicalSequent.Parser
import Carnap.Calculi.Util
import Carnap.Calculi.NaturalDeduction.Syntax
import Carnap.Calculi.NaturalDeduction.Parser (toDeductionLemmonGoldfarb, toDeductionLemmonBrown)
import Carnap.Calculi.NaturalDeduction.Checker (hoProcessLineLemmonMemo, hoProcessLineLemmon)
import Carnap.Languages.PureFirstOrder.Logic.Rules
------------------------------------
1 . The basic Goldfarb system --
------------------------------------
data GoldfarbND = TF Int | P | D | UI | UG
| CQ1 | CQ2 | CQ3 | CQ4 | CQ5 | CQ6 | CQ7 | CQ8
deriving Eq
instance Show GoldfarbND where
show (TF _) = "TF"
show UG = "UG"
show P = "P"
show D = "D"
show UI = "UI"
show CQ1 = "CQ"
show CQ2 = "CQ"
show CQ3 = "CQ"
show CQ4 = "CQ"
show CQ5 = "CQ"
show CQ6 = "CQ"
show CQ7 = "CQ"
show CQ8 = "CQ"
instance Inference GoldfarbND PureLexiconFOL (Form Bool) where
ruleOf UI = universalInstantiation
ruleOf UG = universalGeneralization
ruleOf P = P.axiom
ruleOf D = P.explicitConditionalProofVariations !! 0
ruleOf CQ1 = quantifierNegation !! 0
ruleOf CQ2 = quantifierNegation !! 1
ruleOf CQ3 = quantifierNegation !! 2
ruleOf CQ4 = quantifierNegation !! 3
ruleOf CQ5 = quantifierNegation !! 4
ruleOf CQ6 = quantifierNegation !! 5
ruleOf CQ7 = quantifierNegation !! 6
ruleOf CQ8 = quantifierNegation !! 7
ruleOf (TF n) = P.explosion n
restriction (TF n) = Just $ tautologicalConstraint
(map (\m -> phin m :: FOLSequentCalc (Form Bool)) [1 .. n])
(phin (n + 1) :: FOLSequentCalc (Form Bool))
restriction UG = Just (eigenConstraint tau (SS (lall "v" $ phi' 1)) (fogamma 1))
restriction _ = Nothing
globalRestriction (Left ded) n D = Just (P.dischargeConstraint n ded (view lhs $ conclusionOf D))
globalRestriction _ _ _ = Nothing
indirectInference D = Just $ TypedProof (ProofType 1 1)
indirectInference _ = Nothing
isAssumption P = True
isAssumption _ = False
parseGoldfarbND rtc n _ = do r <- choice (map (try . string) ["P","D","CQ","UI","TF","UG"])
case r of
r | r == "P" -> return [P]
| r == "D" -> return [D]
| r == "CQ" -> return [CQ1,CQ2,CQ3,CQ4,CQ5,CQ6,CQ7,CQ8]
| r == "UI" -> return [UI]
| r == "UG" -> return [UG]
| r == "TF" -> return [TF n]
parseGoldfarbNDProof :: RuntimeDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine GoldfarbND PureLexiconFOL (Form Bool)]
parseGoldfarbNDProof ders = toDeductionLemmonGoldfarb (parseGoldfarbND ders) goldfarbNDFormulaParser
parseGoldfarbBrownNDProof :: RuntimeDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine GoldfarbND PureLexiconFOL (Form Bool)]
parseGoldfarbBrownNDProof ders = toDeductionLemmonBrown (parseGoldfarbND ders) goldfarbNDFormulaParser
goldfarbNDNotation :: String -> String
goldfarbNDNotation x = case runParser altParser 0 "" x of
Left e -> show e
Right s -> s
where altParser = do s <- try handleAtom <|> try handleQuant <|> try handleCon <|> fallback
rest <- (eof >> return "") <|> altParser
return $ s ++ rest
handleAtom = do c <- oneOf "ABCDEFGHIJKLMNOPQRSTUVWXYZ" <* char '('
args <- oneOf "abcdefghijklmnopqrstuvwxyz" `sepBy` char ','
char ')'
return $ c:args
handleQuant = do q <- oneOf "∀∃"
v <- anyChar
return $ "(" ++ [q] ++ [v] ++ ")"
handleCon = (char '∧' >> return "∙") <|> (char '¬' >> return "-")
<|> (char '→' >> return "⊃")
<|> (char '↔' >> return "≡")
fallback = do c <- anyChar
return [c]
goldfarbNDCalc = mkNDCalc
{ ndRenderer = LemmonStyle GoldfarbStyle
, ndParseProof = parseGoldfarbNDProof
, ndProcessLine = hoProcessLineLemmon
, ndProcessLineMemo = Just hoProcessLineLemmonMemo
, ndParseForm = goldfarbNDFormulaParser
, ndParseSeq = parseSeqOver goldfarbNDFormulaParser
, ndNotation = goldfarbNDNotation
}
goldfarbBrownNDCalc = goldfarbNDCalc { ndParseProof = parseGoldfarbBrownNDProof }
------------------------------------------------------------------------
2 . The system with convenience rules for existential quantifiers --
------------------------------------------------------------------------
data GoldfarbNDPlus = ND GoldfarbND | EG | EII String | EIE
deriving Eq
instance Show GoldfarbNDPlus where
show (ND s) = show s
show EG = "EG"
show (EII v) = "EII(" ++ v ++ ")"
show EIE = "EIE"
--XXX: including v is important, since the memoization relies
--hashing the rule, which relies on its show instance
instance Inference GoldfarbNDPlus PureLexiconFOL (Form Bool) where
ruleOf (ND s) = ruleOf s
ruleOf EG = existentialGeneralization
ruleOf (EII _) = existentialAssumption
ruleOf EIE = existentialAssumptionDischarge
restriction (ND s) = restriction s
restriction _ = Nothing
globalRestriction (Left ded) n (ND D) = Just (P.dischargeConstraint n ded (view lhs $ conclusionOf (ND D)))
globalRestriction (Left ded) n (EII v) = case parse (parseFreeVar ['a'..'z'] :: Parsec String u (PureLanguageFOL (Term Int))) "" v of
Left e -> Just (const $ Just "couldn't parse flagged term")
Right v' -> Just (totallyFreshConstraint n ded (taun 1) v')
globalRestriction (Left ded) n EIE = Just (P.dischargeConstraint n ded (view lhs $ conclusionOf EIE)
`andFurtherRestriction` flaggedVariableConstraint n ded theSuc checkEII)
where checkEII (EII v) = case parse (parseFreeVar ['a'..'z'] :: Parsec String u (PureLanguageFOL (Term Int))) "" v of
Right v' -> Right (liftToSequent v')
Left e -> Left "couldn't parse flagged term"
checkEII _ = Left "The discharged premise is not justified with EII"
theSuc = SS (phin 1 :: FOLSequentCalc (Form Bool))
globalRestriction _ _ _ = Nothing
indirectInference (ND x) = indirectInference x
indirectInference EIE = Just $ TypedProof (ProofType 1 1)
indirectInference _ = Nothing
isAssumption (ND s) = isAssumption s
isAssumption (EII _) = True
isAssumption _ = False
parseGoldfarbNDPlus rtc n annote = plusRules <|> (map ND <$> parseGoldfarbND rtc n annote)
where plusRules = do r <- choice (map (try . string) ["EG","EII","EIE"])
case r of
r | r == "EG" -> return [EG]
| r == "EII" -> return [EII annote]
| r == "EIE" -> return [EIE]
parseGoldfarbNDPlusProof :: RuntimeDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine GoldfarbNDPlus PureLexiconFOL (Form Bool)]
parseGoldfarbNDPlusProof rtc = toDeductionLemmonGoldfarb (parseGoldfarbNDPlus rtc) goldfarbNDFormulaParser
parseGoldfarbBrownNDPlusProof :: RuntimeDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine GoldfarbNDPlus PureLexiconFOL (Form Bool)]
parseGoldfarbBrownNDPlusProof rtc = toDeductionLemmonBrown (parseGoldfarbNDPlus rtc) goldfarbNDFormulaParser
goldfarbNDPlusCalc = mkNDCalc
{ ndRenderer = LemmonStyle GoldfarbStyle
, ndParseProof = parseGoldfarbNDPlusProof
, ndProcessLine = hoProcessLineLemmon
, ndParseForm = goldfarbNDFormulaParser
, ndParseSeq = parseSeqOver goldfarbNDFormulaParser
, ndProcessLineMemo = Just hoProcessLineLemmonMemo
, ndNotation = goldfarbNDNotation
}
goldfarbBrownNDPlusCalc = goldfarbNDPlusCalc { ndParseProof = parseGoldfarbBrownNDPlusProof }
| null | https://raw.githubusercontent.com/Carnap/Carnap/f02d6dc5b4790edfddaa07d75ee8617a5f6f8332/Carnap/src/Carnap/Languages/PureFirstOrder/Logic/Goldfarb.hs | haskell | ----------------------------------
----------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
XXX: including v is important, since the memoization relies
hashing the rule, which relies on its show instance | # LANGUAGE FlexibleContexts , FlexibleInstances , MultiParamTypeClasses #
module Carnap.Languages.PureFirstOrder.Logic.Goldfarb where
import Text.Parsec
import Control.Lens (view)
import Carnap.Core.Data.Types (Form,Term)
import Carnap.Core.Data.Classes (lhs)
import Carnap.Languages.Util.LanguageClasses
import Carnap.Languages.Util.GenericParsers
import Carnap.Languages.PureFirstOrder.Syntax (PureLanguageFOL, PureLexiconFOL,fogamma)
import Carnap.Languages.PureFirstOrder.Parser
import qualified Carnap.Languages.PurePropositional.Logic.Rules as P
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.ClassicalSequent.Parser
import Carnap.Calculi.Util
import Carnap.Calculi.NaturalDeduction.Syntax
import Carnap.Calculi.NaturalDeduction.Parser (toDeductionLemmonGoldfarb, toDeductionLemmonBrown)
import Carnap.Calculi.NaturalDeduction.Checker (hoProcessLineLemmonMemo, hoProcessLineLemmon)
import Carnap.Languages.PureFirstOrder.Logic.Rules
data GoldfarbND = TF Int | P | D | UI | UG
| CQ1 | CQ2 | CQ3 | CQ4 | CQ5 | CQ6 | CQ7 | CQ8
deriving Eq
instance Show GoldfarbND where
show (TF _) = "TF"
show UG = "UG"
show P = "P"
show D = "D"
show UI = "UI"
show CQ1 = "CQ"
show CQ2 = "CQ"
show CQ3 = "CQ"
show CQ4 = "CQ"
show CQ5 = "CQ"
show CQ6 = "CQ"
show CQ7 = "CQ"
show CQ8 = "CQ"
instance Inference GoldfarbND PureLexiconFOL (Form Bool) where
ruleOf UI = universalInstantiation
ruleOf UG = universalGeneralization
ruleOf P = P.axiom
ruleOf D = P.explicitConditionalProofVariations !! 0
ruleOf CQ1 = quantifierNegation !! 0
ruleOf CQ2 = quantifierNegation !! 1
ruleOf CQ3 = quantifierNegation !! 2
ruleOf CQ4 = quantifierNegation !! 3
ruleOf CQ5 = quantifierNegation !! 4
ruleOf CQ6 = quantifierNegation !! 5
ruleOf CQ7 = quantifierNegation !! 6
ruleOf CQ8 = quantifierNegation !! 7
ruleOf (TF n) = P.explosion n
restriction (TF n) = Just $ tautologicalConstraint
(map (\m -> phin m :: FOLSequentCalc (Form Bool)) [1 .. n])
(phin (n + 1) :: FOLSequentCalc (Form Bool))
restriction UG = Just (eigenConstraint tau (SS (lall "v" $ phi' 1)) (fogamma 1))
restriction _ = Nothing
globalRestriction (Left ded) n D = Just (P.dischargeConstraint n ded (view lhs $ conclusionOf D))
globalRestriction _ _ _ = Nothing
indirectInference D = Just $ TypedProof (ProofType 1 1)
indirectInference _ = Nothing
isAssumption P = True
isAssumption _ = False
parseGoldfarbND rtc n _ = do r <- choice (map (try . string) ["P","D","CQ","UI","TF","UG"])
case r of
r | r == "P" -> return [P]
| r == "D" -> return [D]
| r == "CQ" -> return [CQ1,CQ2,CQ3,CQ4,CQ5,CQ6,CQ7,CQ8]
| r == "UI" -> return [UI]
| r == "UG" -> return [UG]
| r == "TF" -> return [TF n]
parseGoldfarbNDProof :: RuntimeDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine GoldfarbND PureLexiconFOL (Form Bool)]
parseGoldfarbNDProof ders = toDeductionLemmonGoldfarb (parseGoldfarbND ders) goldfarbNDFormulaParser
parseGoldfarbBrownNDProof :: RuntimeDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine GoldfarbND PureLexiconFOL (Form Bool)]
parseGoldfarbBrownNDProof ders = toDeductionLemmonBrown (parseGoldfarbND ders) goldfarbNDFormulaParser
goldfarbNDNotation :: String -> String
goldfarbNDNotation x = case runParser altParser 0 "" x of
Left e -> show e
Right s -> s
where altParser = do s <- try handleAtom <|> try handleQuant <|> try handleCon <|> fallback
rest <- (eof >> return "") <|> altParser
return $ s ++ rest
handleAtom = do c <- oneOf "ABCDEFGHIJKLMNOPQRSTUVWXYZ" <* char '('
args <- oneOf "abcdefghijklmnopqrstuvwxyz" `sepBy` char ','
char ')'
return $ c:args
handleQuant = do q <- oneOf "∀∃"
v <- anyChar
return $ "(" ++ [q] ++ [v] ++ ")"
handleCon = (char '∧' >> return "∙") <|> (char '¬' >> return "-")
<|> (char '→' >> return "⊃")
<|> (char '↔' >> return "≡")
fallback = do c <- anyChar
return [c]
goldfarbNDCalc = mkNDCalc
{ ndRenderer = LemmonStyle GoldfarbStyle
, ndParseProof = parseGoldfarbNDProof
, ndProcessLine = hoProcessLineLemmon
, ndProcessLineMemo = Just hoProcessLineLemmonMemo
, ndParseForm = goldfarbNDFormulaParser
, ndParseSeq = parseSeqOver goldfarbNDFormulaParser
, ndNotation = goldfarbNDNotation
}
goldfarbBrownNDCalc = goldfarbNDCalc { ndParseProof = parseGoldfarbBrownNDProof }
data GoldfarbNDPlus = ND GoldfarbND | EG | EII String | EIE
deriving Eq
instance Show GoldfarbNDPlus where
show (ND s) = show s
show EG = "EG"
show (EII v) = "EII(" ++ v ++ ")"
show EIE = "EIE"
instance Inference GoldfarbNDPlus PureLexiconFOL (Form Bool) where
ruleOf (ND s) = ruleOf s
ruleOf EG = existentialGeneralization
ruleOf (EII _) = existentialAssumption
ruleOf EIE = existentialAssumptionDischarge
restriction (ND s) = restriction s
restriction _ = Nothing
globalRestriction (Left ded) n (ND D) = Just (P.dischargeConstraint n ded (view lhs $ conclusionOf (ND D)))
globalRestriction (Left ded) n (EII v) = case parse (parseFreeVar ['a'..'z'] :: Parsec String u (PureLanguageFOL (Term Int))) "" v of
Left e -> Just (const $ Just "couldn't parse flagged term")
Right v' -> Just (totallyFreshConstraint n ded (taun 1) v')
globalRestriction (Left ded) n EIE = Just (P.dischargeConstraint n ded (view lhs $ conclusionOf EIE)
`andFurtherRestriction` flaggedVariableConstraint n ded theSuc checkEII)
where checkEII (EII v) = case parse (parseFreeVar ['a'..'z'] :: Parsec String u (PureLanguageFOL (Term Int))) "" v of
Right v' -> Right (liftToSequent v')
Left e -> Left "couldn't parse flagged term"
checkEII _ = Left "The discharged premise is not justified with EII"
theSuc = SS (phin 1 :: FOLSequentCalc (Form Bool))
globalRestriction _ _ _ = Nothing
indirectInference (ND x) = indirectInference x
indirectInference EIE = Just $ TypedProof (ProofType 1 1)
indirectInference _ = Nothing
isAssumption (ND s) = isAssumption s
isAssumption (EII _) = True
isAssumption _ = False
parseGoldfarbNDPlus rtc n annote = plusRules <|> (map ND <$> parseGoldfarbND rtc n annote)
where plusRules = do r <- choice (map (try . string) ["EG","EII","EIE"])
case r of
r | r == "EG" -> return [EG]
| r == "EII" -> return [EII annote]
| r == "EIE" -> return [EIE]
parseGoldfarbNDPlusProof :: RuntimeDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine GoldfarbNDPlus PureLexiconFOL (Form Bool)]
parseGoldfarbNDPlusProof rtc = toDeductionLemmonGoldfarb (parseGoldfarbNDPlus rtc) goldfarbNDFormulaParser
parseGoldfarbBrownNDPlusProof :: RuntimeDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine GoldfarbNDPlus PureLexiconFOL (Form Bool)]
parseGoldfarbBrownNDPlusProof rtc = toDeductionLemmonBrown (parseGoldfarbNDPlus rtc) goldfarbNDFormulaParser
goldfarbNDPlusCalc = mkNDCalc
{ ndRenderer = LemmonStyle GoldfarbStyle
, ndParseProof = parseGoldfarbNDPlusProof
, ndProcessLine = hoProcessLineLemmon
, ndParseForm = goldfarbNDFormulaParser
, ndParseSeq = parseSeqOver goldfarbNDFormulaParser
, ndProcessLineMemo = Just hoProcessLineLemmonMemo
, ndNotation = goldfarbNDNotation
}
goldfarbBrownNDPlusCalc = goldfarbNDPlusCalc { ndParseProof = parseGoldfarbBrownNDPlusProof }
|
81ff7a69702317439f664dc5e33daa54e78a78228000abc420850f369f4fb96c | danlarkin/subrosa | project.clj | (defproject subrosa (.trim (slurp "etc/version.txt"))
:main subrosa.main
:repositories {"jboss"
"/"}
:resource-paths ["etc"]
:dependencies [[aleph "0.3.0-beta8"]
[log4j "1.2.16"]
[org.clojure/clojure "1.4.0"]
[org.clojure/tools.logging "0.2.4"]
[org.clojure/tools.namespace "0.1.3"]
[org.jboss.netty/netty "3.2.1.Final"]
[slingshot "0.10.3"]
[sonian/carica "1.0.1"]
[swank-clojure "1.4.3"]]
:profiles {:dev {:dependencies [[commons-io "2.2"]]}}
:plugins [[lein-tar "1.1.0"]])
| null | https://raw.githubusercontent.com/danlarkin/subrosa/b8e554ffc1b83572acbbb8f50704d3db44b3770f/project.clj | clojure | (defproject subrosa (.trim (slurp "etc/version.txt"))
:main subrosa.main
:repositories {"jboss"
"/"}
:resource-paths ["etc"]
:dependencies [[aleph "0.3.0-beta8"]
[log4j "1.2.16"]
[org.clojure/clojure "1.4.0"]
[org.clojure/tools.logging "0.2.4"]
[org.clojure/tools.namespace "0.1.3"]
[org.jboss.netty/netty "3.2.1.Final"]
[slingshot "0.10.3"]
[sonian/carica "1.0.1"]
[swank-clojure "1.4.3"]]
:profiles {:dev {:dependencies [[commons-io "2.2"]]}}
:plugins [[lein-tar "1.1.0"]])
|
|
7dcbe594381e1d88cd2f358da4b779eeeef3b12a8f4200fbf01e22c4d884bb34 | input-output-hk/plutus-apps | HandlingBlockchainEvents.hs | # OPTIONS_GHC -fno - warn - unused - top - binds #
module HandlingBlockchainEvents() where
import Data.List.NonEmpty (NonEmpty)
import Ledger (CardanoAddress, TxId, TxOutRef)
import Plutus.ChainIndex (ChainIndexTx, TxStatus)
import Plutus.Contract (AsContractError, Contract)
import Plutus.Contract qualified as Contract
BLOCK0
| Wait until one or more unspent outputs are produced at an address .
-}
awaitUtxoProduced ::
forall w s e .
(AsContractError e)
=> CardanoAddress
-> Contract w s e (NonEmpty ChainIndexTx)
-- BLOCK1
awaitUtxoProduced = Contract.awaitUtxoProduced
-- BLOCK2
| Wait until the UTXO has been spent , returning the transaction that spends it .
-}
awaitUtxoSpent ::
forall w s e.
(AsContractError e)
=> TxOutRef
-> Contract w s e ChainIndexTx
awaitUtxoSpent = Contract.awaitUtxoSpent
-- | Wait for the status of a transaction to change
awaitTxStatusChange ::
forall w s e.
(AsContractError e)
=> TxId
-> Contract w s e TxStatus
-- BLOCK5
awaitTxStatusChange = Contract.awaitTxStatusChange
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/cd70d8acbde66c0f9a637d6b114cb6ca8bc4bb31/doc/plutus/tutorials/HandlingBlockchainEvents.hs | haskell | BLOCK1
BLOCK2
| Wait for the status of a transaction to change
BLOCK5 | # OPTIONS_GHC -fno - warn - unused - top - binds #
module HandlingBlockchainEvents() where
import Data.List.NonEmpty (NonEmpty)
import Ledger (CardanoAddress, TxId, TxOutRef)
import Plutus.ChainIndex (ChainIndexTx, TxStatus)
import Plutus.Contract (AsContractError, Contract)
import Plutus.Contract qualified as Contract
BLOCK0
| Wait until one or more unspent outputs are produced at an address .
-}
awaitUtxoProduced ::
forall w s e .
(AsContractError e)
=> CardanoAddress
-> Contract w s e (NonEmpty ChainIndexTx)
awaitUtxoProduced = Contract.awaitUtxoProduced
| Wait until the UTXO has been spent , returning the transaction that spends it .
-}
awaitUtxoSpent ::
forall w s e.
(AsContractError e)
=> TxOutRef
-> Contract w s e ChainIndexTx
awaitUtxoSpent = Contract.awaitUtxoSpent
awaitTxStatusChange ::
forall w s e.
(AsContractError e)
=> TxId
-> Contract w s e TxStatus
awaitTxStatusChange = Contract.awaitTxStatusChange
|
35856c41a1cc4ffa27fdffd8b9857900faa1f653f38e00e3a094697d152dcf34 | parapluu/Concuerror | depend_5.erl | -module(depend_5).
-export([depend_5/0]).
-export([scenarios/0]).
scenarios() -> [{?MODULE, inf, dpor}].
depend_5() ->
ets:new(table, [public, named_table]),
ets:insert(table, {x, 0}),
ets:insert(table, {y, 0}),
ets:insert(table, {z, 0}),
spawn(fun() -> ets:insert(table, {z, 1}) end),
spawn(fun() -> ets:insert(table, {x, 1}) end),
spawn(fun() -> ets:insert(table, {y, 1}),
ets:insert(table, {y, 2})
end),
spawn(fun() ->
[{x, X}] = ets:lookup(table, x),
case X of
0 -> ok;
1 ->
[{y, Y}] = ets:lookup(table, y),
case Y of
0 -> ok;
_ -> ets:lookup(table, z)
end
end
end),
spawn(fun() ->
ets:lookup(table, x)
end),
block().
block() ->
receive
after
infinity -> ok
end.
| null | https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests/suites/dpor_tests/src/depend_5.erl | erlang | -module(depend_5).
-export([depend_5/0]).
-export([scenarios/0]).
scenarios() -> [{?MODULE, inf, dpor}].
depend_5() ->
ets:new(table, [public, named_table]),
ets:insert(table, {x, 0}),
ets:insert(table, {y, 0}),
ets:insert(table, {z, 0}),
spawn(fun() -> ets:insert(table, {z, 1}) end),
spawn(fun() -> ets:insert(table, {x, 1}) end),
spawn(fun() -> ets:insert(table, {y, 1}),
ets:insert(table, {y, 2})
end),
spawn(fun() ->
[{x, X}] = ets:lookup(table, x),
case X of
0 -> ok;
1 ->
[{y, Y}] = ets:lookup(table, y),
case Y of
0 -> ok;
_ -> ets:lookup(table, z)
end
end
end),
spawn(fun() ->
ets:lookup(table, x)
end),
block().
block() ->
receive
after
infinity -> ok
end.
|
|
138e2ce1942f8a4589b02a35914ade8837ec9a084cedd5a521ad357ea57d5149 | konn/smooth | Types.hs | # LANGUAGE MonoLocalBinds #
# LANGUAGE ScopedTypeVariables #
module Numeric.Algebra.Smooth.Types (Vec, UVec, convVec) where
import Data.Sized (Sized)
import qualified Data.Sized as SV
import Data.Vector (Vector)
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
import GHC.TypeNats (KnownNat)
type Vec n a = Sized Vector n a
type UVec n a = Sized U.Vector n a
convVec ::
forall u v n a.
(G.Vector v a, G.Vector u a, KnownNat n, SV.DomC u a) =>
Sized v n a ->
Sized u n a
convVec = SV.unsafeToSized' . G.convert . SV.unsized
| null | https://raw.githubusercontent.com/konn/smooth/ce47287f6277f54b42a87df9ff2a444f185cde87/src/Numeric/Algebra/Smooth/Types.hs | haskell | # LANGUAGE MonoLocalBinds #
# LANGUAGE ScopedTypeVariables #
module Numeric.Algebra.Smooth.Types (Vec, UVec, convVec) where
import Data.Sized (Sized)
import qualified Data.Sized as SV
import Data.Vector (Vector)
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
import GHC.TypeNats (KnownNat)
type Vec n a = Sized Vector n a
type UVec n a = Sized U.Vector n a
convVec ::
forall u v n a.
(G.Vector v a, G.Vector u a, KnownNat n, SV.DomC u a) =>
Sized v n a ->
Sized u n a
convVec = SV.unsafeToSized' . G.convert . SV.unsized
|
|
e6b61e03079b57306454fc5b818327c1a63e3796707c249907fd1c38a97b064c | fukamachi/fukacl | macro.lisp | (in-package :fukacl)
(defun g!-symbol-p (s)
(if (symbolp s)
(let ((str (symbol-name s)))
(string= str "#" :start1 (1- (length str))))))
(defun o!-symbol-p (s)
(if (symbolp s)
(let ((str (symbol-name s)))
(string= str "%" :start1 (1- (length str))))))
(defun o!-symbol-to-g!-symbol (s)
(let ((str (symbol-name s)))
(symb (subseq str 0 (1- (length str)))
"#")))
(defmacro defmacro/g! (name args &body body)
(let ((symbs (remove-duplicates
(remove-if-not #'g!-symbol-p
(flatten body)))))
`(defmacro ,name ,args
(let ,(mapcar
(lambda (s)
`(,s (gensym ,(subseq
(symbol-name s)
2))))
symbs)
,@body))))
(defmacro defmacro* (name args &body body)
(let* ((os (remove-if-not #'o!-symbol-p args))
(gs (mapcar #'o!-symbol-to-g!-symbol os)))
`(defmacro/g! ,name ,args
`(let ,(mapcar #'list (list ,@gs) (list ,@os))
,(progn ,@body)))))
| null | https://raw.githubusercontent.com/fukamachi/fukacl/c633005755c4273dbee3aef54a8d86a8fbecc6f5/macro.lisp | lisp | (in-package :fukacl)
(defun g!-symbol-p (s)
(if (symbolp s)
(let ((str (symbol-name s)))
(string= str "#" :start1 (1- (length str))))))
(defun o!-symbol-p (s)
(if (symbolp s)
(let ((str (symbol-name s)))
(string= str "%" :start1 (1- (length str))))))
(defun o!-symbol-to-g!-symbol (s)
(let ((str (symbol-name s)))
(symb (subseq str 0 (1- (length str)))
"#")))
(defmacro defmacro/g! (name args &body body)
(let ((symbs (remove-duplicates
(remove-if-not #'g!-symbol-p
(flatten body)))))
`(defmacro ,name ,args
(let ,(mapcar
(lambda (s)
`(,s (gensym ,(subseq
(symbol-name s)
2))))
symbs)
,@body))))
(defmacro defmacro* (name args &body body)
(let* ((os (remove-if-not #'o!-symbol-p args))
(gs (mapcar #'o!-symbol-to-g!-symbol os)))
`(defmacro/g! ,name ,args
`(let ,(mapcar #'list (list ,@gs) (list ,@os))
,(progn ,@body)))))
|
|
97b6d46541dc831aedc4842621df7b10e6a298523aff18728535016e01e7db61 | aggelgian/erlang-algorithms | dfs_demo.erl | -module(dfs_demo).
-export([s1/0, s2/0]).
-spec s1() -> ok.
s1() ->
Root = 0,
G = graph_demo:g1(),
DFS = dfs:run(G, Root),
io:format("~p~n", [DFS]).
-spec s2() -> ok.
s2() ->
Root = "a",
G = graph_demo:g4(),
DFS = dfs:run(G, Root),
io:format("~p~n", [DFS]).
| null | https://raw.githubusercontent.com/aggelgian/erlang-algorithms/8ceee72146f2a6eff70a16e3e9a74d2ed072fa0a/demo/src/dfs_demo.erl | erlang | -module(dfs_demo).
-export([s1/0, s2/0]).
-spec s1() -> ok.
s1() ->
Root = 0,
G = graph_demo:g1(),
DFS = dfs:run(G, Root),
io:format("~p~n", [DFS]).
-spec s2() -> ok.
s2() ->
Root = "a",
G = graph_demo:g4(),
DFS = dfs:run(G, Root),
io:format("~p~n", [DFS]).
|
|
acaf703b0bccfd640fe4e629340f25aabb2fdd0ddc396f9b5e9921ab2687c039 | jwiegley/hierarchy | Hierarchy.hs | {-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
module Hierarchy where
import Control.Monad
import Control.Comonad.Trans.Cofree
import Control.Cond
-- | A 'TreeT' is a tree of values, where the (possible) branches are
represented by some MonadPlus ' m ' .
type TreeT m = CofreeT Maybe m
-- | Turn a list into a series of possibilities:
select :: MonadPlus m => [a] -> m a
select = msum . map pure
| Descend one level into a ' TreeT ' , yielding a list of values and their
-- possible associated trees.
descend :: MonadPlus m => TreeT m a -> m (a, Maybe (TreeT m a))
descend (CofreeT t) = t >>= \(a :< mp) -> pure (a, mp)
# INLINE descend #
-- | Perform a depth-first traversal of a 'TreeT', yielding each of its
-- contents. Note that breadth-first traversals cannot offer static memory
-- guarantees, so they are not provided by this module.
walk :: MonadPlus m => TreeT m a -> m a
walk (CofreeT t) = t >>= \(a :< mp) -> pure a `mplus` maybe mzero walk mp
# INLINEABLE walk #
-- | Given a 'TreeT', produce another 'TreeT' which yields only those elements
-- (and sub-trees) matching the given monadic conditional. This conditional
( see ' Control . Cond . ' ) can choose both elements and points of
-- recursion, making it capable of expressing any tree traversal in the form
-- of a predicate DSL. This differs from an expression-based traversal, like
or Lens , in that effects in ' m ' may be used to guide selection .
--
For example , to print all files under the current directory :
--
-- @
-- let files = winnow (directoryFiles ".") $ do
-- path <- query
-- liftIO $ putStrLn $ "Considering " ++ path
-- when (path @`elem@` [".@/@.git", ".@/@dist", ".@/@result"])
-- prune -- ignore these, and don't recurse into them
-- guard_ (".hs" @`isInfixOf@`) -- implicitly references 'path'
-- forM_ (walk files) $ liftIO . print
-- @
winnow :: MonadPlus m => TreeT m a -> CondT a m () -> TreeT m a
winnow (CofreeT t) p = CofreeT $ t >>= \(a :< mst) -> do
(mval, mnext) <- execCondT a p
let mnext' = winnow <$> mst <*> mnext
case mval of
Nothing -> maybe mzero runCofreeT mnext'
Just a' -> pure $ a' :< mnext'
| null | https://raw.githubusercontent.com/jwiegley/hierarchy/8c1a730605fef59e655c258684e89f5a7151d275/src/Hierarchy.hs | haskell | # LANGUAGE RankNTypes #
| A 'TreeT' is a tree of values, where the (possible) branches are
| Turn a list into a series of possibilities:
possible associated trees.
| Perform a depth-first traversal of a 'TreeT', yielding each of its
contents. Note that breadth-first traversals cannot offer static memory
guarantees, so they are not provided by this module.
| Given a 'TreeT', produce another 'TreeT' which yields only those elements
(and sub-trees) matching the given monadic conditional. This conditional
recursion, making it capable of expressing any tree traversal in the form
of a predicate DSL. This differs from an expression-based traversal, like
@
let files = winnow (directoryFiles ".") $ do
path <- query
liftIO $ putStrLn $ "Considering " ++ path
when (path @`elem@` [".@/@.git", ".@/@dist", ".@/@result"])
prune -- ignore these, and don't recurse into them
guard_ (".hs" @`isInfixOf@`) -- implicitly references 'path'
forM_ (walk files) $ liftIO . print
@ | # LANGUAGE ScopedTypeVariables #
module Hierarchy where
import Control.Monad
import Control.Comonad.Trans.Cofree
import Control.Cond
represented by some MonadPlus ' m ' .
type TreeT m = CofreeT Maybe m
select :: MonadPlus m => [a] -> m a
select = msum . map pure
| Descend one level into a ' TreeT ' , yielding a list of values and their
descend :: MonadPlus m => TreeT m a -> m (a, Maybe (TreeT m a))
descend (CofreeT t) = t >>= \(a :< mp) -> pure (a, mp)
# INLINE descend #
walk :: MonadPlus m => TreeT m a -> m a
walk (CofreeT t) = t >>= \(a :< mp) -> pure a `mplus` maybe mzero walk mp
# INLINEABLE walk #
( see ' Control . Cond . ' ) can choose both elements and points of
or Lens , in that effects in ' m ' may be used to guide selection .
For example , to print all files under the current directory :
winnow :: MonadPlus m => TreeT m a -> CondT a m () -> TreeT m a
winnow (CofreeT t) p = CofreeT $ t >>= \(a :< mst) -> do
(mval, mnext) <- execCondT a p
let mnext' = winnow <$> mst <*> mnext
case mval of
Nothing -> maybe mzero runCofreeT mnext'
Just a' -> pure $ a' :< mnext'
|
9b6cb77d2e22ba9eebe5bd4ea277a255c3d37d429557519a898c9711164fb17e | qingliangcn/mgee | mgee_tcp_listener.erl | %%%----------------------------------------------------------------------
%%% File : mgee_tcp_listener.erl
%%% Author : Qingliang
Created : 2010 - 01 - 02
Description : Ming game engine erlang
%%%----------------------------------------------------------------------
-module(mgee_tcp_listener).
-behaviour(gen_server).
-include("mgee.hrl").
-export([start_link/8]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {sock, on_startup, on_shutdown, label}).
%%--------------------------------------------------------------------
start_link(IPAddress, Port, SocketOpts,
ConcurrentAcceptorCount, AcceptorSup,
OnStartup, OnShutdown, Label) ->
gen_server:start_link(
?MODULE, {IPAddress, Port, SocketOpts,
ConcurrentAcceptorCount, AcceptorSup,
OnStartup, OnShutdown, Label}, []).
%%--------------------------------------------------------------------
init({IPAddress, Port, SocketOpts,
ConcurrentAcceptorCount, AcceptorSup,
{M,F,A} = OnStartup, OnShutdown, Label}) ->
?INFO_MSG("~p init: ~p",[?MODULE, {IPAddress, Port, SocketOpts,
ConcurrentAcceptorCount, AcceptorSup,
{M,F,A} = OnStartup, OnShutdown, Label} ]),
process_flag(trap_exit, true),
case gen_tcp:listen(Port, SocketOpts ++ [{active, false}]) of
{ok, LSock} ->
%% if listen successful ,we start several acceptor to accept it
lists:foreach(fun (_) ->
{ok, APid} = supervisor:start_child(
AcceptorSup, [LSock]),
APid ! {event, start}
end,
lists:duplicate(ConcurrentAcceptorCount, dummy)),
{ok, {LIPAddress, LPort}} = inet:sockname(LSock),
?TEST_MSG("started ~s on ~s:~p~n",
[Label, inet_parse:ntoa(LIPAddress), LPort]),
apply(M, F, A ++ [IPAddress, Port]),
{ok, #state{sock = LSock,
on_startup = OnStartup, on_shutdown = OnShutdown,
label = Label}};
{error, Reason} ->
error_logger:error_msg(
"failed to start ~s on ~s:~p - ~p~n",
[Label, inet_parse:ntoa(IPAddress), Port, Reason]),
{stop, {cannot_listen, IPAddress, Port, Reason}}
end.
handle_call(_Request, _From, State) ->
{noreply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, #state{sock=LSock, on_shutdown = {M,F,A}, label=Label}) ->
{ok, {IPAddress, Port}} = inet:sockname(LSock),
gen_tcp:close(LSock),
error_logger:info_msg("stopped ~s on ~s:~p~n",
[Label, inet_parse:ntoa(IPAddress), Port]),
apply(M, F, A ++ [IPAddress, Port]).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
| null | https://raw.githubusercontent.com/qingliangcn/mgee/b65babc3a34ef678ae2b25ce1a8fdd06b2707bb8/src/mgee_tcp_listener.erl | erlang | ----------------------------------------------------------------------
File : mgee_tcp_listener.erl
Author : Qingliang
----------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
if listen successful ,we start several acceptor to accept it | Created : 2010 - 01 - 02
Description : Ming game engine erlang
-module(mgee_tcp_listener).
-behaviour(gen_server).
-include("mgee.hrl").
-export([start_link/8]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {sock, on_startup, on_shutdown, label}).
start_link(IPAddress, Port, SocketOpts,
ConcurrentAcceptorCount, AcceptorSup,
OnStartup, OnShutdown, Label) ->
gen_server:start_link(
?MODULE, {IPAddress, Port, SocketOpts,
ConcurrentAcceptorCount, AcceptorSup,
OnStartup, OnShutdown, Label}, []).
init({IPAddress, Port, SocketOpts,
ConcurrentAcceptorCount, AcceptorSup,
{M,F,A} = OnStartup, OnShutdown, Label}) ->
?INFO_MSG("~p init: ~p",[?MODULE, {IPAddress, Port, SocketOpts,
ConcurrentAcceptorCount, AcceptorSup,
{M,F,A} = OnStartup, OnShutdown, Label} ]),
process_flag(trap_exit, true),
case gen_tcp:listen(Port, SocketOpts ++ [{active, false}]) of
{ok, LSock} ->
lists:foreach(fun (_) ->
{ok, APid} = supervisor:start_child(
AcceptorSup, [LSock]),
APid ! {event, start}
end,
lists:duplicate(ConcurrentAcceptorCount, dummy)),
{ok, {LIPAddress, LPort}} = inet:sockname(LSock),
?TEST_MSG("started ~s on ~s:~p~n",
[Label, inet_parse:ntoa(LIPAddress), LPort]),
apply(M, F, A ++ [IPAddress, Port]),
{ok, #state{sock = LSock,
on_startup = OnStartup, on_shutdown = OnShutdown,
label = Label}};
{error, Reason} ->
error_logger:error_msg(
"failed to start ~s on ~s:~p - ~p~n",
[Label, inet_parse:ntoa(IPAddress), Port, Reason]),
{stop, {cannot_listen, IPAddress, Port, Reason}}
end.
handle_call(_Request, _From, State) ->
{noreply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, #state{sock=LSock, on_shutdown = {M,F,A}, label=Label}) ->
{ok, {IPAddress, Port}} = inet:sockname(LSock),
gen_tcp:close(LSock),
error_logger:info_msg("stopped ~s on ~s:~p~n",
[Label, inet_parse:ntoa(IPAddress), Port]),
apply(M, F, A ++ [IPAddress, Port]).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
|
ce271e97b56012ad46100a337952ca818ec07dba89d9cdc6a94c3bd25034aea2 | headwinds/reagent-reframe-material-ui | templating.cljs | (ns devtools.formatters.templating
(:require-macros [devtools.oops :refer [oget oset ocall oapply safe-call]])
(:require [clojure.walk :refer [prewalk]]
[devtools.util :refer [pprint-str]]
[devtools.protocols :refer [ITemplate IGroup ISurrogate IFormat]]
[devtools.formatters.helpers :refer [pref cljs-value?]]
[devtools.formatters.state :refer [get-current-state prevent-recursion?]]
[clojure.string :as string]))
; -- object marking support -------------------------------------------------------------------------------------------------
(defn mark-as-group! [value]
(specify! value IGroup)
value)
(defn group? [value]
(satisfies? IGroup value))
(defn mark-as-template! [value]
(specify! value ITemplate)
value)
(defn template? [value]
(satisfies? ITemplate value))
(defn mark-as-surrogate! [value]
(specify! value ISurrogate)
value)
(defn surrogate? [value]
(satisfies? ISurrogate value))
(defn reference? [value]
(and (group? value)
(= (aget value 0) "object")))
; ---------------------------------------------------------------------------------------------------------------------------
(defn make-group [& items]
(let [group (mark-as-group! #js [])]
(doseq [item items]
(if (some? item)
(if (coll? item)
convenience helper to splat cljs collections
(.push group (pref item)))))
group))
(defn make-template
[tag style & children]
(let [tag (pref tag)
style (pref style)
template (mark-as-template! #js [tag (if (empty? style)
#js {}
#js {"style" style})])]
(doseq [child children]
(if (some? child)
(if (coll? child)
convenience helper to splat cljs collections
(if-let [child-value (pref child)]
(.push template child-value)))))
template))
(defn concat-templates! [template & templates]
(mark-as-template! (.apply (oget template "concat") template (into-array (map into-array (keep pref templates))))))
(defn extend-template! [template & args]
(concat-templates! template args))
(defn make-surrogate
; passing :target as body means that targt object body should be rendered using standard templates
; see <surrogate-body> in markup.cljs
([object] (make-surrogate object nil))
([object header] (make-surrogate object header nil))
([object header body] (make-surrogate object header body 0))
([object header body start-index]
(mark-as-surrogate! (js-obj
"target" object
"header" header
"body" body
"startIndex" (or start-index 0)))))
(defn get-surrogate-target [surrogate]
{:pre [(surrogate? surrogate)]}
(oget surrogate "target"))
(defn get-surrogate-header [surrogate]
{:pre [(surrogate? surrogate)]}
(oget surrogate "header"))
(defn get-surrogate-body [surrogate]
{:pre [(surrogate? surrogate)]}
(oget surrogate "body"))
(defn get-surrogate-start-index [surrogate]
{:pre [(surrogate? surrogate)]}
(oget surrogate "startIndex"))
(defn make-reference [object & [state-override-fn]]
{:pre [(or (nil? state-override-fn) (fn? state-override-fn))]}
(if (nil? object)
; this code is duplicated in markup.cljs <nil>
(make-template :span :nil-style :nil-label)
(let [sub-state (if (some? state-override-fn)
(state-override-fn (get-current-state))
(get-current-state))]
(make-group "object" #js {"object" object
"config" sub-state}))))
-- JSON ML support --------------------------------------------------------------------------------------------------------
a renderer from hiccup - like data markup to json - ml
;
; [[tag style] child1 child2 ...] -> #js [tag #js {"style" ...} child1 child2 ...]
;
(declare render-json-ml*)
(def ^:dynamic *current-render-stack* [])
(def ^:dynamic *current-render-path* [])
(defn print-preview [markup]
(binding [*print-level* 1]
(pr-str markup)))
(defn add-stack-separators [stack]
(interpose "-------------" stack))
(defn replace-fns-with-markers [stack]
(let [f (fn [v]
(if (fn? v)
"##fn##"
v))]
(prewalk f stack)))
(defn pprint-render-calls [stack]
(map pprint-str stack))
(defn pprint-render-stack [stack]
(string/join "\n" (-> stack
reverse
replace-fns-with-markers
pprint-render-calls
add-stack-separators)))
(defn pprint-render-path [path]
(pprint-str path))
(defn assert-markup-error [msg]
(assert false (str msg "\n"
"Render path: " (pprint-render-path *current-render-path*) "\n"
"Render stack:\n"
(pprint-render-stack *current-render-stack*))))
(defn surrogate-markup? [markup]
(and (sequential? markup) (= (first markup) "surrogate")))
(defn render-special [name args]
(case name
"surrogate" (let [obj (first args)
converted-args (map render-json-ml* (rest args))]
(apply make-surrogate (concat [obj] converted-args)))
"reference" (let [obj (first args)
converted-obj (if (surrogate-markup? obj) (render-json-ml* obj) obj)]
(apply make-reference (concat [converted-obj] (rest args))))
(assert-markup-error (str "no matching special tag name: '" name "'"))))
(defn emptyish? [v]
(if (or (seqable? v) (array? v) (string? v))
(empty? v)
false))
(defn render-subtree [tag children]
(let [[html-tag style] tag]
(apply make-template html-tag style (map render-json-ml* (remove emptyish? (map pref children))))))
(defn render-json-ml* [markup]
(if-not (sequential? markup)
markup
(binding [*current-render-path* (conj *current-render-path* (first markup))]
(let [tag (pref (first markup))]
(cond
(string? tag) (render-special tag (rest markup))
(sequential? tag) (render-subtree tag (rest markup))
:else (assert-markup-error (str "invalid json-ml markup at " (print-preview markup) ":")))))))
(defn render-json-ml [markup]
(binding [*current-render-stack* (conj *current-render-stack* markup)
*current-render-path* (conj *current-render-path* "<render-json-ml>")]
(render-json-ml* markup)))
; -- template rendering -----------------------------------------------------------------------------------------------------
(defn ^:dynamic assert-failed-markup-rendering [initial-value value]
(assert false (str "result of markup rendering must be a template,\n"
"resolved to " (pprint-str value)
"initial value: " (pprint-str initial-value))))
(defn render-markup* [initial-value value]
(cond
(fn? value) (recur initial-value (value))
(keyword? value) (recur initial-value (pref value))
(sequential? value) (recur initial-value (render-json-ml value))
(template? value) value
(surrogate? value) value
(reference? value) value
:else (assert-failed-markup-rendering initial-value value)))
(defn render-markup [value]
(render-markup* value value))
| null | https://raw.githubusercontent.com/headwinds/reagent-reframe-material-ui/8a6fba82a026cfedca38491becac85751be9a9d4/resources/public/js/out/devtools/formatters/templating.cljs | clojure | -- object marking support -------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
passing :target as body means that targt object body should be rendered using standard templates
see <surrogate-body> in markup.cljs
this code is duplicated in markup.cljs <nil>
[[tag style] child1 child2 ...] -> #js [tag #js {"style" ...} child1 child2 ...]
-- template rendering ----------------------------------------------------------------------------------------------------- | (ns devtools.formatters.templating
(:require-macros [devtools.oops :refer [oget oset ocall oapply safe-call]])
(:require [clojure.walk :refer [prewalk]]
[devtools.util :refer [pprint-str]]
[devtools.protocols :refer [ITemplate IGroup ISurrogate IFormat]]
[devtools.formatters.helpers :refer [pref cljs-value?]]
[devtools.formatters.state :refer [get-current-state prevent-recursion?]]
[clojure.string :as string]))
(defn mark-as-group! [value]
(specify! value IGroup)
value)
(defn group? [value]
(satisfies? IGroup value))
(defn mark-as-template! [value]
(specify! value ITemplate)
value)
(defn template? [value]
(satisfies? ITemplate value))
(defn mark-as-surrogate! [value]
(specify! value ISurrogate)
value)
(defn surrogate? [value]
(satisfies? ISurrogate value))
(defn reference? [value]
(and (group? value)
(= (aget value 0) "object")))
(defn make-group [& items]
(let [group (mark-as-group! #js [])]
(doseq [item items]
(if (some? item)
(if (coll? item)
convenience helper to splat cljs collections
(.push group (pref item)))))
group))
(defn make-template
[tag style & children]
(let [tag (pref tag)
style (pref style)
template (mark-as-template! #js [tag (if (empty? style)
#js {}
#js {"style" style})])]
(doseq [child children]
(if (some? child)
(if (coll? child)
convenience helper to splat cljs collections
(if-let [child-value (pref child)]
(.push template child-value)))))
template))
(defn concat-templates! [template & templates]
(mark-as-template! (.apply (oget template "concat") template (into-array (map into-array (keep pref templates))))))
(defn extend-template! [template & args]
(concat-templates! template args))
(defn make-surrogate
([object] (make-surrogate object nil))
([object header] (make-surrogate object header nil))
([object header body] (make-surrogate object header body 0))
([object header body start-index]
(mark-as-surrogate! (js-obj
"target" object
"header" header
"body" body
"startIndex" (or start-index 0)))))
(defn get-surrogate-target [surrogate]
{:pre [(surrogate? surrogate)]}
(oget surrogate "target"))
(defn get-surrogate-header [surrogate]
{:pre [(surrogate? surrogate)]}
(oget surrogate "header"))
(defn get-surrogate-body [surrogate]
{:pre [(surrogate? surrogate)]}
(oget surrogate "body"))
(defn get-surrogate-start-index [surrogate]
{:pre [(surrogate? surrogate)]}
(oget surrogate "startIndex"))
(defn make-reference [object & [state-override-fn]]
{:pre [(or (nil? state-override-fn) (fn? state-override-fn))]}
(if (nil? object)
(make-template :span :nil-style :nil-label)
(let [sub-state (if (some? state-override-fn)
(state-override-fn (get-current-state))
(get-current-state))]
(make-group "object" #js {"object" object
"config" sub-state}))))
-- JSON ML support --------------------------------------------------------------------------------------------------------
a renderer from hiccup - like data markup to json - ml
(declare render-json-ml*)
(def ^:dynamic *current-render-stack* [])
(def ^:dynamic *current-render-path* [])
(defn print-preview [markup]
(binding [*print-level* 1]
(pr-str markup)))
(defn add-stack-separators [stack]
(interpose "-------------" stack))
(defn replace-fns-with-markers [stack]
(let [f (fn [v]
(if (fn? v)
"##fn##"
v))]
(prewalk f stack)))
(defn pprint-render-calls [stack]
(map pprint-str stack))
(defn pprint-render-stack [stack]
(string/join "\n" (-> stack
reverse
replace-fns-with-markers
pprint-render-calls
add-stack-separators)))
(defn pprint-render-path [path]
(pprint-str path))
(defn assert-markup-error [msg]
(assert false (str msg "\n"
"Render path: " (pprint-render-path *current-render-path*) "\n"
"Render stack:\n"
(pprint-render-stack *current-render-stack*))))
(defn surrogate-markup? [markup]
(and (sequential? markup) (= (first markup) "surrogate")))
(defn render-special [name args]
(case name
"surrogate" (let [obj (first args)
converted-args (map render-json-ml* (rest args))]
(apply make-surrogate (concat [obj] converted-args)))
"reference" (let [obj (first args)
converted-obj (if (surrogate-markup? obj) (render-json-ml* obj) obj)]
(apply make-reference (concat [converted-obj] (rest args))))
(assert-markup-error (str "no matching special tag name: '" name "'"))))
(defn emptyish? [v]
(if (or (seqable? v) (array? v) (string? v))
(empty? v)
false))
(defn render-subtree [tag children]
(let [[html-tag style] tag]
(apply make-template html-tag style (map render-json-ml* (remove emptyish? (map pref children))))))
(defn render-json-ml* [markup]
(if-not (sequential? markup)
markup
(binding [*current-render-path* (conj *current-render-path* (first markup))]
(let [tag (pref (first markup))]
(cond
(string? tag) (render-special tag (rest markup))
(sequential? tag) (render-subtree tag (rest markup))
:else (assert-markup-error (str "invalid json-ml markup at " (print-preview markup) ":")))))))
(defn render-json-ml [markup]
(binding [*current-render-stack* (conj *current-render-stack* markup)
*current-render-path* (conj *current-render-path* "<render-json-ml>")]
(render-json-ml* markup)))
(defn ^:dynamic assert-failed-markup-rendering [initial-value value]
(assert false (str "result of markup rendering must be a template,\n"
"resolved to " (pprint-str value)
"initial value: " (pprint-str initial-value))))
(defn render-markup* [initial-value value]
(cond
(fn? value) (recur initial-value (value))
(keyword? value) (recur initial-value (pref value))
(sequential? value) (recur initial-value (render-json-ml value))
(template? value) value
(surrogate? value) value
(reference? value) value
:else (assert-failed-markup-rendering initial-value value)))
(defn render-markup [value]
(render-markup* value value))
|
f385a46e48969d1a67cbef9e4712b2df7cf76b20a23489f85cb036a29428ecd5 | typedclojure/typedclojure | rep.cljc | Copyright ( c ) , contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns typed.clj.annotator.rep
"Intermediate representation for types"
Note : depends on this ns
)
;;========================
;;Type Predicates
;;========================
(defn type? [t]
(and (map? t)
(keyword? (:op t))))
(defn alias? [t]
(= :alias (:op t)))
(defn HMap? [t]
(= :HMap (:op t)))
(defn HVec? [t]
(= :HVec (:op t)))
(defn union? [t]
(= :union (:op t)))
(defn Any? [m]
{:pre [(map? m)]
:post [(boolean? %)]}
(= :Top (:op m)))
(defn unknown? [m]
(= :unknown
(:op m)))
(defn nothing? [t]
(boolean
(when (union? t)
(empty? (:types t)))))
(def val? (comp boolean #{:val} :op))
;;========================
Type Constructors
;;========================
(defn -class? [m]
(boolean (#{:class} (:op m))))
(defn -alias [name]
{:pre [(symbol? name)]}
{:op :alias
:name name})
(def -any {:op :Top})
(def -nothing {:op :union :types #{}})
(defn -val [v]
{:op :val
:val v})
(defn -class [cls args]
{:pre [(vector? args)
(every? type? args)]}
(assert ((some-fn keyword? string?) cls) cls)
{:op :class
:typed.clj.annotator.rep/class-instance cls
:args args})
(defn make-HMap [req opt]
{:op :HMap
:typed.clj.annotator.rep/HMap-req req
:typed.clj.annotator.rep/HMap-opt opt})
;;========================
;; Inference results
;;========================
(defn infer-result [path type]
{:op :path-type
:type type
:path path})
(defn infer-results [paths type]
(map #(infer-result % type) paths))
;; ========================
;; Path elements
;; ========================
(defn key-path
([keys key] (key-path {} keys key))
([kw-entries keys key]
{:pre [(keyword? key)]}
{:op :key
( ( ValType Kw ) ) for constant keyword entries
:kw-entries kw-entries
:keys keys
:key key}))
(defn map-keys-path []
{:op :map-keys})
(defn map-vals-path []
{:op :map-vals})
for zero arity , use ( fn - dom - path 0 -1 )
(defn fn-dom-path [arity pos]
(assert (< pos arity)
(str "Arity: " arity
"Position:" pos))
{:op :fn-domain
:arity arity :position pos})
(defn fn-rng-path [arity]
{:op :fn-range
:arity arity})
(defn seq-entry []
{:op :seq-entry})
(defn transient-vector-entry []
{:op :transient-vector-entry})
(defn index-path [count nth]
{:op :index
:count count
:nth nth})
(defn vec-entry-path []
{:op :vec-entry})
(defn set-entry []
{:op :set-entry})
(defn atom-contents []
{:op :atom-contents})
(defn var-path
([name] (var-path nil name))
([ns name]
{:pre [((some-fn symbol? nil?) ns)
(symbol? name)]}
{:op :var
:ns ns
:name name}))
| null | https://raw.githubusercontent.com/typedclojure/typedclojure/45556897356f3c9cbc7b1b6b4df263086a9d5803/typed/clj.annotator/src/typed/clj/annotator/rep.cljc | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
========================
Type Predicates
========================
========================
========================
========================
Inference results
========================
========================
Path elements
======================== | Copyright ( c ) , contributors .
(ns typed.clj.annotator.rep
"Intermediate representation for types"
Note : depends on this ns
)
(defn type? [t]
(and (map? t)
(keyword? (:op t))))
(defn alias? [t]
(= :alias (:op t)))
(defn HMap? [t]
(= :HMap (:op t)))
(defn HVec? [t]
(= :HVec (:op t)))
(defn union? [t]
(= :union (:op t)))
(defn Any? [m]
{:pre [(map? m)]
:post [(boolean? %)]}
(= :Top (:op m)))
(defn unknown? [m]
(= :unknown
(:op m)))
(defn nothing? [t]
(boolean
(when (union? t)
(empty? (:types t)))))
(def val? (comp boolean #{:val} :op))
Type Constructors
(defn -class? [m]
(boolean (#{:class} (:op m))))
(defn -alias [name]
{:pre [(symbol? name)]}
{:op :alias
:name name})
(def -any {:op :Top})
(def -nothing {:op :union :types #{}})
(defn -val [v]
{:op :val
:val v})
(defn -class [cls args]
{:pre [(vector? args)
(every? type? args)]}
(assert ((some-fn keyword? string?) cls) cls)
{:op :class
:typed.clj.annotator.rep/class-instance cls
:args args})
(defn make-HMap [req opt]
{:op :HMap
:typed.clj.annotator.rep/HMap-req req
:typed.clj.annotator.rep/HMap-opt opt})
(defn infer-result [path type]
{:op :path-type
:type type
:path path})
(defn infer-results [paths type]
(map #(infer-result % type) paths))
(defn key-path
([keys key] (key-path {} keys key))
([kw-entries keys key]
{:pre [(keyword? key)]}
{:op :key
( ( ValType Kw ) ) for constant keyword entries
:kw-entries kw-entries
:keys keys
:key key}))
(defn map-keys-path []
{:op :map-keys})
(defn map-vals-path []
{:op :map-vals})
for zero arity , use ( fn - dom - path 0 -1 )
(defn fn-dom-path [arity pos]
(assert (< pos arity)
(str "Arity: " arity
"Position:" pos))
{:op :fn-domain
:arity arity :position pos})
(defn fn-rng-path [arity]
{:op :fn-range
:arity arity})
(defn seq-entry []
{:op :seq-entry})
(defn transient-vector-entry []
{:op :transient-vector-entry})
(defn index-path [count nth]
{:op :index
:count count
:nth nth})
(defn vec-entry-path []
{:op :vec-entry})
(defn set-entry []
{:op :set-entry})
(defn atom-contents []
{:op :atom-contents})
(defn var-path
([name] (var-path nil name))
([ns name]
{:pre [((some-fn symbol? nil?) ns)
(symbol? name)]}
{:op :var
:ns ns
:name name}))
|
7effe8867ffae1457e4961a1c67b7adcf7f68ffcb26d244273b4689668c5f5dd | dstarcev/stepic-haskell | Task17_Unique.hs | module Module3.Task17_Unique (change) where
import Data.List (nub, sort)
-- system code
coins :: (Ord a, Num a) => [a]
coins = [2, 3, 7]
--solution code
change :: (Ord a, Num a) => a -> [[a]]
change = f where
f 0 = [[]]
f s = nub [
sort (coin:ch) |
coin <- coins,
coin <= s,
ch <- (f $ s - coin)]
| null | https://raw.githubusercontent.com/dstarcev/stepic-haskell/6a8cf4b3cc17333ac4175e825db57dbe151ebae0/src/Module3/Task17_Unique.hs | haskell | system code
solution code | module Module3.Task17_Unique (change) where
import Data.List (nub, sort)
coins :: (Ord a, Num a) => [a]
coins = [2, 3, 7]
change :: (Ord a, Num a) => a -> [[a]]
change = f where
f 0 = [[]]
f s = nub [
sort (coin:ch) |
coin <- coins,
coin <= s,
ch <- (f $ s - coin)]
|
2b5bace69e6e92f244b1f07a5084c12cabeca03755a38c01843aad538ff3583e | bohonghuang/cl-gtk4 | gdk4-cairo.lisp | ;;;; examples/gdk4-cairo.lisp
Copyright ( C ) 2022 - 2023
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation , 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 Lesser General Public License for more details .
;;;;
You should have received a copy of the GNU Lesser General Public License
;;;; along with this program. If not, see </>.
(cl:defpackage cairo-gobject
(:use)
(:export #:*ns*))
(cl:in-package #:cairo-gobject)
(gir-wrapper:define-gir-namespace "cairo")
(cl:defpackage gdk4.example
(:use #:cl #:gtk4)
(:export #:cairo-test))
(cl:in-package #:gdk4.example)
(cffi:defcstruct gdk-rgba
(red :double)
(green :double)
(blue :double)
(alpha :double))
(defmacro with-gdk-rgba ((pointer color) &body body)
`(locally
#+sbcl (declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(cffi:with-foreign-object (,pointer '(:struct gdk-rgba))
(let ((,pointer (make-instance 'gir::struct-instance
:class (gir:nget gdk::*ns* "RGBA")
:this ,pointer)))
(gdk:rgba-parse ,pointer ,color)
(locally
#+sbcl (declare (sb-ext:unmuffle-conditions sb-ext:compiler-note))
,@body)))))
(declaim (ftype (function (t t t t) t) draw-func))
(cffi:defcallback %draw-func :void ((area :pointer)
(cr :pointer)
(width :int)
(height :int)
(data :pointer))
(declare (ignore data))
(let ((cairo:*context* (make-instance 'cairo:context
:pointer cr
:width width
:height height
:pixel-based-p nil)))
(draw-func (make-instance 'gir::object-instance
:class (gir:nget gtk:*ns* "DrawingArea")
:this area)
(make-instance 'gir::struct-instance
:class (gir:nget cairo-gobject:*ns* "Context")
:this cr)
width height)))
(define-application (:name cairo-test
:id "org.bohonghuang.gdk4-cairo-example")
(defun draw-func (area cr width height)
(declare (ignore area)
(optimize (speed 3)
(debug 0)
(safety 0)))
(let ((width (coerce (the fixnum width) 'single-float))
(height (coerce (the fixnum height) 'single-float))
(fpi (coerce pi 'single-float)))
(let* ((radius (/ (min width height) 2.0))
(stroke-width (/ radius 8.0))
(button-radius (* radius 0.4)))
(declare (type single-float radius stroke-width button-radius))
(with-gdk-rgba (color "#000000")
(cairo:arc (/ width 2.0) (/ height 2.0) radius 0.0 (* 2.0 fpi))
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path))
(with-gdk-rgba (color "#FF0000")
(cairo:arc (/ width 2.0) (/ height 2.0) (- radius stroke-width) pi (* 2.0 fpi))
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path))
(with-gdk-rgba (color "#FFFFFF")
(cairo:arc (/ width 2.0) (/ height 2.0) (- radius stroke-width) 0.0 fpi)
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path))
(with-gdk-rgba (color "#000000")
(let ((bar-length (sqrt (- (expt (* radius 2) 2.0) (expt stroke-width 2.0)))))
(declare (type single-float bar-length))
(cairo:rectangle (+ (- (/ width 2.0) radius) (- radius (/ bar-length 2.0)))
(+ (- (/ height 2.0) radius) (- radius (/ stroke-width 2.0)))
bar-length
stroke-width))
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path))
(with-gdk-rgba (color "#000000")
(cairo:arc (/ width 2.0) (/ height 2.0) button-radius 0.0 (* 2.0 fpi))
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path))
(with-gdk-rgba (color "#FFFFFF")
(cairo:arc (/ width 2.0) (/ height 2.0) (- button-radius stroke-width) 0.0 (* 2.0 fpi))
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path)))))
(define-main-window (window (make-application-window :application *application*))
(setf (window-title window) "Drawing Area Test")
(let ((area (gtk:make-drawing-area)))
(setf (drawing-area-content-width area) 200
(drawing-area-content-height area) 200
(drawing-area-draw-func area) (list (cffi:callback %draw-func)
(cffi:null-pointer)
(cffi:null-pointer)))
(setf (window-child window) area))
(unless (widget-visible-p window)
(window-present window))))
| null | https://raw.githubusercontent.com/bohonghuang/cl-gtk4/ad8fae4171bdf9532cd268d3e0a57548b3d92ec6/examples/gdk4-cairo.lisp | lisp | examples/gdk4-cairo.lisp
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see </>. |
Copyright ( C ) 2022 - 2023
the Free Software Foundation , either version 3 of the License , or
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
(cl:defpackage cairo-gobject
(:use)
(:export #:*ns*))
(cl:in-package #:cairo-gobject)
(gir-wrapper:define-gir-namespace "cairo")
(cl:defpackage gdk4.example
(:use #:cl #:gtk4)
(:export #:cairo-test))
(cl:in-package #:gdk4.example)
(cffi:defcstruct gdk-rgba
(red :double)
(green :double)
(blue :double)
(alpha :double))
(defmacro with-gdk-rgba ((pointer color) &body body)
`(locally
#+sbcl (declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(cffi:with-foreign-object (,pointer '(:struct gdk-rgba))
(let ((,pointer (make-instance 'gir::struct-instance
:class (gir:nget gdk::*ns* "RGBA")
:this ,pointer)))
(gdk:rgba-parse ,pointer ,color)
(locally
#+sbcl (declare (sb-ext:unmuffle-conditions sb-ext:compiler-note))
,@body)))))
(declaim (ftype (function (t t t t) t) draw-func))
(cffi:defcallback %draw-func :void ((area :pointer)
(cr :pointer)
(width :int)
(height :int)
(data :pointer))
(declare (ignore data))
(let ((cairo:*context* (make-instance 'cairo:context
:pointer cr
:width width
:height height
:pixel-based-p nil)))
(draw-func (make-instance 'gir::object-instance
:class (gir:nget gtk:*ns* "DrawingArea")
:this area)
(make-instance 'gir::struct-instance
:class (gir:nget cairo-gobject:*ns* "Context")
:this cr)
width height)))
(define-application (:name cairo-test
:id "org.bohonghuang.gdk4-cairo-example")
(defun draw-func (area cr width height)
(declare (ignore area)
(optimize (speed 3)
(debug 0)
(safety 0)))
(let ((width (coerce (the fixnum width) 'single-float))
(height (coerce (the fixnum height) 'single-float))
(fpi (coerce pi 'single-float)))
(let* ((radius (/ (min width height) 2.0))
(stroke-width (/ radius 8.0))
(button-radius (* radius 0.4)))
(declare (type single-float radius stroke-width button-radius))
(with-gdk-rgba (color "#000000")
(cairo:arc (/ width 2.0) (/ height 2.0) radius 0.0 (* 2.0 fpi))
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path))
(with-gdk-rgba (color "#FF0000")
(cairo:arc (/ width 2.0) (/ height 2.0) (- radius stroke-width) pi (* 2.0 fpi))
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path))
(with-gdk-rgba (color "#FFFFFF")
(cairo:arc (/ width 2.0) (/ height 2.0) (- radius stroke-width) 0.0 fpi)
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path))
(with-gdk-rgba (color "#000000")
(let ((bar-length (sqrt (- (expt (* radius 2) 2.0) (expt stroke-width 2.0)))))
(declare (type single-float bar-length))
(cairo:rectangle (+ (- (/ width 2.0) radius) (- radius (/ bar-length 2.0)))
(+ (- (/ height 2.0) radius) (- radius (/ stroke-width 2.0)))
bar-length
stroke-width))
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path))
(with-gdk-rgba (color "#000000")
(cairo:arc (/ width 2.0) (/ height 2.0) button-radius 0.0 (* 2.0 fpi))
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path))
(with-gdk-rgba (color "#FFFFFF")
(cairo:arc (/ width 2.0) (/ height 2.0) (- button-radius stroke-width) 0.0 (* 2.0 fpi))
(gdk:cairo-set-source-rgba cr color)
(cairo:fill-path)))))
(define-main-window (window (make-application-window :application *application*))
(setf (window-title window) "Drawing Area Test")
(let ((area (gtk:make-drawing-area)))
(setf (drawing-area-content-width area) 200
(drawing-area-content-height area) 200
(drawing-area-draw-func area) (list (cffi:callback %draw-func)
(cffi:null-pointer)
(cffi:null-pointer)))
(setf (window-child window) area))
(unless (widget-visible-p window)
(window-present window))))
|
03781eeb2d42f524d8c130ece3f43381750dc99c122459ab4370ea99dc220203 | TrustInSoft/tis-kernel | source_manager.ml | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
type tab = {
tab_name : string ;
tab_file : string ;
tab_page : int ;
tab_select : line:int -> unit ;
tab_source_view : GSourceView2.source_view;
}
type t = {
notebook : GPack.notebook;
file_index : (string,tab) Hashtbl.t;
name_index : (string,tab) Hashtbl.t;
page_index : (int,tab) Hashtbl.t;
mutable pages : int ;
}
let make ?tab_pos ?packing () =
let notebook = GPack.notebook
~scrollable:true ~show_tabs:true ?tab_pos ?packing ()
in
notebook#set_enable_popup true ;
{
notebook = notebook ;
file_index = Hashtbl.create 7;
name_index = Hashtbl.create 7;
page_index = Hashtbl.create 7;
pages = 0 ;
}
let input_channel b ic =
let buf = Bytes.create 1024 and len = ref 0 in
while len := input ic buf 0 1024; !len > 0 do
Buffer.add_substring b buf 0 !len
done
let with_file name ~f =
try
let ic = open_in_gen [Open_rdonly] 0o644 name in
try f ic; close_in ic with _exn ->
close_in ic (*; !flash_info ("Error: "^Printexc.to_string exn)*)
with _exn -> ()
let clear w =
begin
for _i=1 to w.pages do w.notebook#remove_page 0 done ;
w.pages <- 0 ;
Hashtbl.clear w.file_index ;
Hashtbl.clear w.name_index ;
Hashtbl.clear w.page_index ;
end
let later f = ignore (Glib.Idle.add (fun () -> f () ; false))
let select_file w filename =
try
let tab = Hashtbl.find w.file_index filename in
later (fun () -> w.notebook#goto_page tab.tab_page)
with Not_found -> ()
let select_name w title =
try
let tab = Hashtbl.find w.name_index title in
later (fun () -> w.notebook#goto_page tab.tab_page)
with Not_found -> ()
let selection_locked = ref false
let load_file w ?title ~filename ?(line=(-1)) ~click_cb () =
Gui_parameters.debug ~level:2 "Opening file %S line %d" filename line ;
let tab =
begin
try Hashtbl.find w.file_index filename
with Not_found ->
let name = match title with
| None -> Filepath.pretty filename
| Some s -> s
in
let label = GMisc.label ~text:name () in
let sw = GBin.scrolled_window
~vpolicy:`AUTOMATIC
~hpolicy:`AUTOMATIC
~packing:(fun arg ->
ignore
(w.notebook#append_page ~tab_label:label#coerce arg))
() in
let original_source_view = Source_viewer.make ~name:"original_source"
~packing:sw#add ()
in
let window = (original_source_view :> GText.view) in
let page_num = w.notebook#page_num sw#coerce in
let b = Buffer.create 1024 in
with_file filename ~f:(input_channel b) ;
let s = Wutil.to_utf8 (Buffer.contents b) in
Buffer.reset b;
let (buffer:GText.buffer) = window#buffer in
buffer#set_text s;
let select_line ~line =
if !selection_locked then
ignore a single call and release the lock for the next one
selection_locked := false
else
begin
w.notebook#goto_page page_num;
if line >= 0 then
let it = buffer#get_iter (`LINE (line-1)) in
buffer#place_cursor ~where:it;
let y = if buffer#line_count < 20 then 0.23 else 0.3 in
window#scroll_to_mark ~use_align:true ~yalign:y `INSERT
end
in
(* Ctrl+click opens the external viewer at the current line and file. *)
ignore (window#event#connect#button_press
~callback:
(fun ev ->
(if GdkEvent.Button.button ev = 1 &&
List.mem `CONTROL
(Gdk.Convert.modifier (GdkEvent.Button.state ev))
then
Wutil.later
(fun () ->
try
let cur_page = w.notebook#current_page in
let tab = Hashtbl.find w.page_index cur_page in
let file = tab.tab_file in
let iter = buffer#get_iter_at_mark `INSERT in
let line = iter#line + 1 in
Gtk_helper.open_in_external_viewer ~line file
with Not_found ->
failwith (Printf.sprintf "ctrl+click cb: invalid page %d"
w.notebook#current_page)
);
if GdkEvent.Button.button ev = 1 then
Wutil.later
(fun () ->
try
let iter = buffer#get_iter_at_mark `INSERT in
let line = iter#line + 1 in
let col = iter#line_index in
let offset = iter#offset in
let pos = {Lexing.pos_fname = filename;
Lexing.pos_lnum = line;
Lexing.pos_bol = offset - col;
Lexing.pos_cnum = offset;} in
let localz =
Pretty_source.loc_to_localizable ~precise_col:true pos
in
click_cb localz
with Not_found ->
failwith (Printf.sprintf "click cb: invalid page %d"
w.notebook#current_page)
);
);
false (* other events are processed as usual *)
));
let tab = {
tab_file = filename ;
tab_name = name ;
tab_select = select_line ;
tab_page = page_num ;
tab_source_view = original_source_view;
} in
w.pages <- succ page_num ;
Hashtbl.add w.file_index filename tab ;
Hashtbl.add w.name_index name tab ;
Hashtbl.add w.page_index page_num tab ;
tab
end
in
(* Runs this at idle priority to let the text be displayed before. *)
later (fun () -> tab.tab_select ~line)
let get_current_source_view w =
try
let tab = Hashtbl.find w.page_index w.notebook#current_page in
tab.tab_source_view
with Not_found ->
failwith (Printf.sprintf "get_source_view: invalid page %d"
w.notebook#current_page)
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/gui/source_manager.ml | 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.
************************************************************************
; !flash_info ("Error: "^Printexc.to_string exn)
Ctrl+click opens the external viewer at the current line and file.
other events are processed as usual
Runs this at idle priority to let the text be displayed before.
Local Variables:
compile-command: "make -C ../../.."
End:
| This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
type tab = {
tab_name : string ;
tab_file : string ;
tab_page : int ;
tab_select : line:int -> unit ;
tab_source_view : GSourceView2.source_view;
}
type t = {
notebook : GPack.notebook;
file_index : (string,tab) Hashtbl.t;
name_index : (string,tab) Hashtbl.t;
page_index : (int,tab) Hashtbl.t;
mutable pages : int ;
}
let make ?tab_pos ?packing () =
let notebook = GPack.notebook
~scrollable:true ~show_tabs:true ?tab_pos ?packing ()
in
notebook#set_enable_popup true ;
{
notebook = notebook ;
file_index = Hashtbl.create 7;
name_index = Hashtbl.create 7;
page_index = Hashtbl.create 7;
pages = 0 ;
}
let input_channel b ic =
let buf = Bytes.create 1024 and len = ref 0 in
while len := input ic buf 0 1024; !len > 0 do
Buffer.add_substring b buf 0 !len
done
let with_file name ~f =
try
let ic = open_in_gen [Open_rdonly] 0o644 name in
try f ic; close_in ic with _exn ->
with _exn -> ()
let clear w =
begin
for _i=1 to w.pages do w.notebook#remove_page 0 done ;
w.pages <- 0 ;
Hashtbl.clear w.file_index ;
Hashtbl.clear w.name_index ;
Hashtbl.clear w.page_index ;
end
let later f = ignore (Glib.Idle.add (fun () -> f () ; false))
let select_file w filename =
try
let tab = Hashtbl.find w.file_index filename in
later (fun () -> w.notebook#goto_page tab.tab_page)
with Not_found -> ()
let select_name w title =
try
let tab = Hashtbl.find w.name_index title in
later (fun () -> w.notebook#goto_page tab.tab_page)
with Not_found -> ()
let selection_locked = ref false
let load_file w ?title ~filename ?(line=(-1)) ~click_cb () =
Gui_parameters.debug ~level:2 "Opening file %S line %d" filename line ;
let tab =
begin
try Hashtbl.find w.file_index filename
with Not_found ->
let name = match title with
| None -> Filepath.pretty filename
| Some s -> s
in
let label = GMisc.label ~text:name () in
let sw = GBin.scrolled_window
~vpolicy:`AUTOMATIC
~hpolicy:`AUTOMATIC
~packing:(fun arg ->
ignore
(w.notebook#append_page ~tab_label:label#coerce arg))
() in
let original_source_view = Source_viewer.make ~name:"original_source"
~packing:sw#add ()
in
let window = (original_source_view :> GText.view) in
let page_num = w.notebook#page_num sw#coerce in
let b = Buffer.create 1024 in
with_file filename ~f:(input_channel b) ;
let s = Wutil.to_utf8 (Buffer.contents b) in
Buffer.reset b;
let (buffer:GText.buffer) = window#buffer in
buffer#set_text s;
let select_line ~line =
if !selection_locked then
ignore a single call and release the lock for the next one
selection_locked := false
else
begin
w.notebook#goto_page page_num;
if line >= 0 then
let it = buffer#get_iter (`LINE (line-1)) in
buffer#place_cursor ~where:it;
let y = if buffer#line_count < 20 then 0.23 else 0.3 in
window#scroll_to_mark ~use_align:true ~yalign:y `INSERT
end
in
ignore (window#event#connect#button_press
~callback:
(fun ev ->
(if GdkEvent.Button.button ev = 1 &&
List.mem `CONTROL
(Gdk.Convert.modifier (GdkEvent.Button.state ev))
then
Wutil.later
(fun () ->
try
let cur_page = w.notebook#current_page in
let tab = Hashtbl.find w.page_index cur_page in
let file = tab.tab_file in
let iter = buffer#get_iter_at_mark `INSERT in
let line = iter#line + 1 in
Gtk_helper.open_in_external_viewer ~line file
with Not_found ->
failwith (Printf.sprintf "ctrl+click cb: invalid page %d"
w.notebook#current_page)
);
if GdkEvent.Button.button ev = 1 then
Wutil.later
(fun () ->
try
let iter = buffer#get_iter_at_mark `INSERT in
let line = iter#line + 1 in
let col = iter#line_index in
let offset = iter#offset in
let pos = {Lexing.pos_fname = filename;
Lexing.pos_lnum = line;
Lexing.pos_bol = offset - col;
Lexing.pos_cnum = offset;} in
let localz =
Pretty_source.loc_to_localizable ~precise_col:true pos
in
click_cb localz
with Not_found ->
failwith (Printf.sprintf "click cb: invalid page %d"
w.notebook#current_page)
);
);
));
let tab = {
tab_file = filename ;
tab_name = name ;
tab_select = select_line ;
tab_page = page_num ;
tab_source_view = original_source_view;
} in
w.pages <- succ page_num ;
Hashtbl.add w.file_index filename tab ;
Hashtbl.add w.name_index name tab ;
Hashtbl.add w.page_index page_num tab ;
tab
end
in
later (fun () -> tab.tab_select ~line)
let get_current_source_view w =
try
let tab = Hashtbl.find w.page_index w.notebook#current_page in
tab.tab_source_view
with Not_found ->
failwith (Printf.sprintf "get_source_view: invalid page %d"
w.notebook#current_page)
|
e955c381668e2df18e4cfd1f248d58afacc234774d39e4732929eb1782124555 | davazp/cl-icalendar | types-utc-offset.lisp | ;; types-utc-offset.lisp ---
;;
Copyrigth ( C ) 2009 , 2010 < marioxcc >
Copyrigth ( C ) 2009 , 2010
;;
This file is part of cl - icalendar .
;;
;; cl-icalendar 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.
;;
;; cl-icalendar 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 cl-icalendar. If not, see </>.
(in-package :cl-icalendar)
(deftype utc-offset ()
'integer)
(register-ical-value utc-offset)
(defun utc-offset-hour (utc-offset)
(values (truncate (abs utc-offset) 3600)))
(defun utc-offset-minute (utc-offset)
(values (truncate (mod (abs utc-offset) 3600) 60)))
(defun utc-offset-second (utc-offset)
(mod (abs utc-offset) 60))
(defun utc-offset-negative-p (utc-offset)
(minusp utc-offset))
(defmethod format-value (x (type (eql 'utc-offset)) &optional params)
(declare (ignore params))
(declare (type (integer -43200 43200) x))
(format nil "~:[+~;-~]~2,'0d~2,'0d~@[~2,'0d~]"
(utc-offset-negative-p x)
(utc-offset-hour x)
(utc-offset-minute x)
(let ((seconds (utc-offset-second x)))
(if (zerop seconds) nil seconds))))
(defmethod parse-value (string (type (eql 'utc-offset)) &optional params)
(declare (ignore params))
(let* ((sign (elt string 0))
(hour (parse-unsigned-integer string :start 1 :end 3))
(minute (parse-unsigned-integer string :start 3 :end 5))
(second (ecase (length string)
(5 0)
(7 (parse-unsigned-integer string :start 5 :end 7)))))
(let ((value (+ (* 3600 hour) (* 60 minute) second)))
(check-ical-type hour (integer 0 12))
(check-ical-type minute (integer 0 59))
(check-ical-type second (integer 0 59))
(cond
((char= sign #\+))
((char= sign #\-)
(when (zerop value)
(%parse-error "The value -0000 or -000000 are not valid utc-offsets."))
(setf value (- value)))
(t (%parse-error "Bad sign.")))
value)))
;;; types-utc-offset.lisp ends here
| null | https://raw.githubusercontent.com/davazp/cl-icalendar/b5295ac245f5d333fa593352039ca4fd6a52a058/types-utc-offset.lisp | lisp | types-utc-offset.lisp ---
cl-icalendar is free software: you can redistribute it and/or modify
(at your option) any later version.
cl-icalendar is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with cl-icalendar. If not, see </>.
types-utc-offset.lisp ends here | Copyrigth ( C ) 2009 , 2010 < marioxcc >
Copyrigth ( C ) 2009 , 2010
This file is part of cl - icalendar .
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(in-package :cl-icalendar)
(deftype utc-offset ()
'integer)
(register-ical-value utc-offset)
(defun utc-offset-hour (utc-offset)
(values (truncate (abs utc-offset) 3600)))
(defun utc-offset-minute (utc-offset)
(values (truncate (mod (abs utc-offset) 3600) 60)))
(defun utc-offset-second (utc-offset)
(mod (abs utc-offset) 60))
(defun utc-offset-negative-p (utc-offset)
(minusp utc-offset))
(defmethod format-value (x (type (eql 'utc-offset)) &optional params)
(declare (ignore params))
(declare (type (integer -43200 43200) x))
(format nil "~:[+~;-~]~2,'0d~2,'0d~@[~2,'0d~]"
(utc-offset-negative-p x)
(utc-offset-hour x)
(utc-offset-minute x)
(let ((seconds (utc-offset-second x)))
(if (zerop seconds) nil seconds))))
(defmethod parse-value (string (type (eql 'utc-offset)) &optional params)
(declare (ignore params))
(let* ((sign (elt string 0))
(hour (parse-unsigned-integer string :start 1 :end 3))
(minute (parse-unsigned-integer string :start 3 :end 5))
(second (ecase (length string)
(5 0)
(7 (parse-unsigned-integer string :start 5 :end 7)))))
(let ((value (+ (* 3600 hour) (* 60 minute) second)))
(check-ical-type hour (integer 0 12))
(check-ical-type minute (integer 0 59))
(check-ical-type second (integer 0 59))
(cond
((char= sign #\+))
((char= sign #\-)
(when (zerop value)
(%parse-error "The value -0000 or -000000 are not valid utc-offsets."))
(setf value (- value)))
(t (%parse-error "Bad sign.")))
value)))
|
d0689a9ec8725bdc004a3f4ba4e3fa564222afaba3bdb74dd839e717f9ba7ffb | basho/yokozuna | yz_fallback.erl | %% @doc Verify that fallback data is handled properly. I.e. not indexed.
-module(yz_fallback).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
-define(NUM_KEYS, 1000).
-define(INDEX, <<"fallback">>).
-define(BUCKET, {?INDEX, <<"bucket">>}).
-define(KEY, <<"key">>).
-define(FMT(S, Args), lists:flatten(io_lib:format(S, Args))).
-define(CFG,
[{riak_core,
[
{ring_creation_size, 16}
]},
{yokozuna,
[
{enabled, true}
]}
]).
confirm() ->
Cluster = rt:build_cluster(2, ?CFG),
rt:wait_for_cluster_service(Cluster, yokozuna),
create_index(Cluster, ?INDEX),
Cluster2 = take_node_down(Cluster),
write_obj(Cluster2, ?INDEX, ?BUCKET, ?KEY),
check_fallbacks(Cluster2, ?INDEX, ?BUCKET, ?KEY),
ANode = yz_rt:select_random(Cluster2),
?assertEqual(ok, yz_rt:search_expect(ANode, ?INDEX, "*", "*", 1)),
pass.
check_fallbacks(Cluster, Index, Bucket, Key) ->
Node = yz_rt:select_random(Cluster),
KVPreflist = kv_preflist(Node, Bucket, Key),
FallbackPreflist = filter_fallbacks(KVPreflist),
LogicalFallbackPL = make_logical(Node, FallbackPreflist),
[?assertEqual(ok, yz_rt:search_expect(FNode, solr, Index, "_yz_pn",
integer_to_list(LPN), 0))
|| {LPN, FNode} <- LogicalFallbackPL].
create_index(Cluster, Index) ->
yz_rt:create_index(Cluster, Index),
ok = yz_rt:set_bucket_type_index(Cluster, Index),
timer:sleep(5000).
make_logical(Node, Preflist) ->
rpc:call(Node, yz_misc, convert_preflist, [Preflist, logical]).
filter_fallbacks(Preflist) ->
[PartitionNode || {{_,_} = PartitionNode, fallback} <- Preflist].
kv_preflist(Node, Bucket, Key) ->
{ok, Ring} = rpc:call(Node, riak_core_ring_manager, get_my_ring, []),
BucketProps = rpc:call(Node, riak_core_bucket, get_bucket, [Bucket, Ring]),
DocIdx = rpc:call(Node, riak_core_util, chash_key, [{Bucket,Key}]),
N = proplists:get_value(n_val,BucketProps),
UpNodes = rpc:call(Node, riak_core_node_watcher, nodes, [riak_kv]),
riak_core_apl:get_apl_ann(DocIdx, N, Ring, UpNodes).
take_node_down(Cluster) ->
DownNode = yz_rt:select_random(Cluster),
rt:stop(DownNode),
timer:sleep(5000),
Cluster -- [DownNode].
write_obj(Cluster, Index, {BType, BName}, Key) ->
Node = yz_rt:select_random(Cluster),
{Host, Port} = riak_hp(Node, Cluster),
lager:info("write obj to node ~p", [Node]),
URL = ?FMT("http://~s:~s/types/~s/buckets/~s/keys/~s",
[Host, integer_to_list(Port), BType, BName, Key]),
Headers = [{"content-type", "text/plain"}],
Body = <<"yokozuna">>,
{ok, "204", _, _} = ibrowse:send_req(URL, Headers, put, Body, []),
yz_rt:commit(Cluster, Index).
riak_hp(Node, Cluster) ->
CI = yz_rt:connection_info(Cluster),
yz_rt:riak_http(proplists:get_value(Node, CI)).
| null | https://raw.githubusercontent.com/basho/yokozuna/e15fe64f9ef9318c0cc21754f3dfdd073d2dc77d/riak_test/yz_fallback.erl | erlang | @doc Verify that fallback data is handled properly. I.e. not indexed. | -module(yz_fallback).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
-define(NUM_KEYS, 1000).
-define(INDEX, <<"fallback">>).
-define(BUCKET, {?INDEX, <<"bucket">>}).
-define(KEY, <<"key">>).
-define(FMT(S, Args), lists:flatten(io_lib:format(S, Args))).
-define(CFG,
[{riak_core,
[
{ring_creation_size, 16}
]},
{yokozuna,
[
{enabled, true}
]}
]).
confirm() ->
Cluster = rt:build_cluster(2, ?CFG),
rt:wait_for_cluster_service(Cluster, yokozuna),
create_index(Cluster, ?INDEX),
Cluster2 = take_node_down(Cluster),
write_obj(Cluster2, ?INDEX, ?BUCKET, ?KEY),
check_fallbacks(Cluster2, ?INDEX, ?BUCKET, ?KEY),
ANode = yz_rt:select_random(Cluster2),
?assertEqual(ok, yz_rt:search_expect(ANode, ?INDEX, "*", "*", 1)),
pass.
check_fallbacks(Cluster, Index, Bucket, Key) ->
Node = yz_rt:select_random(Cluster),
KVPreflist = kv_preflist(Node, Bucket, Key),
FallbackPreflist = filter_fallbacks(KVPreflist),
LogicalFallbackPL = make_logical(Node, FallbackPreflist),
[?assertEqual(ok, yz_rt:search_expect(FNode, solr, Index, "_yz_pn",
integer_to_list(LPN), 0))
|| {LPN, FNode} <- LogicalFallbackPL].
create_index(Cluster, Index) ->
yz_rt:create_index(Cluster, Index),
ok = yz_rt:set_bucket_type_index(Cluster, Index),
timer:sleep(5000).
make_logical(Node, Preflist) ->
rpc:call(Node, yz_misc, convert_preflist, [Preflist, logical]).
filter_fallbacks(Preflist) ->
[PartitionNode || {{_,_} = PartitionNode, fallback} <- Preflist].
kv_preflist(Node, Bucket, Key) ->
{ok, Ring} = rpc:call(Node, riak_core_ring_manager, get_my_ring, []),
BucketProps = rpc:call(Node, riak_core_bucket, get_bucket, [Bucket, Ring]),
DocIdx = rpc:call(Node, riak_core_util, chash_key, [{Bucket,Key}]),
N = proplists:get_value(n_val,BucketProps),
UpNodes = rpc:call(Node, riak_core_node_watcher, nodes, [riak_kv]),
riak_core_apl:get_apl_ann(DocIdx, N, Ring, UpNodes).
take_node_down(Cluster) ->
DownNode = yz_rt:select_random(Cluster),
rt:stop(DownNode),
timer:sleep(5000),
Cluster -- [DownNode].
write_obj(Cluster, Index, {BType, BName}, Key) ->
Node = yz_rt:select_random(Cluster),
{Host, Port} = riak_hp(Node, Cluster),
lager:info("write obj to node ~p", [Node]),
URL = ?FMT("http://~s:~s/types/~s/buckets/~s/keys/~s",
[Host, integer_to_list(Port), BType, BName, Key]),
Headers = [{"content-type", "text/plain"}],
Body = <<"yokozuna">>,
{ok, "204", _, _} = ibrowse:send_req(URL, Headers, put, Body, []),
yz_rt:commit(Cluster, Index).
riak_hp(Node, Cluster) ->
CI = yz_rt:connection_info(Cluster),
yz_rt:riak_http(proplists:get_value(Node, CI)).
|
9e652b1405d532559037eb2f2d8382b69902781bc0a557541c114aeb926d492c | shonfeder/nomad | git_cmd.ml | open Bos
let bin = Cmd.v "git"
let init () = Cmd_util.run Cmd.(bin % "init")
let add files = Cmd_util.run Cmd.(bin % "add" %% of_list files)
let changed_files () =
Cmd.(bin % "diff" % "--name-only" % "HEAD")
|> OS.Cmd.(run_out ~err:err_run_out)
|> OS.Cmd.to_lines ~trim:true
let commit msg = Cmd_util.run Cmd.(bin % "commit" % "-m" % msg)
| null | https://raw.githubusercontent.com/shonfeder/nomad/40c00e1792b3d45c0aa51ecec46abbc15410dd1c/lib/git_cmd.ml | ocaml | open Bos
let bin = Cmd.v "git"
let init () = Cmd_util.run Cmd.(bin % "init")
let add files = Cmd_util.run Cmd.(bin % "add" %% of_list files)
let changed_files () =
Cmd.(bin % "diff" % "--name-only" % "HEAD")
|> OS.Cmd.(run_out ~err:err_run_out)
|> OS.Cmd.to_lines ~trim:true
let commit msg = Cmd_util.run Cmd.(bin % "commit" % "-m" % msg)
|
|
55ce203232d4c0be077fededac086d73ada4ef69729fb44a53ae8292a1fba0ec | DataHaskell/dh-core | Html.hs | -- | Functions for working with HTML.
module Analyze.Html where
import Analyze.RFrame (RFrame (..))
import Control.Monad (forM_)
import qualified Lucid as L
-- | Renders an 'RFrame' to an HTML table.
renderHtml :: (L.ToHtml k, L.ToHtml v, Monad m)
=> RFrame k v -> L.HtmlT m ()
renderHtml (RFrame ks _ vs) =
L.table_ $ do
L.thead_ $
L.tr_ $ forM_ ks (L.th_ . L.toHtml)
L.tbody_ $ forM_ vs $ \v -> L.tr_ (forM_ v (L.td_ . L.toHtml))
| null | https://raw.githubusercontent.com/DataHaskell/dh-core/2beb8740f27fa9683db70eb8d8424ee6c75d3e91/analyze/src/Analyze/Html.hs | haskell | | Functions for working with HTML.
| Renders an 'RFrame' to an HTML table. | module Analyze.Html where
import Analyze.RFrame (RFrame (..))
import Control.Monad (forM_)
import qualified Lucid as L
renderHtml :: (L.ToHtml k, L.ToHtml v, Monad m)
=> RFrame k v -> L.HtmlT m ()
renderHtml (RFrame ks _ vs) =
L.table_ $ do
L.thead_ $
L.tr_ $ forM_ ks (L.th_ . L.toHtml)
L.tbody_ $ forM_ vs $ \v -> L.tr_ (forM_ v (L.td_ . L.toHtml))
|
6332c0e488794aa3f896bcce3f51656820cded07cb1e844a0478b482a9298f41 | avalor/eJason | scanner.erl | -module(scanner).
-compile(export_all).
-include("include/macros.hrl").
getTokens(File)->
{ok, RawTokens} =
case file:path_open(code:get_path(),File,[read]) of
{ok, F, _Path} ->
scan(F);
{error, enoent} ->
io:format("File: ~s cannot be found.~n",[File]),
exit(asl_file_not_found)
end,
%% io:format("RAW TOKENS: ~p~n",[lists:flatten(RawTokens)]),
{ok, lex(lists:flatten(RawTokens))}.
scan(Inport) ->
scan(Inport, '', 1).
scan(Inport, Prompt, Line1) ->
case catch io:scan_erl_form(Inport, Prompt, Line1) of
{eof, Line2} ->
{eof, Line2};
{ok, Tokens, Line2} ->
%%io:format("RAW TOKENS: ~p~n",[Tokens]),
case Tokens of
[] ->
scan(Inport, Prompt, Line2);
_ ->
%%Toks = lex(Tokens),
ResultScan = scan(Inport,Prompt,Line2),
%%io:format("Result Scan: ~p~n",[ResultScan]),
{Stat,Scan} = ResultScan,
case Stat of
ok ->
{ok,[[Tokens]|[Scan]]};
eof ->
{ok,Tokens};
_ ->
{Stat,Scan}
end
end;
{error, Descriptor, Line2} ->
{error, Descriptor, Line2};
{'EXIT', Why} ->
io:format('yeccscan: Error scanning input line ~w~n', [Line1]),
exit(Why)
end.
lex([]) ->
[];
lex([Token | Tokens]) ->
% io:format("Token: ~p~n",[Token]),
case Token of
{'fun',Line} ->
[{atom,Line,'fun'}|lex(Tokens)];
{'-',Line}->
case Tokens of
%% [{integer,Line2,Int}|MoreTokens] ->
%% %% -Int -> + (-1*Int)
%% [{'+',Line2},{'(',Line2},{number,Line2,-1},{'*',Line2},
{ number , Line2 , Int } , { ' ) ' , ) ] ;
%% [{float,Line2,Float}|MoreTokens] ->
% % -Float - > + ( )
%% [{'+',Line2},{'(',Line2},{number,Line2,-1},{'*',Line2},
{ number , Line2 , Float } , { ' ) ' , ) ] ;
[ { var , Line2,Var}|MoreTokens ] - >
%% %% -Var -> + (-1*Var)
%% [{'+',Line2},{'(',Line2},{number,Line2,-1},{'*',Line2},
{ var , Line2 , Var } , { ' ) ' , ) ] ;
[{integer,_Line2,Int}|MoreTokens] ->
[{neg_number, Line, -Int}|lex(MoreTokens)];
[{float,_Line2,Float}|MoreTokens] ->
[{neg_number, Line, -Float}|lex(MoreTokens)];
[ { var , Line2,Var}|MoreTokens ] - >
[ Token , { arith_var , Line2 , Var}|lex(MoreTokens ) ] ;
[{'+',_Line2}|MoreTokens] ->
[{'-+', Line}|lex(MoreTokens)];
_ ->
[{'-', Line} | lex(Tokens)]
end;
{'--',Line}->
lex([{'-',Line},{'-',Line}|Tokens]);
{':', Line} ->
case Tokens of
[{'-',_Line2}|MoreTokens] ->
[{':-', Line}|lex(MoreTokens)];
_ ->
[{':', Line} | lex(Tokens)]
end;
{'!', Line} ->
case Tokens of
[{'!',_Line2}|MoreTokens] ->
[{'!!', Line}|lex(MoreTokens)];
_ ->
[{'!', Line} | lex(Tokens)]
end;
{'?', Line} ->
case Tokens of
[{'?',_Line2}|MoreTokens] ->
[{'??', Line}|lex(MoreTokens)];
_ ->
[{'?', Line} | lex(Tokens)]
end;
{'{', Line} ->
case Tokens of
[{'{',_Line2}|MoreTokens] ->
[{'{{', Line}|lex(MoreTokens)];
_ ->
[{'{', Line} | lex(Tokens)]
end;
{'}', Line} ->
case Tokens of
[{'}',_Line2}|MoreTokens] ->
[{'}}', Line}|lex(MoreTokens)];
_ ->
[{'}', Line} | lex(Tokens)]
end;
{'\\', Line} ->
case Tokens of
[{'==',_Line2}|MoreTokens] ->
[{'\\==', Line}|lex(MoreTokens)];
_ ->
[{'\\', Line} | lex(Tokens)]
end;
{'/',Line}->
case Tokens of
[{'/',_Line}|MoreTokens]->
lex(skipLine(Line,MoreTokens));
[{'*',_Line}|MoreTokens]->
lex(skipSome(MoreTokens));
_ ->
[{'/',Line}|lex(Tokens)]
end;
{'*', Line} ->
case Tokens of
[{'*',_Line2}|MoreTokens] ->
[{'**', Line}|lex(MoreTokens)];
[ {'-',_Line1},{integer,_Line2,Int}|MoreTokens]->
[{'*', Line},{number,_Line2,-Int}|lex(MoreTokens)];
[ {'-',_Line1},{float,_Line2,Float}|MoreTokens]->
[{'*', Line},{number,_Line2,-Float}|lex(MoreTokens)];
_ ->
[{'*', Line} | lex(Tokens)]
end;
{'=', Line} ->
case Tokens of
[{'..',_Line2}|MoreTokens] ->
[{'=..', Line}|lex(MoreTokens)];
[{string,SomeLine,String}|MoreTokens]->
[{'=', Line},{rel_string,SomeLine,String}|
lex(MoreTokens)];
_ ->
[{'=', Line} | lex(Tokens)]
end;
{var, Line, VarName}->
NewVarName =
case VarName of
'_' ->
?UNDERSCORE;
_ ->
list_to_atom(lists:flatten("Ejason_"++
atom_to_list(VarName)))
end,
% io:format("NewVarName: ~p~n",[NewVarName]),
case Tokens of
[{'[',_OtherLine}|_] ->
[{var_label,Line,NewVarName}|
lex(Tokens)];
_ ->
[{var,Line,NewVarName}|
lex(Tokens)]
end;
%% {atom, Line, true} ->
%% [{true,Line}| lex(Tokens)];
%% {atom, Line, false} ->
%% [{false,Line}| lex(Tokens)];
{atom, Line, mod} ->
[{mod,Line}| lex(Tokens)];
{reserved_word, Line, 'div'}->
[{reserved_word_div,Line}| lex(Tokens)];
{integer, Line, Int}->
[{number,Line, Int}| lex(Tokens)];
{float, Line, Float}->
[{number,Line,Float}| lex(Tokens)];
{Category, Line, Symbol} ->
[{Category, Line, Symbol} | lex(Tokens)];
{Other, Line} ->
%% Cat = case erl_scan:reserved_word(Other) of
%% true -> reserved_word;
%% false -> reserved_symbol
%% end,
[{Other, Line} | lex(Tokens)]
end.
%% Line skipped due to comments symbol
skipLine(Line,[_Skipped = {_,Line}|MoreTokens]) ->
%% io:format("Skipping: ~p~n",[Skipped]),
skipLine(Line,MoreTokens);
skipLine(Line,[_Skipped = {_,Line,_}|MoreTokens]) ->
%% io:format("Skipping: {~p, ~n",[Skipped]),
skipLine(Line,MoreTokens);
skipLine(_Line,MoreTokens) ->
%% io:format("Stopped skipping at: ~p~n",[MoreTokens]),
MoreTokens.
%% Skipping several elements between symbos '/*' '*/'
skipSome([])->
[];
skipSome([{'*',Line},{'/',Line}|MoreTokens])->
MoreTokens;
skipSome([_Token|MoreTokens]) ->
io : format("More : ~p ~ n",[MoreTokens ] ) ,
skipSome(MoreTokens).
| null | https://raw.githubusercontent.com/avalor/eJason/3e5092d42de0a3df5c5e5ec42cb552a2f282bbb1/src/scanner.erl | erlang | io:format("RAW TOKENS: ~p~n",[lists:flatten(RawTokens)]),
io:format("RAW TOKENS: ~p~n",[Tokens]),
Toks = lex(Tokens),
io:format("Result Scan: ~p~n",[ResultScan]),
io:format("Token: ~p~n",[Token]),
[{integer,Line2,Int}|MoreTokens] ->
%% -Int -> + (-1*Int)
[{'+',Line2},{'(',Line2},{number,Line2,-1},{'*',Line2},
[{float,Line2,Float}|MoreTokens] ->
% -Float - > + ( )
[{'+',Line2},{'(',Line2},{number,Line2,-1},{'*',Line2},
%% -Var -> + (-1*Var)
[{'+',Line2},{'(',Line2},{number,Line2,-1},{'*',Line2},
io:format("NewVarName: ~p~n",[NewVarName]),
{atom, Line, true} ->
[{true,Line}| lex(Tokens)];
{atom, Line, false} ->
[{false,Line}| lex(Tokens)];
Cat = case erl_scan:reserved_word(Other) of
true -> reserved_word;
false -> reserved_symbol
end,
Line skipped due to comments symbol
io:format("Skipping: ~p~n",[Skipped]),
io:format("Skipping: {~p, ~n",[Skipped]),
io:format("Stopped skipping at: ~p~n",[MoreTokens]),
Skipping several elements between symbos '/*' '*/' | -module(scanner).
-compile(export_all).
-include("include/macros.hrl").
getTokens(File)->
{ok, RawTokens} =
case file:path_open(code:get_path(),File,[read]) of
{ok, F, _Path} ->
scan(F);
{error, enoent} ->
io:format("File: ~s cannot be found.~n",[File]),
exit(asl_file_not_found)
end,
{ok, lex(lists:flatten(RawTokens))}.
scan(Inport) ->
scan(Inport, '', 1).
scan(Inport, Prompt, Line1) ->
case catch io:scan_erl_form(Inport, Prompt, Line1) of
{eof, Line2} ->
{eof, Line2};
{ok, Tokens, Line2} ->
case Tokens of
[] ->
scan(Inport, Prompt, Line2);
_ ->
ResultScan = scan(Inport,Prompt,Line2),
{Stat,Scan} = ResultScan,
case Stat of
ok ->
{ok,[[Tokens]|[Scan]]};
eof ->
{ok,Tokens};
_ ->
{Stat,Scan}
end
end;
{error, Descriptor, Line2} ->
{error, Descriptor, Line2};
{'EXIT', Why} ->
io:format('yeccscan: Error scanning input line ~w~n', [Line1]),
exit(Why)
end.
lex([]) ->
[];
lex([Token | Tokens]) ->
case Token of
{'fun',Line} ->
[{atom,Line,'fun'}|lex(Tokens)];
{'-',Line}->
case Tokens of
{ number , Line2 , Int } , { ' ) ' , ) ] ;
{ number , Line2 , Float } , { ' ) ' , ) ] ;
[ { var , Line2,Var}|MoreTokens ] - >
{ var , Line2 , Var } , { ' ) ' , ) ] ;
[{integer,_Line2,Int}|MoreTokens] ->
[{neg_number, Line, -Int}|lex(MoreTokens)];
[{float,_Line2,Float}|MoreTokens] ->
[{neg_number, Line, -Float}|lex(MoreTokens)];
[ { var , Line2,Var}|MoreTokens ] - >
[ Token , { arith_var , Line2 , Var}|lex(MoreTokens ) ] ;
[{'+',_Line2}|MoreTokens] ->
[{'-+', Line}|lex(MoreTokens)];
_ ->
[{'-', Line} | lex(Tokens)]
end;
{'--',Line}->
lex([{'-',Line},{'-',Line}|Tokens]);
{':', Line} ->
case Tokens of
[{'-',_Line2}|MoreTokens] ->
[{':-', Line}|lex(MoreTokens)];
_ ->
[{':', Line} | lex(Tokens)]
end;
{'!', Line} ->
case Tokens of
[{'!',_Line2}|MoreTokens] ->
[{'!!', Line}|lex(MoreTokens)];
_ ->
[{'!', Line} | lex(Tokens)]
end;
{'?', Line} ->
case Tokens of
[{'?',_Line2}|MoreTokens] ->
[{'??', Line}|lex(MoreTokens)];
_ ->
[{'?', Line} | lex(Tokens)]
end;
{'{', Line} ->
case Tokens of
[{'{',_Line2}|MoreTokens] ->
[{'{{', Line}|lex(MoreTokens)];
_ ->
[{'{', Line} | lex(Tokens)]
end;
{'}', Line} ->
case Tokens of
[{'}',_Line2}|MoreTokens] ->
[{'}}', Line}|lex(MoreTokens)];
_ ->
[{'}', Line} | lex(Tokens)]
end;
{'\\', Line} ->
case Tokens of
[{'==',_Line2}|MoreTokens] ->
[{'\\==', Line}|lex(MoreTokens)];
_ ->
[{'\\', Line} | lex(Tokens)]
end;
{'/',Line}->
case Tokens of
[{'/',_Line}|MoreTokens]->
lex(skipLine(Line,MoreTokens));
[{'*',_Line}|MoreTokens]->
lex(skipSome(MoreTokens));
_ ->
[{'/',Line}|lex(Tokens)]
end;
{'*', Line} ->
case Tokens of
[{'*',_Line2}|MoreTokens] ->
[{'**', Line}|lex(MoreTokens)];
[ {'-',_Line1},{integer,_Line2,Int}|MoreTokens]->
[{'*', Line},{number,_Line2,-Int}|lex(MoreTokens)];
[ {'-',_Line1},{float,_Line2,Float}|MoreTokens]->
[{'*', Line},{number,_Line2,-Float}|lex(MoreTokens)];
_ ->
[{'*', Line} | lex(Tokens)]
end;
{'=', Line} ->
case Tokens of
[{'..',_Line2}|MoreTokens] ->
[{'=..', Line}|lex(MoreTokens)];
[{string,SomeLine,String}|MoreTokens]->
[{'=', Line},{rel_string,SomeLine,String}|
lex(MoreTokens)];
_ ->
[{'=', Line} | lex(Tokens)]
end;
{var, Line, VarName}->
NewVarName =
case VarName of
'_' ->
?UNDERSCORE;
_ ->
list_to_atom(lists:flatten("Ejason_"++
atom_to_list(VarName)))
end,
case Tokens of
[{'[',_OtherLine}|_] ->
[{var_label,Line,NewVarName}|
lex(Tokens)];
_ ->
[{var,Line,NewVarName}|
lex(Tokens)]
end;
{atom, Line, mod} ->
[{mod,Line}| lex(Tokens)];
{reserved_word, Line, 'div'}->
[{reserved_word_div,Line}| lex(Tokens)];
{integer, Line, Int}->
[{number,Line, Int}| lex(Tokens)];
{float, Line, Float}->
[{number,Line,Float}| lex(Tokens)];
{Category, Line, Symbol} ->
[{Category, Line, Symbol} | lex(Tokens)];
{Other, Line} ->
[{Other, Line} | lex(Tokens)]
end.
skipLine(Line,[_Skipped = {_,Line}|MoreTokens]) ->
skipLine(Line,MoreTokens);
skipLine(Line,[_Skipped = {_,Line,_}|MoreTokens]) ->
skipLine(Line,MoreTokens);
skipLine(_Line,MoreTokens) ->
MoreTokens.
skipSome([])->
[];
skipSome([{'*',Line},{'/',Line}|MoreTokens])->
MoreTokens;
skipSome([_Token|MoreTokens]) ->
io : format("More : ~p ~ n",[MoreTokens ] ) ,
skipSome(MoreTokens).
|
3bb3e6580ac51cacd086332dabbd04e15df61e0f410bd3966d5f3a631ef33585 | canonical/jepsen.dqlite | append.clj | (ns jepsen.dqlite.append
"Test for transactional list append."
(:require [clojure [string :as str]]
[jepsen [client :as client]]
[jepsen.tests.cycle.append :as append]
[jepsen.dqlite [client :as c]]))
(defrecord Client [conn]
client/Client
(open! [this test node]
(assoc this :conn (c/open test node)))
(close! [this test])
(setup! [this test])
(teardown! [_ test])
(invoke! [_ test op]
(c/with-errors op
(let [body (str (:value op))
value (c/request conn "POST" "/append" {:body body})]
(assoc op :type :ok, :value value))))
client/Reusable
(reusable? [client test]))
(defn workload
"A list append workload."
[opts]
(assoc (append/test {:key-count 10
:max-txn-length 2
:consistency-models [:serializable
:strict-serializable]})
:client (Client. nil)))
| null | https://raw.githubusercontent.com/canonical/jepsen.dqlite/be21c914b13d5a86e845856cda9357fc326006cb/src/jepsen/dqlite/append.clj | clojure | (ns jepsen.dqlite.append
"Test for transactional list append."
(:require [clojure [string :as str]]
[jepsen [client :as client]]
[jepsen.tests.cycle.append :as append]
[jepsen.dqlite [client :as c]]))
(defrecord Client [conn]
client/Client
(open! [this test node]
(assoc this :conn (c/open test node)))
(close! [this test])
(setup! [this test])
(teardown! [_ test])
(invoke! [_ test op]
(c/with-errors op
(let [body (str (:value op))
value (c/request conn "POST" "/append" {:body body})]
(assoc op :type :ok, :value value))))
client/Reusable
(reusable? [client test]))
(defn workload
"A list append workload."
[opts]
(assoc (append/test {:key-count 10
:max-txn-length 2
:consistency-models [:serializable
:strict-serializable]})
:client (Client. nil)))
|
|
d9cc033be87aaae23e319d92fb30ae2767d89000ba25eb08e5d12a1dbf15ba24 | dvcrn/proton | keymap.cljs | (ns proton.lib.keymap
#_(:require [proton.core]
[proton.lib.mode])
(:require [proton.lib.atom :as atom-env :refer [workspace commands views eval-action! eval-actions!]]
[proton.lib.helpers :as helpers :refer [deep-merge]]))
(defonce atom-keymap (atom {}))
(defonce proton-keymap (atom {}))
(defonce mode-keymap (atom {}))
(def get-current-editor-mode #(proton.lib.mode.get-current-editor-mode))
(defn get-mode-info [mode-name] (proton.lib.mode.get-mode mode-name))
(defn set-proton-keys-for-mode
"Define multiple key bindings associated with mode."
[mode-name keybindings-map]
(swap! mode-keymap helpers/deep-merge (assoc {} mode-name keybindings-map)))
(defn set-proton-leader-keys
"Define multiple key bindings with associated action for `proton-keymap`."
[keybindings-map]
(swap! proton-keymap helpers/deep-merge keybindings-map))
(defn- is-exec? [hash]
(let [{:keys [action target fx title]} hash]
(or action target fx title)))
(defn cleanup! []
(reset! atom-keymap {})
(reset! proton-keymap {})
(reset! mode-keymap {}))
(defn get-mode-keybindings [mode-name]
(when-not (nil? mode-name)
(if-let [mode-info (get-mode-info mode-name)]
(let [mode-map (or (get @mode-keymap (keyword mode-name)) {})
child-modes (mode-info :child)]
(if-not (nil? child-modes)
(helpers/deep-merge (reduce #(helpers/deep-merge %1 (get-mode-keybindings %2)) {} child-modes) mode-map)
mode-map)))))
(defn find-keybindings [ks]
(let [current-mode (get-current-editor-mode)
mode-prefix-key (keyword (first proton.core.mode-keys))
mode-keymap {mode-prefix-key (conj (get @proton-keymap mode-prefix-key) (get-mode-keybindings current-mode))}
keymap (merge @proton-keymap mode-keymap)]
(get-in keymap ks)))
(defn exec-binding [keymap-item]
;; if it is a vector, it means we are dealing with a multi keybinding
(if (vector? keymap-item)
(eval-actions! keymap-item)
(eval-action! keymap-item)))
(defn is-action? [{:keys [fx action]}]
(not (nil? (or fx action))))
(defn unset-keymap-for-mode! [mode-name]
(swap! mode-keymap dissoc mode-name))
| null | https://raw.githubusercontent.com/dvcrn/proton/427d83ffdb61d84a04e3d30032b792a9cfbfc53f/src/cljs/proton/lib/keymap.cljs | clojure | if it is a vector, it means we are dealing with a multi keybinding | (ns proton.lib.keymap
#_(:require [proton.core]
[proton.lib.mode])
(:require [proton.lib.atom :as atom-env :refer [workspace commands views eval-action! eval-actions!]]
[proton.lib.helpers :as helpers :refer [deep-merge]]))
(defonce atom-keymap (atom {}))
(defonce proton-keymap (atom {}))
(defonce mode-keymap (atom {}))
(def get-current-editor-mode #(proton.lib.mode.get-current-editor-mode))
(defn get-mode-info [mode-name] (proton.lib.mode.get-mode mode-name))
(defn set-proton-keys-for-mode
"Define multiple key bindings associated with mode."
[mode-name keybindings-map]
(swap! mode-keymap helpers/deep-merge (assoc {} mode-name keybindings-map)))
(defn set-proton-leader-keys
"Define multiple key bindings with associated action for `proton-keymap`."
[keybindings-map]
(swap! proton-keymap helpers/deep-merge keybindings-map))
(defn- is-exec? [hash]
(let [{:keys [action target fx title]} hash]
(or action target fx title)))
(defn cleanup! []
(reset! atom-keymap {})
(reset! proton-keymap {})
(reset! mode-keymap {}))
(defn get-mode-keybindings [mode-name]
(when-not (nil? mode-name)
(if-let [mode-info (get-mode-info mode-name)]
(let [mode-map (or (get @mode-keymap (keyword mode-name)) {})
child-modes (mode-info :child)]
(if-not (nil? child-modes)
(helpers/deep-merge (reduce #(helpers/deep-merge %1 (get-mode-keybindings %2)) {} child-modes) mode-map)
mode-map)))))
(defn find-keybindings [ks]
(let [current-mode (get-current-editor-mode)
mode-prefix-key (keyword (first proton.core.mode-keys))
mode-keymap {mode-prefix-key (conj (get @proton-keymap mode-prefix-key) (get-mode-keybindings current-mode))}
keymap (merge @proton-keymap mode-keymap)]
(get-in keymap ks)))
(defn exec-binding [keymap-item]
(if (vector? keymap-item)
(eval-actions! keymap-item)
(eval-action! keymap-item)))
(defn is-action? [{:keys [fx action]}]
(not (nil? (or fx action))))
(defn unset-keymap-for-mode! [mode-name]
(swap! mode-keymap dissoc mode-name))
|
3385f768db064ab703259a1faf945b36c6b2ffa8c3bbe12235e1db0e2c2c0a14 | oklm-wsh/MrMime | parser.ml | let () = Printexc.record_backtrace true
module Input = RingBuffer.Committed
let locate buff off len f =
let idx = ref 0 in
while !idx < len && f (Internal_buffer.get buff (off + !idx))
do incr idx done;
!idx
module type S =
sig
type s =
| Complete
| Incomplete
val pp : Format.formatter -> s -> unit
type err = ..
type ('a, 'input) state =
| Read of { buffer : 'input Input.t; k : int -> s -> ('a, 'input) state }
| Done of 'a
| Fail of string list * err
type ('a, 'input) k = 'input Input.t -> s -> 'a
type ('a, 'input) fail = (string list -> err -> ('a, 'input) state, 'input) k
type ('a, 'r, 'input) success = ('a -> ('r, 'input) state, 'input) k
type 'a t =
{ f : 'r 'input. (('r, 'input) fail -> ('a, 'r, 'input) success -> ('r, 'input) state, 'input) k }
val return : 'a -> 'a t
val fail : err -> 'a t
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
val (>>|) : 'a t -> ('a -> 'b) -> 'b t
val (<|>) : 'a t -> 'a t -> 'a t
val (<$>) : ('a -> 'b) -> 'a t -> 'b t
val (<* ) : 'a t -> 'b t -> 'a t
val ( *>) : 'a t -> 'b t -> 'b t
val (<*>) : ('a -> 'b) t -> 'a t -> 'b t
val (<?>) : 'a t -> string -> 'a t
val fix : ('a t -> 'a t) -> 'a t
val lift : ('a -> 'b) -> 'a t -> 'b t
val lift2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t
val lift3 : ('a -> 'b -> 'c -> 'd) -> 'a t -> 'b t -> 'c t -> 'd t
val run : 'input Input.t -> 'a t -> ('a, 'input) state
val only : 'input Input.t -> 'a t -> ('a, 'input) state
end
type s =
| Complete
| Incomplete
let pp fmt = function
| Complete -> Format.pp_print_string fmt "Complete"
| Incomplete -> Format.pp_print_string fmt "Incomplete"
type err = ..
type ('a, 'input) state =
| Read of { buffer : 'input Input.t; k : int -> s -> ('a, 'input) state }
| Done of 'a
| Fail of string list * err
type ('a, 'input) k = 'input Input.t -> s -> 'a
type ('a, 'input) fail = (string list -> err -> ('a, 'input) state, 'input) k
type ('a, 'r, 'input) success = ('a -> ('r, 'input) state, 'input) k
type 'a t =
{ f : 'r 'input. (('r, 'input) fail -> ('a, 'r, 'input) success -> ('r, 'input) state, 'input) k }
let return v = { f = fun i s _ succ -> succ i s v }
let fail err = { f = fun i s fail _ -> fail i s [] err }
let (>>=) a f = { f = fun i s fail succ ->
let succ' i' s' v = (f v).f i' s' fail succ in
a.f i s fail succ' }
let (>>|) a f = { f = fun i s fail succ ->
let succ' i' s' v = succ i' s' (f v) in
a.f i s fail succ' }
let (<$>) f m = m >>| f
let lift f m = f <$> m
let (<|>) u v =
{ f = fun i s fail succ ->
let mark = Input.mark i in
let fail' i s _marks _err =
Input.unmark mark i; (* we rollback to old read position *)
v.f i s fail succ
in
let succ' i s e =
if Input.equal (Input.mark i) mark
then begin
Input.unmark mark i;
v.f i s fail succ
end else begin
Input.forget mark i; (* forget the mark, and may be switch to
ring-buffer *)
succ i s e
end
in
u.f i s fail' succ' }
let (<* ) a b =
{ f = fun i s fail succ ->
let succ' i' s' x =
let succ'' i'' s'' _ = succ i'' s'' x in
b.f i' s' fail succ'' in
a.f i s fail succ' }
let ( *>) a b =
{ f = fun i s fail succ ->
let succ' i' s' _ = b.f i' s' fail succ in
a.f i s fail succ' }
let (<*>) u v =
{ f = fun i s fail succ ->
let succ' i' s' f =
let succ'' i'' s'' m =
succ i'' s'' (f m)
in
v.f i' s' fail succ''
in
u.f i s fail succ' }
let (<?>) a mark =
{ f = fun i s fail succ ->
let fail' i' s' marks err =
fail i' s' (mark :: marks) err in
a.f i s fail' succ }
let lift2 f m1 m2 =
{ f = fun i s fail succ ->
let succ' i' s' m' =
let succ'' i'' s'' m'' = succ i'' s'' (f m' m'') in
m2.f i' s' fail succ''
in
m1.f i s fail succ' }
let lift3 f m1 m2 m3 =
{ f = fun i s fail succ ->
let succ' i' s' m' =
let succ'' i'' s'' m'' =
let succ''' i''' s''' m''' = succ i''' s''' (f m' m'' m''') in
m3.f i'' s'' fail succ'''
in
m2.f i' s' fail succ''
in
m1.f i s fail succ' }
let fix f =
let rec u = lazy (f r)
and r = { f = fun i s fail succ ->
Lazy.(force u).f i s fail succ }
in r
let run buffer a =
let fail' _buf _ marks err = Fail (marks, err) in
let succeed' _buf _ value = Done value in
a.f buffer Incomplete fail' succeed'
let only buffer a =
let fail' _buf _ marks err = Fail (marks, err) in
let succeed' _buf _ value = Done value in
a.f buffer Complete fail' succeed'
module type I =
sig
type err += End_of_flow
val prompt : 'input Input.t -> ('input Input.t -> s -> ('a, 'input) state) -> ('input Input.t -> s -> ('a, 'input) state) -> ('a, 'input) state
val expect : unit t
val require : int -> 'input Input.t -> s -> ('a, 'input) fail -> (unit, 'a, 'input) success -> ('a, 'input) state
val ensure : int -> bytes t
end
module type C =
sig
type err += Satisfy
type err += String
type err += Repeat
val peek_chr : char option t
val peek_chr_exn : char t
val advance : int -> unit t
val satisfy : (char -> bool) -> char t
val print : string -> unit t
val string : (string -> string) -> string -> bytes t
val store : Buffer.t -> (char -> bool) -> int t
val recognize : (char -> bool) -> string t
val char : char -> char t
val many : 'a t -> 'a list t
val one : 'a t -> 'a list t
val option : 'a -> 'a t -> 'a t
val take : int -> bytes t
val list : 'a t list -> 'a list t
val count : int -> 'a t -> 'a list t
val repeat' : Buffer.t -> int option -> int option -> (char -> bool) -> int t
val repeat : int option -> int option -> (char -> bool) -> string t
end
module IO : I =
struct
type err += End_of_flow
let rec prompt i fail succ =
let continue n s =
if n = 0 then
if s = Complete
then fail i Complete
else prompt i fail succ
else succ i s
in
Read { buffer = i; k = continue; }
let expect =
{ f = fun i s fail succ ->
match s with
| Complete -> fail i s [] End_of_flow
| Incomplete ->
let succ' i' s' = succ i' s' () in
let fail' i' s' = fail i' s' [] End_of_flow in
prompt i fail' succ' }
let require n i s fail succ =
let rec continue = { f = fun i' s' fail' succ' ->
if n < Input.ravailable i'
then succ' i' s' ()
else (expect >>= fun () -> continue).f i' s' fail' succ' }
in
(expect >>= fun () -> continue).f i s fail succ
let ensure n =
let sub n =
let f
: 'r 'input. (('r, 'input) fail -> ('a, 'r, 'input) success -> ('r, 'input) state, 'input) k
= fun i s _fail succ ->
let tmp = Internal_buffer.create_by ~proof:(Input.proof i) n in
Input.peek i tmp 0 n;
succ i s (Internal_buffer.sub_string tmp 0 (Internal_buffer.length tmp))
in
{ f }
in
{ f = fun i s fail succ ->
if Input.ravailable i >= n
then succ i s ()
else require n i s fail succ }
>>= fun () -> sub n
end
module Convenience : C =
struct
let peek_chr = { f = fun i s _fail succ ->
if Input.ravailable i > 0
then succ i s (Some (Input.get i))
else if s = Complete
then succ i s None
else
let succ' i' s' =
succ i' s' (Some (Input.get i')) in
let fail' i' s' =
succ i' s' None in
IO.prompt i fail' succ' }
let peek_chr_exn = { f = fun i s fail succ ->
if Input.ravailable i > 0
then succ i s (Input.get i)
else let succ' i' s' () =
succ i' s' (Input.get i') in
IO.require 1 i s fail succ' }
let advance n =
{ f = fun i s _fail succ -> Input.radvance i n; succ i s () }
type err += Satisfy
let satisfy f =
peek_chr_exn >>= fun chr ->
if f chr
then advance 1 >>| fun () -> chr
else fail Satisfy
type err += String
let print t =
{ f = fun i s _fail succ ->
Printf.printf "%s%!" t;
succ i s () }
let string f s =
let len = String.length s in
IO.ensure len >>= fun s' ->
if f s = f (Bytes.to_string s')
then advance len *> return s'
else fail String
let store buffer f =
{ f = fun i s _fail succ ->
let recognize buff off len =
let len' = locate buff off len f in
Buffer.add_bytes buffer (Internal_buffer.sub_string buff off len');
len'
in
let consumed = Input.transmit i recognize in
succ i s consumed }
let recognize f =
{ f = fun i s fail succ ->
let buffer = Buffer.create 16 in
let r = fix @@ fun m ->
peek_chr >>= function
| Some chr when f chr -> store buffer f >>= fun _ -> m
| Some _ | None -> return (Buffer.length buffer)
in
let succ' i s _consumed = succ i s (Buffer.contents buffer) in
r.f i s fail succ' }
let char chr =
satisfy ((=) chr) <?> (String.make 1 chr)
let many p =
fix (fun m -> (lift2 (fun x r -> x :: r) p m) <|> return [])
let one p =
lift2 (fun x r -> x :: r) p (many p)
let option x p =
p <|> return x
let take n =
let n = max n 0 in
IO.ensure n >>= fun str ->
advance n >>| fun () -> str
let rec list l =
match l with
| [] -> return []
| x :: r -> lift2 (fun x r -> x :: r) x (list r)
let count n p =
assert (n >= 0);
let rec loop = function
| 0 -> return []
| n -> lift2 (fun x r -> x :: r) p (loop (n - 1))
in
loop n
type err += Repeat
let repeat' buffer a b f =
let at_least n = match a with
| Some a -> n >= a
| None -> true
in
let is_most n = match b with
| Some b -> n = b
| None -> false
in
fix @@ fun m ->
peek_chr >>= function
| Some chr when f chr && not (is_most (Buffer.length buffer)) ->
{ f = fun i s _fail succ ->
let consumed = Input.transmit i
(fun buff off len ->
let len' = locate buff off len f in
let len' = match b with
| Some b when (Buffer.length buffer + len') > b ->
b - (Buffer.length buffer)
| _ -> len'
in
Buffer.add_bytes buffer (Internal_buffer.sub_string buff off len');
len') in
succ i s consumed } *> m
| _ ->
if at_least (Buffer.length buffer)
then return (Buffer.length buffer)
else fail Repeat
let repeat a b f =
{ f = fun i s fail succ ->
let buffer = Buffer.create 16 in
let succ' i s _n = succ i s (Buffer.contents buffer) in
(repeat' buffer a b f).f i s fail succ' }
end
| null | https://raw.githubusercontent.com/oklm-wsh/MrMime/4d2a9dc75905927a092c0424cff7462e2b26bb96/lib/parser.ml | ocaml | we rollback to old read position
forget the mark, and may be switch to
ring-buffer | let () = Printexc.record_backtrace true
module Input = RingBuffer.Committed
let locate buff off len f =
let idx = ref 0 in
while !idx < len && f (Internal_buffer.get buff (off + !idx))
do incr idx done;
!idx
module type S =
sig
type s =
| Complete
| Incomplete
val pp : Format.formatter -> s -> unit
type err = ..
type ('a, 'input) state =
| Read of { buffer : 'input Input.t; k : int -> s -> ('a, 'input) state }
| Done of 'a
| Fail of string list * err
type ('a, 'input) k = 'input Input.t -> s -> 'a
type ('a, 'input) fail = (string list -> err -> ('a, 'input) state, 'input) k
type ('a, 'r, 'input) success = ('a -> ('r, 'input) state, 'input) k
type 'a t =
{ f : 'r 'input. (('r, 'input) fail -> ('a, 'r, 'input) success -> ('r, 'input) state, 'input) k }
val return : 'a -> 'a t
val fail : err -> 'a t
val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
val (>>|) : 'a t -> ('a -> 'b) -> 'b t
val (<|>) : 'a t -> 'a t -> 'a t
val (<$>) : ('a -> 'b) -> 'a t -> 'b t
val (<* ) : 'a t -> 'b t -> 'a t
val ( *>) : 'a t -> 'b t -> 'b t
val (<*>) : ('a -> 'b) t -> 'a t -> 'b t
val (<?>) : 'a t -> string -> 'a t
val fix : ('a t -> 'a t) -> 'a t
val lift : ('a -> 'b) -> 'a t -> 'b t
val lift2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t
val lift3 : ('a -> 'b -> 'c -> 'd) -> 'a t -> 'b t -> 'c t -> 'd t
val run : 'input Input.t -> 'a t -> ('a, 'input) state
val only : 'input Input.t -> 'a t -> ('a, 'input) state
end
type s =
| Complete
| Incomplete
let pp fmt = function
| Complete -> Format.pp_print_string fmt "Complete"
| Incomplete -> Format.pp_print_string fmt "Incomplete"
type err = ..
type ('a, 'input) state =
| Read of { buffer : 'input Input.t; k : int -> s -> ('a, 'input) state }
| Done of 'a
| Fail of string list * err
type ('a, 'input) k = 'input Input.t -> s -> 'a
type ('a, 'input) fail = (string list -> err -> ('a, 'input) state, 'input) k
type ('a, 'r, 'input) success = ('a -> ('r, 'input) state, 'input) k
type 'a t =
{ f : 'r 'input. (('r, 'input) fail -> ('a, 'r, 'input) success -> ('r, 'input) state, 'input) k }
let return v = { f = fun i s _ succ -> succ i s v }
let fail err = { f = fun i s fail _ -> fail i s [] err }
let (>>=) a f = { f = fun i s fail succ ->
let succ' i' s' v = (f v).f i' s' fail succ in
a.f i s fail succ' }
let (>>|) a f = { f = fun i s fail succ ->
let succ' i' s' v = succ i' s' (f v) in
a.f i s fail succ' }
let (<$>) f m = m >>| f
let lift f m = f <$> m
let (<|>) u v =
{ f = fun i s fail succ ->
let mark = Input.mark i in
let fail' i s _marks _err =
v.f i s fail succ
in
let succ' i s e =
if Input.equal (Input.mark i) mark
then begin
Input.unmark mark i;
v.f i s fail succ
end else begin
succ i s e
end
in
u.f i s fail' succ' }
let (<* ) a b =
{ f = fun i s fail succ ->
let succ' i' s' x =
let succ'' i'' s'' _ = succ i'' s'' x in
b.f i' s' fail succ'' in
a.f i s fail succ' }
let ( *>) a b =
{ f = fun i s fail succ ->
let succ' i' s' _ = b.f i' s' fail succ in
a.f i s fail succ' }
let (<*>) u v =
{ f = fun i s fail succ ->
let succ' i' s' f =
let succ'' i'' s'' m =
succ i'' s'' (f m)
in
v.f i' s' fail succ''
in
u.f i s fail succ' }
let (<?>) a mark =
{ f = fun i s fail succ ->
let fail' i' s' marks err =
fail i' s' (mark :: marks) err in
a.f i s fail' succ }
let lift2 f m1 m2 =
{ f = fun i s fail succ ->
let succ' i' s' m' =
let succ'' i'' s'' m'' = succ i'' s'' (f m' m'') in
m2.f i' s' fail succ''
in
m1.f i s fail succ' }
let lift3 f m1 m2 m3 =
{ f = fun i s fail succ ->
let succ' i' s' m' =
let succ'' i'' s'' m'' =
let succ''' i''' s''' m''' = succ i''' s''' (f m' m'' m''') in
m3.f i'' s'' fail succ'''
in
m2.f i' s' fail succ''
in
m1.f i s fail succ' }
let fix f =
let rec u = lazy (f r)
and r = { f = fun i s fail succ ->
Lazy.(force u).f i s fail succ }
in r
let run buffer a =
let fail' _buf _ marks err = Fail (marks, err) in
let succeed' _buf _ value = Done value in
a.f buffer Incomplete fail' succeed'
let only buffer a =
let fail' _buf _ marks err = Fail (marks, err) in
let succeed' _buf _ value = Done value in
a.f buffer Complete fail' succeed'
module type I =
sig
type err += End_of_flow
val prompt : 'input Input.t -> ('input Input.t -> s -> ('a, 'input) state) -> ('input Input.t -> s -> ('a, 'input) state) -> ('a, 'input) state
val expect : unit t
val require : int -> 'input Input.t -> s -> ('a, 'input) fail -> (unit, 'a, 'input) success -> ('a, 'input) state
val ensure : int -> bytes t
end
module type C =
sig
type err += Satisfy
type err += String
type err += Repeat
val peek_chr : char option t
val peek_chr_exn : char t
val advance : int -> unit t
val satisfy : (char -> bool) -> char t
val print : string -> unit t
val string : (string -> string) -> string -> bytes t
val store : Buffer.t -> (char -> bool) -> int t
val recognize : (char -> bool) -> string t
val char : char -> char t
val many : 'a t -> 'a list t
val one : 'a t -> 'a list t
val option : 'a -> 'a t -> 'a t
val take : int -> bytes t
val list : 'a t list -> 'a list t
val count : int -> 'a t -> 'a list t
val repeat' : Buffer.t -> int option -> int option -> (char -> bool) -> int t
val repeat : int option -> int option -> (char -> bool) -> string t
end
module IO : I =
struct
type err += End_of_flow
let rec prompt i fail succ =
let continue n s =
if n = 0 then
if s = Complete
then fail i Complete
else prompt i fail succ
else succ i s
in
Read { buffer = i; k = continue; }
let expect =
{ f = fun i s fail succ ->
match s with
| Complete -> fail i s [] End_of_flow
| Incomplete ->
let succ' i' s' = succ i' s' () in
let fail' i' s' = fail i' s' [] End_of_flow in
prompt i fail' succ' }
let require n i s fail succ =
let rec continue = { f = fun i' s' fail' succ' ->
if n < Input.ravailable i'
then succ' i' s' ()
else (expect >>= fun () -> continue).f i' s' fail' succ' }
in
(expect >>= fun () -> continue).f i s fail succ
let ensure n =
let sub n =
let f
: 'r 'input. (('r, 'input) fail -> ('a, 'r, 'input) success -> ('r, 'input) state, 'input) k
= fun i s _fail succ ->
let tmp = Internal_buffer.create_by ~proof:(Input.proof i) n in
Input.peek i tmp 0 n;
succ i s (Internal_buffer.sub_string tmp 0 (Internal_buffer.length tmp))
in
{ f }
in
{ f = fun i s fail succ ->
if Input.ravailable i >= n
then succ i s ()
else require n i s fail succ }
>>= fun () -> sub n
end
module Convenience : C =
struct
let peek_chr = { f = fun i s _fail succ ->
if Input.ravailable i > 0
then succ i s (Some (Input.get i))
else if s = Complete
then succ i s None
else
let succ' i' s' =
succ i' s' (Some (Input.get i')) in
let fail' i' s' =
succ i' s' None in
IO.prompt i fail' succ' }
let peek_chr_exn = { f = fun i s fail succ ->
if Input.ravailable i > 0
then succ i s (Input.get i)
else let succ' i' s' () =
succ i' s' (Input.get i') in
IO.require 1 i s fail succ' }
let advance n =
{ f = fun i s _fail succ -> Input.radvance i n; succ i s () }
type err += Satisfy
let satisfy f =
peek_chr_exn >>= fun chr ->
if f chr
then advance 1 >>| fun () -> chr
else fail Satisfy
type err += String
let print t =
{ f = fun i s _fail succ ->
Printf.printf "%s%!" t;
succ i s () }
let string f s =
let len = String.length s in
IO.ensure len >>= fun s' ->
if f s = f (Bytes.to_string s')
then advance len *> return s'
else fail String
let store buffer f =
{ f = fun i s _fail succ ->
let recognize buff off len =
let len' = locate buff off len f in
Buffer.add_bytes buffer (Internal_buffer.sub_string buff off len');
len'
in
let consumed = Input.transmit i recognize in
succ i s consumed }
let recognize f =
{ f = fun i s fail succ ->
let buffer = Buffer.create 16 in
let r = fix @@ fun m ->
peek_chr >>= function
| Some chr when f chr -> store buffer f >>= fun _ -> m
| Some _ | None -> return (Buffer.length buffer)
in
let succ' i s _consumed = succ i s (Buffer.contents buffer) in
r.f i s fail succ' }
let char chr =
satisfy ((=) chr) <?> (String.make 1 chr)
let many p =
fix (fun m -> (lift2 (fun x r -> x :: r) p m) <|> return [])
let one p =
lift2 (fun x r -> x :: r) p (many p)
let option x p =
p <|> return x
let take n =
let n = max n 0 in
IO.ensure n >>= fun str ->
advance n >>| fun () -> str
let rec list l =
match l with
| [] -> return []
| x :: r -> lift2 (fun x r -> x :: r) x (list r)
let count n p =
assert (n >= 0);
let rec loop = function
| 0 -> return []
| n -> lift2 (fun x r -> x :: r) p (loop (n - 1))
in
loop n
type err += Repeat
let repeat' buffer a b f =
let at_least n = match a with
| Some a -> n >= a
| None -> true
in
let is_most n = match b with
| Some b -> n = b
| None -> false
in
fix @@ fun m ->
peek_chr >>= function
| Some chr when f chr && not (is_most (Buffer.length buffer)) ->
{ f = fun i s _fail succ ->
let consumed = Input.transmit i
(fun buff off len ->
let len' = locate buff off len f in
let len' = match b with
| Some b when (Buffer.length buffer + len') > b ->
b - (Buffer.length buffer)
| _ -> len'
in
Buffer.add_bytes buffer (Internal_buffer.sub_string buff off len');
len') in
succ i s consumed } *> m
| _ ->
if at_least (Buffer.length buffer)
then return (Buffer.length buffer)
else fail Repeat
let repeat a b f =
{ f = fun i s fail succ ->
let buffer = Buffer.create 16 in
let succ' i s _n = succ i s (Buffer.contents buffer) in
(repeat' buffer a b f).f i s fail succ' }
end
|
a98631612ca1e122fad9362869eca8b5f2dc7e2567e06dc4ce27ab02c7c42277 | meriken/ju | util.clj | (ns ju.util
(:require [ju.param :as param]
[taoensso.timbre :as timbre]
[pandect.algo.sha1 :refer :all]
[clojure.data.codec.base64]
[taoensso.timbre.appenders.3rd-party.rotor :as rotor])
(:import (java.net URLEncoder InetAddress)
(java.nio.file Files)
(java.security MessageDigest)))
(defn try-times*
[n thunk]
(loop [n n]
(if-let [result (try
[(thunk)]
(catch Exception e
(when (zero? n)
(throw e))))]
(result 0)
(recur (dec n)))))
(defmacro try-times
[n & body]
`(try-times* ~n (fn [] ~@body)))
(defn valid-node-name? [node-name]
(and
(re-find #"^((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])):[0-9]+(/[a-zA-Z0-9._]+)+$" node-name)
(not (re-find #"^192\." node-name))
(not (re-find #"^128\." node-name))
(not (re-find #"^localhost:" node-name))))
(defn valid-file? [file]
(re-find #"^([0-9]+<>[0-9a-f]{32}<>.*\n)+$" file))
(defn valid-file-name? [file-name]
(re-find #"^[0-9a-zA-Z]+_[0-9a-zA-Z_]+$" file-name))
(defn valid-range? [range]
(if (or (re-find #"^[0-9]+$" range)
(re-find #"^-[0-9]+$" range)
(re-find #"^[0-9]+-$" range))
true
(let [match (re-find #"^([0-9]+)-([0-9]+)$" range)]
(and match (<= (Long/parseLong (nth match 1)) (Long/parseLong (nth match 2)))))))
(defn hexify [s]
(apply str (map #(format "%02X" %) (.getBytes s "UTF-8"))))
(defn hex-string-to-byte-array
[s]
(into-array Byte/TYPE
(map (fn [[x y]]
(unchecked-byte (Integer/parseInt (str x y) 16)))
(partition 2 s))))
(defn unhexify [s]
(let [bytes (hex-string-to-byte-array s)]
(String. bytes "UTF-8")))
(defn file-name-to-thread-title
[file-name]
(and
(re-find #"^thread_(.*)$" file-name)
(unhexify (second (re-find #"^thread_(.*)$" file-name)))))
(defn thread-title-to-file-name
[thread-title]
(str "thread_" (apply str (map #(format "%02X" %) (.getBytes thread-title "UTF-8")))))
(defn md5
[s]
(let [md (MessageDigest/getInstance "MD5")]
(.update md (cond
(nil? s) (.getBytes "" "UTF-8")
(string? s) (.getBytes s "UTF-8")
:else s))
(apply str (map #(format "%02x" %) (.digest md)))))
(defn- nth-unsigned
[a i]
(let [value (int (nth a i 0))]
(if (< value 0) (+ 256 value) value)))
(defn jane-md5
[binary-array]
(let [digest (let [m (java.security.MessageDigest/getInstance "MD5")]
(.reset m)
(.update m binary-array)
(.digest m))]
(apply str (map #(.charAt
"0123456789ABCDEFGHIJKLMNOPQRSTUV"
(bit-and
(bit-shift-right
(bit-or
(bit-shift-left
(nth-unsigned digest (inc (quot (* % 5) 8))) 8)
(nth-unsigned digest (quot (* % 5) 8)))
(rem (* % 5) 8))
31))
(range 0 26)))))
(defn valid-node?
[node-name]
(not (some #{node-name} (into #{} param/blocked-nodes))))
(import 'org.apache.commons.codec.digest.Crypt)
(def tripcode-encoding "windows-31j")
(def nec-character-map
(apply merge (map (fn [pair] {(first pair) (hex-string-to-byte-array (second pair))})
(apply concat (map (fn [[start char-string]]
(map (fn [c i] (list (str c) (format "%04x" i)))
char-string
(range start (+ start (count char-string)))))
[[0xed40 "纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"]
[0xed80 "塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"]
[0xee40 "犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"]
[0xee80 "蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"]
[0xeeef "ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹ¬¦'""]
])))))
(defn get-byte-array-for-tripcode-key
[key]
(byte-array
(mapcat
seq
(map
#(cond
(get nec-character-map % nil) (get nec-character-map %)
:else (.getBytes % tripcode-encoding))
(map str key)))))
(defn generate-tripcode
[key]
;(timbre/debug "key: " (apply str (map #(format "%02X " %) (get-byte-array-for-tripcode-key key))))
(let
[modified-key1 (-> key
(clojure.string/replace "#" "#"))
modified-key2 (-> modified-key1
(clojure.string/replace "&r" "")
(clojure.string/replace "\"" """)
(clojure.string/replace "<" "<")
(clojure.string/replace ">" ">"))
modified-key modified-key1
key-byte-array (get-byte-array-for-tripcode-key modified-key )
key-byte-array-original-length (count key-byte-array)
key-byte-array (java.util.Arrays/copyOf key-byte-array (+ (* (count key-byte-array) 2) 16))
_ (comment dorun (map (fn [[target replacement]]
(let [target-bytes (get-byte-array-for-tripcode-key target )
replacement-bytes (get-byte-array-for-tripcode-key replacement)]
(if (or
(not (re-find (re-pattern target) replacement))
(loop [[pos & tail] (range key-byte-array-original-length)]
(cond
(every? true? (map
#(or (and (pos? %) (>= (+ pos %) key-byte-array-original-length))
(= (get key-byte-array (+ pos %)) (get replacement-bytes %)))
(range (count replacement-bytes))))
false
(pos? (count tail))
(recur tail)
:else
true)))
(dorun (loop [[pos & tail] (range key-byte-array-original-length)]
(cond
(zero? (count (remove true? (map #(= (get key-byte-array (+ pos %)) (get target-bytes %)) (range (count target-bytes))))))
(do
(dorun (for [i (range (- key-byte-array-original-length (count target-bytes) pos))]
(do
(aset-byte
key-byte-array
(+ pos i (count replacement-bytes))
(get key-byte-array (+ pos i (count target-bytes)))
))))
(dorun (for [j (range (count replacement-bytes))]
(aset-byte key-byte-array (+ pos j) (get replacement-bytes j))
)))
(pos? (count tail))
(recur tail)))))))
[["●" "○"]
["◆" "◇"]
["★" "☆"]
["管理" "”管理”"]
["削除" "”削除”"]
["復帰" "”復帰”"]
["山崎渉" "fusianasan"]]))
actual-key-byte-array-length ((fn count-length
[pos]
(if (or (= (get key-byte-array pos) (byte 0))
(>= pos (count key-byte-array))
)
pos
(count-length (inc pos))))
0)
key-byte-list (reverse (into () (java.util.Arrays/copyOf key-byte-array actual-key-byte-array-length)))
result (split-with #(not (= % (byte -128))) key-byte-list)
key-byte-list-0x80 (concat (first result) (if (empty? (second result)) '() (list (byte -128))))
key-byte-array-for-salt (byte-array (mapcat seq (list key-byte-list (map byte "H."))))
salt-chars "/0123456789ABCDEFGABCDEFGHIJKLMNOPQRSTUVWXYZabcdefabcdefghijklmnopqrstuvwxyz"
salt-map (apply merge (map #(do {(+ 47 (int %2)) (str %1)}) salt-chars (range (count salt-chars))))
salt (str
(get salt-map (get key-byte-array-for-salt 1) ".")
(get salt-map (get key-byte-array-for-salt 2) "."))]
;(timbre/debug "modified-key-0x80:" (apply str (map #(format "%02X " %) (get-byte-array-for-tripcode-key modified-key-0x80))))
(cond
(< (count (get-byte-array-for-tripcode-key key)) 12)
( subs ( Crypt / crypt ( byte - array key - byte - list-0x80 ) salt ) 3 )
(subs (Crypt/crypt (byte-array key-byte-list) salt) 3)
(re-find #"^[a-fA-F0-9]{16}[./0-9A-Za-z]{0,2}$" key)
(let [[_ key-hex-string salt] (re-find #"^([a-fA-F0-9]{16})([./0-9A-Za-z]{0,2})$" key)
salt (str salt "..")]
(subs (Crypt/crypt (hex-string-to-byte-array key-hex-string) salt) 3))
(and
(>= (count (get-byte-array-for-tripcode-key key)) 12)
(re-find #"^[^$#]" key))
(-> key-byte-list ;key-byte-list-0x80
(byte-array)
(sha1)
(hex-string-to-byte-array)
(org.apache.commons.codec.binary.Base64/encodeBase64String)
(subs 0 12)
(clojure.string/replace #"\+" "."))
(and
(>= (count (get-byte-array-for-tripcode-key key)) 12)
(re-find #"^\$[^\uFF61-\uFF9F]" key))
(-> key-byte-list ;key-byte-list-0x80
(byte-array)
(sha1)
(hex-string-to-byte-array)
(org.apache.commons.codec.binary.Base64/encodeBase64String)
(subs 3 18)
(clojure.string/replace #"\/" "!")
(clojure.string/replace #"\+" "."))
(and
(>= (count (get-byte-array-for-tripcode-key key)) 12)
(re-find #"^\$[\uFF61-\uFF9F]" key))
(-> key-byte-list ;key-byte-list-0x80
(byte-array)
(sha1)
(hex-string-to-byte-array)
(org.apache.commons.codec.binary.Base64/encodeBase64String)
(subs 3 18)
(clojure.string/replace #"0" "\uFF61")
(clojure.string/replace #"1" "\uFF62")
(clojure.string/replace #"2" "\uFF63")
(clojure.string/replace #"3" "\uFF64")
(clojure.string/replace #"4" "\uFF65")
(clojure.string/replace #"5" "\uFF66")
(clojure.string/replace #"6" "\uFF67")
(clojure.string/replace #"7" "\uFF68")
(clojure.string/replace #"8" "\uFF69")
(clojure.string/replace #"9" "\uFF6A")
(clojure.string/replace #"A" "\uFF6B")
(clojure.string/replace #"B" "\uFF6C")
(clojure.string/replace #"C" "\uFF6D")
(clojure.string/replace #"D" "\uFF6E")
(clojure.string/replace #"E" "\uFF6F")
(clojure.string/replace #"F" "\uFF70")
(clojure.string/replace #"G" "\uFF71")
(clojure.string/replace #"H" "\uFF72")
(clojure.string/replace #"I" "\uFF73")
(clojure.string/replace #"J" "\uFF74")
(clojure.string/replace #"K" "\uFF75")
(clojure.string/replace #"L" "\uFF76")
(clojure.string/replace #"M" "\uFF77")
(clojure.string/replace #"N" "\uFF78")
(clojure.string/replace #"O" "\uFF79")
(clojure.string/replace #"P" "\uFF7A")
(clojure.string/replace #"Q" "\uFF7B")
(clojure.string/replace #"R" "\uFF7C")
(clojure.string/replace #"S" "\uFF7D")
(clojure.string/replace #"T" "\uFF7E")
(clojure.string/replace #"U" "\uFF7F")
(clojure.string/replace #"V" "\uFF80")
(clojure.string/replace #"W" "\uFF81")
(clojure.string/replace #"X" "\uFF82")
(clojure.string/replace #"Y" "\uFF83")
(clojure.string/replace #"Z" "\uFF84")
(clojure.string/replace #"a" "\uFF85")
(clojure.string/replace #"b" "\uFF86")
(clojure.string/replace #"c" "\uFF87")
(clojure.string/replace #"d" "\uFF88")
(clojure.string/replace #"e" "\uFF89")
(clojure.string/replace #"f" "\uFF8A")
(clojure.string/replace #"g" "\uFF8B")
(clojure.string/replace #"h" "\uFF8C")
(clojure.string/replace #"i" "\uFF8D")
(clojure.string/replace #"j" "\uFF8E")
(clojure.string/replace #"k" "\uFF8F")
(clojure.string/replace #"l" "\uFF90")
(clojure.string/replace #"m" "\uFF91")
(clojure.string/replace #"n" "\uFF92")
(clojure.string/replace #"o" "\uFF93")
(clojure.string/replace #"p" "\uFF94")
(clojure.string/replace #"q" "\uFF95")
(clojure.string/replace #"r" "\uFF96")
(clojure.string/replace #"s" "\uFF97")
(clojure.string/replace #"t" "\uFF98")
(clojure.string/replace #"u" "\uFF99")
(clojure.string/replace #"v" "\uFF9A")
(clojure.string/replace #"w" "\uFF9B")
(clojure.string/replace #"x" "\uFF9C")
(clojure.string/replace #"y" "\uFF9D")
(clojure.string/replace #"z" "\uFF9E")
(clojure.string/replace #"/" "!"))
:else
"???")))
(defn check-tripcodes
[]
(dorun (map (fn [[tripcode key]]
(print (str "◆" tripcode " #" key)
(if (= tripcode (generate-tripcode key))
"[PASS]\n"
(str "[FAIL: ◆" (generate-tripcode key) "]\n"))))
[["WBRXcNtpf." "12345678"]
["WBRXcNtpf." "ア23エオカキク"]
["XlUiP8mHCU" "アイウエオカキク"]
["QH.zpPwVew" "チツテトナニヌネ"]
["QH.zpPwVew" "AツテDEFGH"]
["aOLjRoi1zs" "ABCDEFGH"]
["RMZ/x4umbQ" "'()*+,-."]
["RMZ/x4umbQ" "ァ()ェォャュョ"]
["RMZ/x4umbQ" "ァィゥェォャュョ"]
["5637936436" "'!+$#-.)"]
["5637936436" "ァ!+、」ュョゥ"]
["5637936436" "ァ。ォ、」ュョゥ"]
["7778933162" "&rキR;YFj"];◆IshBgEJs9E ;◆7778933162
["IshBgEJs9E" "キR;YFj"]
["7778933162" "ヲrキR;YFj"]
["7778933162" "&&rrキR;YFj"]
◆ gt1azVccY2 ; ◆ 4eqVTkonjE
["gt1azVccY2" """]
◆ 1771265006 ; ◆ S6SGQNQ5.s
["1771265006" "`サ静<"]
["4097306092" "通:U>"]
["4097306092" "通:U>"]
["s8X90K5ceE" "●"];◆GwiVxeuT5c ;◆s8X90K5ceE
["GwiVxeuT5c" "○"];OK
["gqRrL0OhYE" "◆"]
["gqRrL0OhYE" "◇"]
["G8Jw4.nqFk" "★"]
["G8Jw4.nqFk" "☆"]
["u2YjtUz8MU" "#"];OK ;◆u2YjtUz8MU /
["u2YjtUz8MU" "#"]
["XKSnTxcTbA" "管理"];◆..M7CxRsnk
["XKSnTxcTbA" "”管理”"]
["172VC7723I" "削除"]
["172VC7723I" "”削除”"]
["F4vmrUK4pg" "復帰"]
["F4vmrUK4pg" "”復帰”"]
["M2TLe2H2No" "山崎渉"]
["M2TLe2H2No" "fusianasan"]
6ZmSz0zwL2 ; ◆ QQnk8rTtk6 ;
["6ZmSz0zwL2" "÷うんこ"]
["AOGu5v68Us" "ムスカ"]
["AOGu5v68Us" "ムーミン"]
["Kpoz.PjwKU" "krMfメ彗"]
["Kpoz.PjwKU" "krMfメ嫗"]
["d23M6xVMa." "=ムwT早浣"]
["d23M6xVMa." "=ムwT早椡"]
["aJx2.8B7ls" "a坩7CU|"]
["aJx2.8B7ls" "a勸7CU|"]
["vQ/eO6pbUM" "E0孖ヌ理拭"];◆..M7CxRsnk ;
["vQ/eO6pbUM" "E0增h管理"]
["lsQhRnmqAY" "+ナ檮尞彈"]
["lsQhRnmqAY" "+ナ栫h削除"]
["uxO1D1zfT." "封恚A欲["]
["uxO1D1zfT." "普h復帰”"]
["hbqILjsyyc" "虫R崎渉1"]
["hbqILjsyyc" "断usiana"]
["siuX2W5X5Q" "a#eX.o"]
["4297602876" "瘁覇X.o"]
["d6yXdw5r52" "d##シタu!"]
["6089931596" "艨肇シタu!"]
["IHp4MBMwSE" "0000000000000000ZZ"]
["DLUg7SsaxM" "4141414141414141AA"]
["rbRq1xknGPCL0u6" "$000000000000"]
["リイユ、ソアニテワスーゥヤラフ" "$ア00000000000"]
])))
(defn ju-output-fn
([data] (ju-output-fn nil data))
([{:keys [no-stacktrace? stacktrace-fonts] :as opts} data]
(let [{:keys [level ?err_ vargs_ msg_ ?ns-str hostname_ timestamp_]} data]
(str
(force timestamp_) " "
; (force hostname_) " "
; (clojure.string/upper-case (name level)) " "
; "[" (or ?ns-str "?ns") "] "
(force msg_) " "
(if (force ?err_)
(org.apache.commons.lang3.exception.ExceptionUtils/getStackTrace (force ?err_)))
(comment when-not no-stacktrace?
(when-let [err (force ?err_)]
(str "\n" (stacktrace err opts))))
))))
(defn configure-timbre
[]
(let [filename-base "ju"]
(timbre/merge-config!
{:output-fn ju-output-fn})
(timbre/merge-config!
{:appenders
{:rotor (rotor/rotor-appender {:path "ju.log"})}})
(timbre/merge-config!
{:ns-blacklist ["slf4j-timbre.adapter"]})))
| null | https://raw.githubusercontent.com/meriken/ju/99caa4625535d3da66002c460bf16d8708cabd7e/src/ju/util.clj | clojure | (timbre/debug "key: " (apply str (map #(format "%02X " %) (get-byte-array-for-tripcode-key key))))
")
(timbre/debug "modified-key-0x80:" (apply str (map #(format "%02X " %) (get-byte-array-for-tripcode-key modified-key-0x80))))
key-byte-list-0x80
key-byte-list-0x80
key-byte-list-0x80
◆IshBgEJs9E ;◆7778933162
◆ 4eqVTkonjE
◆ S6SGQNQ5.s
◆GwiVxeuT5c ;◆s8X90K5ceE
OK
OK ;◆u2YjtUz8MU /
◆..M7CxRsnk
◆ QQnk8rTtk6 ;
◆..M7CxRsnk ;
(force hostname_) " "
(clojure.string/upper-case (name level)) " "
"[" (or ?ns-str "?ns") "] " | (ns ju.util
(:require [ju.param :as param]
[taoensso.timbre :as timbre]
[pandect.algo.sha1 :refer :all]
[clojure.data.codec.base64]
[taoensso.timbre.appenders.3rd-party.rotor :as rotor])
(:import (java.net URLEncoder InetAddress)
(java.nio.file Files)
(java.security MessageDigest)))
(defn try-times*
[n thunk]
(loop [n n]
(if-let [result (try
[(thunk)]
(catch Exception e
(when (zero? n)
(throw e))))]
(result 0)
(recur (dec n)))))
(defmacro try-times
[n & body]
`(try-times* ~n (fn [] ~@body)))
(defn valid-node-name? [node-name]
(and
(re-find #"^((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])):[0-9]+(/[a-zA-Z0-9._]+)+$" node-name)
(not (re-find #"^192\." node-name))
(not (re-find #"^128\." node-name))
(not (re-find #"^localhost:" node-name))))
(defn valid-file? [file]
(re-find #"^([0-9]+<>[0-9a-f]{32}<>.*\n)+$" file))
(defn valid-file-name? [file-name]
(re-find #"^[0-9a-zA-Z]+_[0-9a-zA-Z_]+$" file-name))
(defn valid-range? [range]
(if (or (re-find #"^[0-9]+$" range)
(re-find #"^-[0-9]+$" range)
(re-find #"^[0-9]+-$" range))
true
(let [match (re-find #"^([0-9]+)-([0-9]+)$" range)]
(and match (<= (Long/parseLong (nth match 1)) (Long/parseLong (nth match 2)))))))
(defn hexify [s]
(apply str (map #(format "%02X" %) (.getBytes s "UTF-8"))))
(defn hex-string-to-byte-array
[s]
(into-array Byte/TYPE
(map (fn [[x y]]
(unchecked-byte (Integer/parseInt (str x y) 16)))
(partition 2 s))))
(defn unhexify [s]
(let [bytes (hex-string-to-byte-array s)]
(String. bytes "UTF-8")))
(defn file-name-to-thread-title
[file-name]
(and
(re-find #"^thread_(.*)$" file-name)
(unhexify (second (re-find #"^thread_(.*)$" file-name)))))
(defn thread-title-to-file-name
[thread-title]
(str "thread_" (apply str (map #(format "%02X" %) (.getBytes thread-title "UTF-8")))))
(defn md5
[s]
(let [md (MessageDigest/getInstance "MD5")]
(.update md (cond
(nil? s) (.getBytes "" "UTF-8")
(string? s) (.getBytes s "UTF-8")
:else s))
(apply str (map #(format "%02x" %) (.digest md)))))
(defn- nth-unsigned
[a i]
(let [value (int (nth a i 0))]
(if (< value 0) (+ 256 value) value)))
(defn jane-md5
[binary-array]
(let [digest (let [m (java.security.MessageDigest/getInstance "MD5")]
(.reset m)
(.update m binary-array)
(.digest m))]
(apply str (map #(.charAt
"0123456789ABCDEFGHIJKLMNOPQRSTUV"
(bit-and
(bit-shift-right
(bit-or
(bit-shift-left
(nth-unsigned digest (inc (quot (* % 5) 8))) 8)
(nth-unsigned digest (quot (* % 5) 8)))
(rem (* % 5) 8))
31))
(range 0 26)))))
(defn valid-node?
[node-name]
(not (some #{node-name} (into #{} param/blocked-nodes))))
(import 'org.apache.commons.codec.digest.Crypt)
(def tripcode-encoding "windows-31j")
(def nec-character-map
(apply merge (map (fn [pair] {(first pair) (hex-string-to-byte-array (second pair))})
(apply concat (map (fn [[start char-string]]
(map (fn [c i] (list (str c) (format "%04x" i)))
char-string
(range start (+ start (count char-string)))))
[[0xed40 "纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"]
[0xed80 "塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"]
[0xee40 "犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"]
[0xee80 "蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"]
[0xeeef "ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹ¬¦'""]
])))))
(defn get-byte-array-for-tripcode-key
[key]
(byte-array
(mapcat
seq
(map
#(cond
(get nec-character-map % nil) (get nec-character-map %)
:else (.getBytes % tripcode-encoding))
(map str key)))))
(defn generate-tripcode
[key]
(let
[modified-key1 (-> key
(clojure.string/replace "#" "#"))
modified-key2 (-> modified-key1
(clojure.string/replace "&r" "")
(clojure.string/replace "<" "<")
(clojure.string/replace ">" ">"))
modified-key modified-key1
key-byte-array (get-byte-array-for-tripcode-key modified-key )
key-byte-array-original-length (count key-byte-array)
key-byte-array (java.util.Arrays/copyOf key-byte-array (+ (* (count key-byte-array) 2) 16))
_ (comment dorun (map (fn [[target replacement]]
(let [target-bytes (get-byte-array-for-tripcode-key target )
replacement-bytes (get-byte-array-for-tripcode-key replacement)]
(if (or
(not (re-find (re-pattern target) replacement))
(loop [[pos & tail] (range key-byte-array-original-length)]
(cond
(every? true? (map
#(or (and (pos? %) (>= (+ pos %) key-byte-array-original-length))
(= (get key-byte-array (+ pos %)) (get replacement-bytes %)))
(range (count replacement-bytes))))
false
(pos? (count tail))
(recur tail)
:else
true)))
(dorun (loop [[pos & tail] (range key-byte-array-original-length)]
(cond
(zero? (count (remove true? (map #(= (get key-byte-array (+ pos %)) (get target-bytes %)) (range (count target-bytes))))))
(do
(dorun (for [i (range (- key-byte-array-original-length (count target-bytes) pos))]
(do
(aset-byte
key-byte-array
(+ pos i (count replacement-bytes))
(get key-byte-array (+ pos i (count target-bytes)))
))))
(dorun (for [j (range (count replacement-bytes))]
(aset-byte key-byte-array (+ pos j) (get replacement-bytes j))
)))
(pos? (count tail))
(recur tail)))))))
[["●" "○"]
["◆" "◇"]
["★" "☆"]
["管理" "”管理”"]
["削除" "”削除”"]
["復帰" "”復帰”"]
["山崎渉" "fusianasan"]]))
actual-key-byte-array-length ((fn count-length
[pos]
(if (or (= (get key-byte-array pos) (byte 0))
(>= pos (count key-byte-array))
)
pos
(count-length (inc pos))))
0)
key-byte-list (reverse (into () (java.util.Arrays/copyOf key-byte-array actual-key-byte-array-length)))
result (split-with #(not (= % (byte -128))) key-byte-list)
key-byte-list-0x80 (concat (first result) (if (empty? (second result)) '() (list (byte -128))))
key-byte-array-for-salt (byte-array (mapcat seq (list key-byte-list (map byte "H."))))
salt-chars "/0123456789ABCDEFGABCDEFGHIJKLMNOPQRSTUVWXYZabcdefabcdefghijklmnopqrstuvwxyz"
salt-map (apply merge (map #(do {(+ 47 (int %2)) (str %1)}) salt-chars (range (count salt-chars))))
salt (str
(get salt-map (get key-byte-array-for-salt 1) ".")
(get salt-map (get key-byte-array-for-salt 2) "."))]
(cond
(< (count (get-byte-array-for-tripcode-key key)) 12)
( subs ( Crypt / crypt ( byte - array key - byte - list-0x80 ) salt ) 3 )
(subs (Crypt/crypt (byte-array key-byte-list) salt) 3)
(re-find #"^[a-fA-F0-9]{16}[./0-9A-Za-z]{0,2}$" key)
(let [[_ key-hex-string salt] (re-find #"^([a-fA-F0-9]{16})([./0-9A-Za-z]{0,2})$" key)
salt (str salt "..")]
(subs (Crypt/crypt (hex-string-to-byte-array key-hex-string) salt) 3))
(and
(>= (count (get-byte-array-for-tripcode-key key)) 12)
(re-find #"^[^$#]" key))
(byte-array)
(sha1)
(hex-string-to-byte-array)
(org.apache.commons.codec.binary.Base64/encodeBase64String)
(subs 0 12)
(clojure.string/replace #"\+" "."))
(and
(>= (count (get-byte-array-for-tripcode-key key)) 12)
(re-find #"^\$[^\uFF61-\uFF9F]" key))
(byte-array)
(sha1)
(hex-string-to-byte-array)
(org.apache.commons.codec.binary.Base64/encodeBase64String)
(subs 3 18)
(clojure.string/replace #"\/" "!")
(clojure.string/replace #"\+" "."))
(and
(>= (count (get-byte-array-for-tripcode-key key)) 12)
(re-find #"^\$[\uFF61-\uFF9F]" key))
(byte-array)
(sha1)
(hex-string-to-byte-array)
(org.apache.commons.codec.binary.Base64/encodeBase64String)
(subs 3 18)
(clojure.string/replace #"0" "\uFF61")
(clojure.string/replace #"1" "\uFF62")
(clojure.string/replace #"2" "\uFF63")
(clojure.string/replace #"3" "\uFF64")
(clojure.string/replace #"4" "\uFF65")
(clojure.string/replace #"5" "\uFF66")
(clojure.string/replace #"6" "\uFF67")
(clojure.string/replace #"7" "\uFF68")
(clojure.string/replace #"8" "\uFF69")
(clojure.string/replace #"9" "\uFF6A")
(clojure.string/replace #"A" "\uFF6B")
(clojure.string/replace #"B" "\uFF6C")
(clojure.string/replace #"C" "\uFF6D")
(clojure.string/replace #"D" "\uFF6E")
(clojure.string/replace #"E" "\uFF6F")
(clojure.string/replace #"F" "\uFF70")
(clojure.string/replace #"G" "\uFF71")
(clojure.string/replace #"H" "\uFF72")
(clojure.string/replace #"I" "\uFF73")
(clojure.string/replace #"J" "\uFF74")
(clojure.string/replace #"K" "\uFF75")
(clojure.string/replace #"L" "\uFF76")
(clojure.string/replace #"M" "\uFF77")
(clojure.string/replace #"N" "\uFF78")
(clojure.string/replace #"O" "\uFF79")
(clojure.string/replace #"P" "\uFF7A")
(clojure.string/replace #"Q" "\uFF7B")
(clojure.string/replace #"R" "\uFF7C")
(clojure.string/replace #"S" "\uFF7D")
(clojure.string/replace #"T" "\uFF7E")
(clojure.string/replace #"U" "\uFF7F")
(clojure.string/replace #"V" "\uFF80")
(clojure.string/replace #"W" "\uFF81")
(clojure.string/replace #"X" "\uFF82")
(clojure.string/replace #"Y" "\uFF83")
(clojure.string/replace #"Z" "\uFF84")
(clojure.string/replace #"a" "\uFF85")
(clojure.string/replace #"b" "\uFF86")
(clojure.string/replace #"c" "\uFF87")
(clojure.string/replace #"d" "\uFF88")
(clojure.string/replace #"e" "\uFF89")
(clojure.string/replace #"f" "\uFF8A")
(clojure.string/replace #"g" "\uFF8B")
(clojure.string/replace #"h" "\uFF8C")
(clojure.string/replace #"i" "\uFF8D")
(clojure.string/replace #"j" "\uFF8E")
(clojure.string/replace #"k" "\uFF8F")
(clojure.string/replace #"l" "\uFF90")
(clojure.string/replace #"m" "\uFF91")
(clojure.string/replace #"n" "\uFF92")
(clojure.string/replace #"o" "\uFF93")
(clojure.string/replace #"p" "\uFF94")
(clojure.string/replace #"q" "\uFF95")
(clojure.string/replace #"r" "\uFF96")
(clojure.string/replace #"s" "\uFF97")
(clojure.string/replace #"t" "\uFF98")
(clojure.string/replace #"u" "\uFF99")
(clojure.string/replace #"v" "\uFF9A")
(clojure.string/replace #"w" "\uFF9B")
(clojure.string/replace #"x" "\uFF9C")
(clojure.string/replace #"y" "\uFF9D")
(clojure.string/replace #"z" "\uFF9E")
(clojure.string/replace #"/" "!"))
:else
"???")))
(defn check-tripcodes
[]
(dorun (map (fn [[tripcode key]]
(print (str "◆" tripcode " #" key)
(if (= tripcode (generate-tripcode key))
"[PASS]\n"
(str "[FAIL: ◆" (generate-tripcode key) "]\n"))))
[["WBRXcNtpf." "12345678"]
["WBRXcNtpf." "ア23エオカキク"]
["XlUiP8mHCU" "アイウエオカキク"]
["QH.zpPwVew" "チツテトナニヌネ"]
["QH.zpPwVew" "AツテDEFGH"]
["aOLjRoi1zs" "ABCDEFGH"]
["RMZ/x4umbQ" "'()*+,-."]
["RMZ/x4umbQ" "ァ()ェォャュョ"]
["RMZ/x4umbQ" "ァィゥェォャュョ"]
["5637936436" "'!+$#-.)"]
["5637936436" "ァ!+、」ュョゥ"]
["5637936436" "ァ。ォ、」ュョゥ"]
["IshBgEJs9E" "キR;YFj"]
["7778933162" "ヲrキR;YFj"]
["7778933162" "&&rrキR;YFj"]
["gt1azVccY2" """]
["1771265006" "`サ静<"]
["4097306092" "通:U>"]
["4097306092" "通:U>"]
["gqRrL0OhYE" "◆"]
["gqRrL0OhYE" "◇"]
["G8Jw4.nqFk" "★"]
["G8Jw4.nqFk" "☆"]
["u2YjtUz8MU" "#"]
["XKSnTxcTbA" "”管理”"]
["172VC7723I" "削除"]
["172VC7723I" "”削除”"]
["F4vmrUK4pg" "復帰"]
["F4vmrUK4pg" "”復帰”"]
["M2TLe2H2No" "山崎渉"]
["M2TLe2H2No" "fusianasan"]
["6ZmSz0zwL2" "÷うんこ"]
["AOGu5v68Us" "ムスカ"]
["AOGu5v68Us" "ムーミン"]
["Kpoz.PjwKU" "krMfメ彗"]
["Kpoz.PjwKU" "krMfメ嫗"]
["d23M6xVMa." "=ムwT早浣"]
["d23M6xVMa." "=ムwT早椡"]
["aJx2.8B7ls" "a坩7CU|"]
["aJx2.8B7ls" "a勸7CU|"]
["vQ/eO6pbUM" "E0增h管理"]
["lsQhRnmqAY" "+ナ檮尞彈"]
["lsQhRnmqAY" "+ナ栫h削除"]
["uxO1D1zfT." "封恚A欲["]
["uxO1D1zfT." "普h復帰”"]
["hbqILjsyyc" "虫R崎渉1"]
["hbqILjsyyc" "断usiana"]
["siuX2W5X5Q" "a#eX.o"]
["4297602876" "瘁覇X.o"]
["d6yXdw5r52" "d##シタu!"]
["6089931596" "艨肇シタu!"]
["IHp4MBMwSE" "0000000000000000ZZ"]
["DLUg7SsaxM" "4141414141414141AA"]
["rbRq1xknGPCL0u6" "$000000000000"]
["リイユ、ソアニテワスーゥヤラフ" "$ア00000000000"]
])))
(defn ju-output-fn
([data] (ju-output-fn nil data))
([{:keys [no-stacktrace? stacktrace-fonts] :as opts} data]
(let [{:keys [level ?err_ vargs_ msg_ ?ns-str hostname_ timestamp_]} data]
(str
(force timestamp_) " "
(force msg_) " "
(if (force ?err_)
(org.apache.commons.lang3.exception.ExceptionUtils/getStackTrace (force ?err_)))
(comment when-not no-stacktrace?
(when-let [err (force ?err_)]
(str "\n" (stacktrace err opts))))
))))
(defn configure-timbre
[]
(let [filename-base "ju"]
(timbre/merge-config!
{:output-fn ju-output-fn})
(timbre/merge-config!
{:appenders
{:rotor (rotor/rotor-appender {:path "ju.log"})}})
(timbre/merge-config!
{:ns-blacklist ["slf4j-timbre.adapter"]})))
|
4a90f05c20f126d1a759a4e044e8f07dc0601ba7a551bd39f0de4da31dd29977 | infinisil/nixbot | Escape.hs | # LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
module Plugins.Commands.Escape where
import Data.Text (Text)
import qualified Data.Text as Text
import Plugins
import Types
import NixEval
import Data.Char
import Data.Text.Encoding
import qualified Data.ByteString.Lazy as LBS
import Data.Aeson
import Control.Monad.IO.Class
data Part
= Literal Char
| Escaped Char
deriving (Show, Eq)
type NixString = [Part]
toNixString :: Text -> NixString
toNixString = map quoteNonAlpha . Text.unpack where
quoteNonAlpha :: Char -> Part
quoteNonAlpha char | isAlpha char = Literal char
| otherwise = Escaped char
fromNixString :: StringKind -> NixString -> Text
fromNixString kind = Text.concat . map x where
quote :: Text
quote = case kind of
SingleQuotes -> "''\\"
DoubleQuote -> "\\"
x :: Part -> Text
x (Literal char) = Text.singleton char
x (Escaped char) = quote <> Text.singleton char
minimizeStep :: StringKind -> NixString -> Maybe NixString
minimizeStep _ [] = Nothing
minimizeStep SingleQuotes (Escaped '\'' : Escaped '\'' : rest) = Just $ Literal '\'' : Literal '\'' : Literal '\'' : rest
minimizeStep SingleQuotes (Escaped '$' : Escaped '{' : rest) = Just $ Literal '\'' : Literal '\'' : Literal '$' : Literal '{' : rest
minimizeStep DoubleQuote (Escaped '$' : Escaped '{' : rest) = Just $ Escaped '$' : Literal '{' : rest
minimizeStep _ (Escaped c : rest) = Just $ Literal c : rest
minimizeStep _ (Literal _ : _) = Nothing
minimizeOnce :: StringKind -> NixString -> NixString -> Text -> IO NixString
minimizeOnce kind prefix str target =
case minimizeStep kind str of
Nothing -> tailMinimize str target
Just newStr -> do
stillValid <- check kind (prefix ++ newStr) target
if stillValid then
minimizeOnce kind prefix newStr target
else
tailMinimize str target
where
tailMinimize :: NixString -> Text -> IO NixString
tailMinimize [] _ = return []
tailMinimize (c:cs) target' = do
minimizedRest <- minimizeOnce kind (prefix ++ [c]) cs target'
return $ c : minimizedRest
minimizeFull :: StringKind -> NixString -> Text -> IO NixString
minimizeFull kind str target = do
newStr <- minimizeOnce kind [] str target
if str /= newStr then
minimizeFull kind newStr target
else return str
data StringKind = SingleQuotes | DoubleQuote
check :: StringKind -> NixString -> Text -> IO Bool
check kind nix target' = do
let target = target' <> " "
(pre, post) = prepost
nixString = pre <> fromNixString kind nix <> post
evalOptions = (defNixEvalOptions (Left (LBS.fromStrict (encodeUtf8 nixString))))
{ mode = Json
}
result <- nixInstantiate "nix-instantiate" evalOptions
case result of
Left _ -> return False
Right jsonString -> case decode' jsonString of
Nothing -> return False
Just evalResult -> return (target == evalResult)
where
prepost :: (Text, Text)
prepost = case kind of
SingleQuotes -> ("''", " ''")
DoubleQuote -> ("\"", " \"")
escapeHandle :: Text -> PluginT App ()
escapeHandle text' = do
let text = Text.dropWhile isSpace text'
if Text.null text then
reply "Usage: ,escape <text> to show how to escape the given text in Nix"
else do
single <- liftIO $ fromNixString SingleQuotes <$> minimizeFull SingleQuotes (toNixString text) text
double <- liftIO $ fromNixString DoubleQuote <$> minimizeFull DoubleQuote (toNixString text) text
if single == double then
reply $ "Escape this in \" and '' strings with: " <> single
else do
reply $ "Escape this in '' strings with: " <> single
reply $ "Escape this in \" strings with: " <> double
| null | https://raw.githubusercontent.com/infinisil/nixbot/e8695fd73c07bc115ee0dd3e7c121cd985c04c06/src/Plugins/Commands/Escape.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE ScopedTypeVariables #
module Plugins.Commands.Escape where
import Data.Text (Text)
import qualified Data.Text as Text
import Plugins
import Types
import NixEval
import Data.Char
import Data.Text.Encoding
import qualified Data.ByteString.Lazy as LBS
import Data.Aeson
import Control.Monad.IO.Class
data Part
= Literal Char
| Escaped Char
deriving (Show, Eq)
type NixString = [Part]
toNixString :: Text -> NixString
toNixString = map quoteNonAlpha . Text.unpack where
quoteNonAlpha :: Char -> Part
quoteNonAlpha char | isAlpha char = Literal char
| otherwise = Escaped char
fromNixString :: StringKind -> NixString -> Text
fromNixString kind = Text.concat . map x where
quote :: Text
quote = case kind of
SingleQuotes -> "''\\"
DoubleQuote -> "\\"
x :: Part -> Text
x (Literal char) = Text.singleton char
x (Escaped char) = quote <> Text.singleton char
minimizeStep :: StringKind -> NixString -> Maybe NixString
minimizeStep _ [] = Nothing
minimizeStep SingleQuotes (Escaped '\'' : Escaped '\'' : rest) = Just $ Literal '\'' : Literal '\'' : Literal '\'' : rest
minimizeStep SingleQuotes (Escaped '$' : Escaped '{' : rest) = Just $ Literal '\'' : Literal '\'' : Literal '$' : Literal '{' : rest
minimizeStep DoubleQuote (Escaped '$' : Escaped '{' : rest) = Just $ Escaped '$' : Literal '{' : rest
minimizeStep _ (Escaped c : rest) = Just $ Literal c : rest
minimizeStep _ (Literal _ : _) = Nothing
minimizeOnce :: StringKind -> NixString -> NixString -> Text -> IO NixString
minimizeOnce kind prefix str target =
case minimizeStep kind str of
Nothing -> tailMinimize str target
Just newStr -> do
stillValid <- check kind (prefix ++ newStr) target
if stillValid then
minimizeOnce kind prefix newStr target
else
tailMinimize str target
where
tailMinimize :: NixString -> Text -> IO NixString
tailMinimize [] _ = return []
tailMinimize (c:cs) target' = do
minimizedRest <- minimizeOnce kind (prefix ++ [c]) cs target'
return $ c : minimizedRest
minimizeFull :: StringKind -> NixString -> Text -> IO NixString
minimizeFull kind str target = do
newStr <- minimizeOnce kind [] str target
if str /= newStr then
minimizeFull kind newStr target
else return str
data StringKind = SingleQuotes | DoubleQuote
check :: StringKind -> NixString -> Text -> IO Bool
check kind nix target' = do
let target = target' <> " "
(pre, post) = prepost
nixString = pre <> fromNixString kind nix <> post
evalOptions = (defNixEvalOptions (Left (LBS.fromStrict (encodeUtf8 nixString))))
{ mode = Json
}
result <- nixInstantiate "nix-instantiate" evalOptions
case result of
Left _ -> return False
Right jsonString -> case decode' jsonString of
Nothing -> return False
Just evalResult -> return (target == evalResult)
where
prepost :: (Text, Text)
prepost = case kind of
SingleQuotes -> ("''", " ''")
DoubleQuote -> ("\"", " \"")
escapeHandle :: Text -> PluginT App ()
escapeHandle text' = do
let text = Text.dropWhile isSpace text'
if Text.null text then
reply "Usage: ,escape <text> to show how to escape the given text in Nix"
else do
single <- liftIO $ fromNixString SingleQuotes <$> minimizeFull SingleQuotes (toNixString text) text
double <- liftIO $ fromNixString DoubleQuote <$> minimizeFull DoubleQuote (toNixString text) text
if single == double then
reply $ "Escape this in \" and '' strings with: " <> single
else do
reply $ "Escape this in '' strings with: " <> single
reply $ "Escape this in \" strings with: " <> double
|
13e6ab68f3b024e66cf3838f1c945f7cab2033cdb2c3d2812d5ce5fb62281302 | muyinliu/cl-diskspace | packages.lisp | packages.lisp
(defpackage #:cl-diskspace
(:use #:cl
#:cffi
#:cffi-grovel)
(:nicknames :diskspace :ds)
(:export #:list-all-disks
#:list-all-disk-info
#:disk-space
#:disk-total-space
#:disk-free-space
#:disk-available-space
#:size-in-human-readable))
| null | https://raw.githubusercontent.com/muyinliu/cl-diskspace/2dce2d0387d58221c452bd76c7b9b7a7de81ef55/src/packages.lisp | lisp | packages.lisp
(defpackage #:cl-diskspace
(:use #:cl
#:cffi
#:cffi-grovel)
(:nicknames :diskspace :ds)
(:export #:list-all-disks
#:list-all-disk-info
#:disk-space
#:disk-total-space
#:disk-free-space
#:disk-available-space
#:size-in-human-readable))
|
|
fbd15e3a172052a880d452c32fcef2e7a17912536f135a74942cc72adf99cca0 | metabase/metabase | before_insert.clj | (ns macros.toucan2.tools.before-insert
(:require [macros.toucan2.common :as common]))
(defmacro define-before-insert
[model [instance-binding] & body]
`(do
~model
(fn [~(common/ignore-unused '&model)
~instance-binding]
~@body)))
| null | https://raw.githubusercontent.com/metabase/metabase/b34fae975cf6e3893f37209920561cf1acd94949/.clj-kondo/com.github.camsaul/toucan2/macros/toucan2/tools/before_insert.clj | clojure | (ns macros.toucan2.tools.before-insert
(:require [macros.toucan2.common :as common]))
(defmacro define-before-insert
[model [instance-binding] & body]
`(do
~model
(fn [~(common/ignore-unused '&model)
~instance-binding]
~@body)))
|
|
3e8d4d3250767e983c28e87a855a305a276aa6629f1390dca197bf35a14b749a | bscarlet/llvm-general | Diagnostic.hs | # LANGUAGE
TemplateHaskell ,
MultiParamTypeClasses
#
TemplateHaskell,
MultiParamTypeClasses
#-}
module LLVM.General.Internal.Diagnostic where
import LLVM.General.Prelude
import qualified LLVM.General.Internal.FFI.LLVMCTypes as FFI
import qualified LLVM.General.Internal.FFI.SMDiagnostic as FFI
import Control.Exception
import Foreign.Ptr
import LLVM.General.Diagnostic
import LLVM.General.Internal.Coding
import LLVM.General.Internal.String ()
genCodingInstance [t| DiagnosticKind |] ''FFI.DiagnosticKind [
(FFI.diagnosticKindError, ErrorKind),
(FFI.diagnosticKindWarning, WarningKind),
(FFI.diagnosticKindNote, NoteKind)
]
withSMDiagnostic :: (Ptr FFI.SMDiagnostic -> IO a) -> IO a
withSMDiagnostic = bracket FFI.createSMDiagnostic FFI.disposeSMDiagnostic
getDiagnostic :: Ptr FFI.SMDiagnostic -> IO Diagnostic
getDiagnostic p = do
l <- decodeM =<< FFI.getSMDiagnosticLineNo p
c <- decodeM =<< FFI.getSMDiagnosticColumnNo p
k <- decodeM =<< FFI.getSMDiagnosticKind p
f <- decodeM $ FFI.getSMDiagnosticFilename p
m <- decodeM $ FFI.getSMDiagnosticMessage p
lc <- decodeM $ FFI.getSMDiagnosticLineContents p
return $ Diagnostic {
lineNumber = l, columnNumber = c, diagnosticKind = k, filename = f, message = m, lineContents = lc
}
| null | https://raw.githubusercontent.com/bscarlet/llvm-general/61fd03639063283e7dc617698265cc883baf0eec/llvm-general/src/LLVM/General/Internal/Diagnostic.hs | haskell | # LANGUAGE
TemplateHaskell ,
MultiParamTypeClasses
#
TemplateHaskell,
MultiParamTypeClasses
#-}
module LLVM.General.Internal.Diagnostic where
import LLVM.General.Prelude
import qualified LLVM.General.Internal.FFI.LLVMCTypes as FFI
import qualified LLVM.General.Internal.FFI.SMDiagnostic as FFI
import Control.Exception
import Foreign.Ptr
import LLVM.General.Diagnostic
import LLVM.General.Internal.Coding
import LLVM.General.Internal.String ()
genCodingInstance [t| DiagnosticKind |] ''FFI.DiagnosticKind [
(FFI.diagnosticKindError, ErrorKind),
(FFI.diagnosticKindWarning, WarningKind),
(FFI.diagnosticKindNote, NoteKind)
]
withSMDiagnostic :: (Ptr FFI.SMDiagnostic -> IO a) -> IO a
withSMDiagnostic = bracket FFI.createSMDiagnostic FFI.disposeSMDiagnostic
getDiagnostic :: Ptr FFI.SMDiagnostic -> IO Diagnostic
getDiagnostic p = do
l <- decodeM =<< FFI.getSMDiagnosticLineNo p
c <- decodeM =<< FFI.getSMDiagnosticColumnNo p
k <- decodeM =<< FFI.getSMDiagnosticKind p
f <- decodeM $ FFI.getSMDiagnosticFilename p
m <- decodeM $ FFI.getSMDiagnosticMessage p
lc <- decodeM $ FFI.getSMDiagnosticLineContents p
return $ Diagnostic {
lineNumber = l, columnNumber = c, diagnosticKind = k, filename = f, message = m, lineContents = lc
}
|
|
32ce27cece74731bc68accc8cee266c54e120089f8e4bfeb66fb0dfb5c16c808 | mkoppmann/eselsohr | Article.hs | module Lib.Domain.Article
( Article (..)
, ArticleState (..)
, changeTitle
, markAsUnread
, markAsRead
, titleFromText
) where
import Data.Time.Clock (UTCTime)
import Prelude hiding
( id
, state
)
import qualified Lib.Domain.NonEmptyText as NET
import Lib.Domain.Error (AppErrorType)
import Lib.Domain.Id (Id)
import Lib.Domain.NonEmptyText (NonEmptyText)
import Lib.Domain.Uri (Uri)
data Article = Article
{ id :: !(Id Article)
, title :: !NonEmptyText
, uri :: !Uri
, state :: !ArticleState
, creation :: !UTCTime
}
deriving stock (Show)
instance Eq Article where
(==) (Article aId _ _ _ _) (Article bId _ _ _ _) = aId == bId
data ArticleState
= Unread
| Read
deriving stock (Eq, Read, Show)
changeTitle :: NonEmptyText -> Article -> Article
changeTitle newTitle art = art{title = newTitle}
markAsUnread :: Article -> Article
markAsUnread art = art{state = Unread}
markAsRead :: Article -> Article
markAsRead art = art{state = Read}
------------------------------------------------------------------------
-- Util
------------------------------------------------------------------------
titleFromText :: Text -> Either AppErrorType NonEmptyText
titleFromText title = NET.fromText title "Article title cannot be empty"
| null | https://raw.githubusercontent.com/mkoppmann/eselsohr/3bb8609199c1dfda94935e6dde0c46fc429de84e/src/Lib/Domain/Article.hs | haskell | ----------------------------------------------------------------------
Util
---------------------------------------------------------------------- | module Lib.Domain.Article
( Article (..)
, ArticleState (..)
, changeTitle
, markAsUnread
, markAsRead
, titleFromText
) where
import Data.Time.Clock (UTCTime)
import Prelude hiding
( id
, state
)
import qualified Lib.Domain.NonEmptyText as NET
import Lib.Domain.Error (AppErrorType)
import Lib.Domain.Id (Id)
import Lib.Domain.NonEmptyText (NonEmptyText)
import Lib.Domain.Uri (Uri)
data Article = Article
{ id :: !(Id Article)
, title :: !NonEmptyText
, uri :: !Uri
, state :: !ArticleState
, creation :: !UTCTime
}
deriving stock (Show)
instance Eq Article where
(==) (Article aId _ _ _ _) (Article bId _ _ _ _) = aId == bId
data ArticleState
= Unread
| Read
deriving stock (Eq, Read, Show)
changeTitle :: NonEmptyText -> Article -> Article
changeTitle newTitle art = art{title = newTitle}
markAsUnread :: Article -> Article
markAsUnread art = art{state = Unread}
markAsRead :: Article -> Article
markAsRead art = art{state = Read}
titleFromText :: Text -> Either AppErrorType NonEmptyText
titleFromText title = NET.fromText title "Article title cannot be empty"
|
3a0ca52cff46314a02a51f217752367250f6b9f24ff7bfb6f48b85c1184919dc | triffon/fp-2019-20 | 10--exists.rkt | #lang racket
(require rackunit rackunit/text-ui)
# # # Задача 10
Напишете функция ` ( exists ? pred ? a b ) ` ,
която проверява дали има цяло число в интервала [ a , b ] , за което предикатът ` pred ? ` е истина .
(define (exists? pred? a b)
void)
(run-tests (test-suite "exists? tests"
(check-true (exists? even? 1 5))
(check-true (exists? (lambda (n) (> n 10)) 1 11))
(check-false (exists? odd? 2 2))
(check-false (exists? (lambda (n) (> n 10)) 1 10))
Тук интервалът е празното множество , защото 5 > 1 .
А празното множество няма елементи , което означава че ` exists ? ` винаги връща лъжа за него .
(check-false (exists? number? 5 1)))
'verbose)
| null | https://raw.githubusercontent.com/triffon/fp-2019-20/7efb13ff4de3ea13baa2c5c59eb57341fac15641/exercises/computer-science-2/03--higher-order-functions--accumulate/10--exists.rkt | racket | #lang racket
(require rackunit rackunit/text-ui)
# # # Задача 10
Напишете функция ` ( exists ? pred ? a b ) ` ,
която проверява дали има цяло число в интервала [ a , b ] , за което предикатът ` pred ? ` е истина .
(define (exists? pred? a b)
void)
(run-tests (test-suite "exists? tests"
(check-true (exists? even? 1 5))
(check-true (exists? (lambda (n) (> n 10)) 1 11))
(check-false (exists? odd? 2 2))
(check-false (exists? (lambda (n) (> n 10)) 1 10))
Тук интервалът е празното множество , защото 5 > 1 .
А празното множество няма елементи , което означава че ` exists ? ` винаги връща лъжа за него .
(check-false (exists? number? 5 1)))
'verbose)
|
|
2baeb50f0d73203a22663f7db74f15db760bc099c1b72dfeaf86f394120d086b | alanz/ghc-exactprint | SH_Overlap2.hs | # LANGUAGE Trustworthy #
# LANGUAGE FlexibleInstances #
| Same as SH_Overlap1 , but SH_Overlap2_A is not imported as ' safe ' .
--
-- Question: Should the OI-check be enforced? Y, see reasoning in
-- `SH_Overlap4.hs` for why the Safe Haskell overlapping instance check should
-- be tied to Safe Haskell mode only, and not to safe imports.
module SH_Overlap2 where
import SH_Overlap2_A
instance
C [a] where
f _ = "[a]"
test :: String
test = f ([1,2,3,4] :: [Int])
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/SH_Overlap2.hs | haskell |
Question: Should the OI-check be enforced? Y, see reasoning in
`SH_Overlap4.hs` for why the Safe Haskell overlapping instance check should
be tied to Safe Haskell mode only, and not to safe imports. | # LANGUAGE Trustworthy #
# LANGUAGE FlexibleInstances #
| Same as SH_Overlap1 , but SH_Overlap2_A is not imported as ' safe ' .
module SH_Overlap2 where
import SH_Overlap2_A
instance
C [a] where
f _ = "[a]"
test :: String
test = f ([1,2,3,4] :: [Int])
|
9f7c10bf2c999658d179691b077cf11ef16fbd3807858fe51cf356446265c34b | finnishtransportagency/harja | bonukset_lomake.cljs | (ns harja.views.urakka.laadunseuranta.bonukset-lomake
"Bonuksien käsittely ja luonti"
(:require [reagent.core :as r]
[tuck.core :as tuck]
[harja.pvm :as pvm]
[harja.domain.laadunseuranta.sanktio :as sanktio-domain]
[harja.domain.yllapitokohde :as yllapitokohde-domain]
[harja.tiedot.navigaatio :as nav]
[harja.tiedot.urakka :as tiedot-urakka]
[harja.tiedot.istunto :as istunto]
[harja.tiedot.urakka.laadunseuranta :as laadunseuranta]
[harja.tiedot.urakka.laadunseuranta.bonukset :as tiedot]
[harja.tiedot.urakka.laadunseuranta.sanktiot :as tiedot-sanktiot]
[harja.ui.yleiset :as yleiset]
[harja.ui.lomake :as lomake]
[harja.ui.napit :as napit]
[harja.ui.liitteet :as liitteet]
[harja.ui.varmista-kayttajalta :as varmista-kayttajalta]))
(defn- hae-tpi-idlla
[tpi-id]
(some
#(when (= tpi-id (:tpi_id %))
%)
@tiedot-urakka/urakan-toimenpideinstanssit))
(defn bonus-lomake*
"MH-urakoidan ja ylläpitourakoiden yhteinen bonuslomake.
Huomioitavaa on, että ylläpidon urakoiden bonukset tallennetaankin oikeasti sanktioina, eikä bonuksina.
Ylläpidon urakoiden bonuslomakkeessa on myös muita pieniä poikkeuksia."
[sulje-fn lukutila? voi-muokata? e! app]
(let [{lomakkeen-tiedot :lomake :keys [uusi-liite voi-sulkea? liitteet-haettu?]} app
urakka-id (:id @nav/valittu-urakka)
urakan-alkuvuosi (-> nav/valittu-urakka deref :alkupvm pvm/vuosi)
laskutuskuukaudet (tiedot-sanktiot/pyorayta-laskutuskuukausi-valinnat)
Lista ylläpitokohteista ylläpitourakoiden
yllapitokohteet (conj
@laadunseuranta/urakan-yllapitokohteet-lomakkeelle
{:id nil})]
(when voi-sulkea? (e! (tiedot/->TyhjennaLomake sulje-fn)))
(when-not liitteet-haettu? (e! (tiedot/->HaeLiitteet)))
[lomake/lomake
{:otsikko "BONUKSEN TIEDOT"
:otsikko-elementti :h4
:ei-borderia? true
:vayla-tyyli? true
:tarkkaile-ulkopuolisia-muutoksia? true
:luokka "padding-16 taustavari-taso3"
:validoi-alussa? false
:voi-muokata? (and voi-muokata? (not lukutila?))
:muokkaa! #(e! (tiedot/->PaivitaLomaketta %))
:footer-fn (fn [bonus]
[:<>
[:span.nappiwrappi.row
[:div.col-xs-8 {:style {:padding-left "0"}}
(when-not lukutila?
[napit/yleinen-ensisijainen "Tallenna" #(e! (tiedot/->TallennaBonus))
{:disabled (not (empty? (::lomake/puuttuvat-pakolliset-kentat bonus)))}])]
[:div.col-xs-4 {:style (merge
{:text-align "end" :float "right"}
(when (not lukutila?)
{:display "contents"}))}
(when (and (not lukutila?) (:id lomakkeen-tiedot))
[napit/kielteinen "Poista" (fn [_]
(varmista-kayttajalta/varmista-kayttajalta
{:otsikko "Bonuksen poistaminen"
:sisalto "Haluatko varmasti poistaa bonuksen? Toimintoa ei voi perua."
:modal-luokka "varmistus-modal"
:hyvaksy "Poista"
:toiminto-fn #(e! (tiedot/->PoistaBonus))}))
{:luokka "oikealle"}])
[napit/peruuta "Sulje" #(e! (tiedot/->TyhjennaLomake sulje-fn))]]]])}
[(let [hae-tpin-tiedot (comp hae-tpi-idlla :toimenpideinstanssi)
tpi (hae-tpin-tiedot lomakkeen-tiedot)]
{:otsikko "Bonus"
Laji on . on sanktion laji .
:nimi :laji
:tyyppi :valinta
:pakollinen? true
Valitse ainoa , on vain yksi .
Esimerkiksi ylläpitourakoiden tapauksessa on saatavilla vain " yllapidon_bonus "
:valitse-ainoa? true
:valinnat (sanktio-domain/luo-kustannustyypit (:tyyppi @nav/valittu-urakka) (:id @istunto/kayttaja) tpi)
:valinta-nayta #(or (sanktio-domain/bonuslaji->teksti %) "- Valitse tyyppi -")
::lomake/col-luokka "col-xs-12"
:validoi [[:ei-tyhja "Valitse laji"]]})
(when @tiedot-urakka/yllapitourakka?
{:otsikko "Kohde" :tyyppi :valinta :nimi :yllapitokohde
:pakollinen? false :muokattava? (constantly voi-muokata?)
::lomake/col-luokka "col-xs-12"
:valinnat yllapitokohteet :jos-tyhja "Ei valittavia kohteita"
:valinta-nayta (fn [arvo voi-muokata?]
(if (:id arvo)
(yllapitokohde-domain/yllapitokohde-tekstina
arvo
{:osoite {:tr-numero (:tr-numero arvo)
:tr-alkuosa (:tr-alkuosa arvo)
:tr-alkuetaisyys (:tr-alkuetaisyys arvo)
:tr-loppuosa (:tr-loppuosa arvo)
:tr-loppuetaisyys (:tr-loppuetaisyys arvo)}})
(if (and voi-muokata? (not arvo))
"- Valitse kohde -"
(if (and voi-muokata? (nil? (:id arvo)))
"Ei liity kohteeseen"
""))))})
{:otsikko "Perustelu"
:nimi :lisatieto
:tyyppi :text
:pakollinen? true
::lomake/col-luokka "col-xs-12"
:validoi [[:ei-tyhja "Anna perustelu"]]}
{:otsikko "Kulun kohdistus"
:nimi :toimenpideinstanssi
:tyyppi :valinta
:pakollinen? true
:valitse-oletus? true
:valinta-arvo :tpi_id
:valinta-nayta #(if % (:tpi_nimi %) " - valitse toimenpide -")
MHU urakoiden toimenpideinstanssi on . ei
:valinnat (if (= :teiden-hoito (:tyyppi @nav/valittu-urakka))
(filter #(= "23150" (:t2_koodi %)) @tiedot-urakka/urakan-toimenpideinstanssit)
@tiedot-urakka/urakan-toimenpideinstanssit)
::lomake/col-luokka "col-xs-12"
Koska MHU urakoilla on , niin ei anneta käyttäjän vaihtaa , mutta alueurakoille se
:disabled? (if (= :teiden-hoito (:tyyppi @nav/valittu-urakka)) true false)}
(lomake/ryhma
{:rivi? true}
{:otsikko "Summa"
:nimi :summa
:tyyppi :euro
:vaadi-positiivinen-numero? true
:pakollinen? true
::lomake/col-luokka "col-xs-4"
:validoi [[:ei-tyhja "Anna summa"] [:rajattu-numero 0 999999999 "Anna arvo väliltä 0 - 999 999 999"]]}
(let [valinnat (when (and
(<= urakan-alkuvuosi 2020)
(= :asiakastyytyvaisyysbonus (:laji lomakkeen-tiedot)))
[(:indeksi @nav/valittu-urakka) nil])]
{:otsikko "Indeksi"
:nimi :indeksi
:tyyppi :valinta
:disabled? (nil? valinnat)
::lomake/col-luokka "col-xs-4"
:valinnat (or valinnat [nil])
:valinta-nayta #(or % "Ei indeksiä")}))
(lomake/ryhma
{:rivi? true}
{:otsikko "Käsitelty"
Hox : päätyy , : ksi
.
:nimi :kasittelyaika
:tyyppi :pvm
:pakollinen? true
::lomake/col-luokka "col-xs-4"
:validoi [[:ei-tyhja "Valitse päivämäärä"]]
:aseta (fn [rivi arvo]
(cond-> rivi
ole , niin asetetaan
pvm
(nil? (:laskutuskuukausi-komp-tiedot rivi))
(assoc :perintapvm arvo)
Tallennetaan aina valittu käsittelyaika :
true
(assoc :kasittelyaika arvo)))}
(if (and voi-muokata? (not lukutila?))
{:otsikko "Laskutuskuukausi"
HOX : Sanktion tapauksessa laskutuskuukausi ' perintapvm'-sarakkeeseen .
( erilliskustannus - taulu ) ei ole ,
johon tämä . Lisäksi , yllapidon_bonus sanktiona .
Yhteneväisyyden vuoksi käytetään perintapvm '
:nimi :perintapvm
:pakollinen? true
:tyyppi :komponentti
::lomake/col-luokka "col-xs-6"
:huomauta [[:urakan-aikana-ja-hoitokaudella]]
:komponentti (fn [{:keys [muokkaa-lomaketta data]}]
(let [perintapvm (get-in data [:perintapvm])]
[:<>
[yleiset/livi-pudotusvalikko
{:data-cy "koontilaskun-kk-dropdown"
:vayla-tyyli? true
:skrollattava? true
:pakollinen? true
:valinta (or
joko valittua laskutuskuukautta , tai
(-> data :laskutuskuukausi-komp-tiedot)
jos käyttäjä ei tehnyt / muuttanut valintaa , käytetään arvoa
(when perintapvm
(some #(when (and
(= (pvm/vuosi perintapvm)
(:vuosi %))
(= (pvm/kuukausi perintapvm)
(:kuukausi %))) %)
laskutuskuukaudet)))
:valitse-fn #(muokkaa-lomaketta
(assoc data
Tallennetaan tieto valinnasta erikseen , jotta
muualla lomakkeessa .
:laskutuskuukausi-komp-tiedot %
Varsinainen perintapvm poimitaan valitun laskutuskuukauden pvm - kentästä .
:perintapvm (:pvm %)))
:format-fn :teksti}
laskutuskuukaudet]
Piilotetaan teksti ylläpitourakoilta , koska niillä ei ole
(when (not @tiedot-urakka/yllapitourakka?)
[:div.small-caption.padding-4 "Näkyy laskutusyhteenvedolla"])]))}
{:otsikko "Laskutuskuukausi"
:nimi :perintapvm
:fmt (fn [pvm]
näytettävä laskutuskuukausi suoraan lomakkeen avaimesta
(when pvm
(some #(when (and
(= (pvm/vuosi pvm) (pvm/vuosi (:pvm %)))
(= (pvm/kuukausi pvm) (pvm/kuukausi (:pvm %)))) (:teksti %))
laskutuskuukaudet)))
:pakollinen? true
:tyyppi :pvm
::lomake/col-luokka "col-xs-6"}))
{:otsikko "Käsittelytapa"
:nimi :kasittelytapa :tyyppi :valinta
:pakollinen? true
::lomake/col-luokka "col-xs-12"
:valinnat sanktio-domain/kasittelytavat
:valinta-nayta #(or (sanktio-domain/kasittelytapa->teksti %) "- valitse käsittelytapa -")}
Piilota lukutilassa kokonaan , koska lukutilaa .
(if-not lukutila?
{:otsikko "Liitteet" :nimi :liitteet :kaariva-luokka "sanktioliite"
:tyyppi :komponentti
::lomake/col-luokka "col-xs-12"
:komponentti (fn [_]
[liitteet/liitteet-ja-lisays urakka-id (get-in app [:lomake :liitteet])
{:uusi-liite-atom (r/wrap uusi-liite
#(e! (tiedot/->LisaaLiite %)))
:uusi-liite-teksti "Lisää liite"
:salli-poistaa-lisatty-liite? true
:poista-lisatty-liite-fn #(e! (tiedot/->PoistaLisattyLiite))
:salli-poistaa-tallennettu-liite? true
:nayta-lisatyt-liitteet? false
:poista-tallennettu-liite-fn #(e! (tiedot/->PoistaTallennettuLiite %))}])}
{:otsikko "Liitteet" :nimi :liitteet :kaariva-luokka "sanktioliite"
:tyyppi :komponentti
::lomake/col-luokka "col-xs-12"
:komponentti (fn [_]
[:div
(if (and (get-in app [:lomake :liitteet])
(not (empty? (get-in app [:lomake :liitteet]))))
(doall
(for [l (get-in app [:lomake :liitteet])]
^{:key l}
[liitteet/liitetiedosto l {:salli-poisto? false
:nayta-koko? true}]))
"Ei liitettä")])})]
lomakkeen-tiedot]))
(defn bonus-lomake
[sivupaneeli-auki?-atom avattu-bonus tallennus-onnistui-fn]
(let [tallennus-onnistui-fn (if (fn? tallennus-onnistui-fn) tallennus-onnistui-fn (constantly nil))
sulje-fn (fn [tallennus-onnistui?]
(when tallennus-onnistui?
(tallennus-onnistui-fn))
(reset! sivupaneeli-auki?-atom false))
bonukset-tila (r/atom {:liitteet-haettu? false
:lomake (or
Muokataan vanhaa
(when (some? (:id avattu-bonus))
avattu-bonus)
tai alustetaan
(tiedot/uusi-bonus))})]
(fn [_ _ _ lukutila? voi-muokata?]
[:<>
#_[harja.ui.debug/debug @bonukset-tila]
[tuck/tuck bonukset-tila
(r/partial bonus-lomake* sulje-fn lukutila? voi-muokata?)]])))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/6666ecfc5ab49605006144ed0557a8dbdfe9f210/src/cljs/harja/views/urakka/laadunseuranta/bonukset_lomake.cljs | clojure | (ns harja.views.urakka.laadunseuranta.bonukset-lomake
"Bonuksien käsittely ja luonti"
(:require [reagent.core :as r]
[tuck.core :as tuck]
[harja.pvm :as pvm]
[harja.domain.laadunseuranta.sanktio :as sanktio-domain]
[harja.domain.yllapitokohde :as yllapitokohde-domain]
[harja.tiedot.navigaatio :as nav]
[harja.tiedot.urakka :as tiedot-urakka]
[harja.tiedot.istunto :as istunto]
[harja.tiedot.urakka.laadunseuranta :as laadunseuranta]
[harja.tiedot.urakka.laadunseuranta.bonukset :as tiedot]
[harja.tiedot.urakka.laadunseuranta.sanktiot :as tiedot-sanktiot]
[harja.ui.yleiset :as yleiset]
[harja.ui.lomake :as lomake]
[harja.ui.napit :as napit]
[harja.ui.liitteet :as liitteet]
[harja.ui.varmista-kayttajalta :as varmista-kayttajalta]))
(defn- hae-tpi-idlla
[tpi-id]
(some
#(when (= tpi-id (:tpi_id %))
%)
@tiedot-urakka/urakan-toimenpideinstanssit))
(defn bonus-lomake*
"MH-urakoidan ja ylläpitourakoiden yhteinen bonuslomake.
Huomioitavaa on, että ylläpidon urakoiden bonukset tallennetaankin oikeasti sanktioina, eikä bonuksina.
Ylläpidon urakoiden bonuslomakkeessa on myös muita pieniä poikkeuksia."
[sulje-fn lukutila? voi-muokata? e! app]
(let [{lomakkeen-tiedot :lomake :keys [uusi-liite voi-sulkea? liitteet-haettu?]} app
urakka-id (:id @nav/valittu-urakka)
urakan-alkuvuosi (-> nav/valittu-urakka deref :alkupvm pvm/vuosi)
laskutuskuukaudet (tiedot-sanktiot/pyorayta-laskutuskuukausi-valinnat)
Lista ylläpitokohteista ylläpitourakoiden
yllapitokohteet (conj
@laadunseuranta/urakan-yllapitokohteet-lomakkeelle
{:id nil})]
(when voi-sulkea? (e! (tiedot/->TyhjennaLomake sulje-fn)))
(when-not liitteet-haettu? (e! (tiedot/->HaeLiitteet)))
[lomake/lomake
{:otsikko "BONUKSEN TIEDOT"
:otsikko-elementti :h4
:ei-borderia? true
:vayla-tyyli? true
:tarkkaile-ulkopuolisia-muutoksia? true
:luokka "padding-16 taustavari-taso3"
:validoi-alussa? false
:voi-muokata? (and voi-muokata? (not lukutila?))
:muokkaa! #(e! (tiedot/->PaivitaLomaketta %))
:footer-fn (fn [bonus]
[:<>
[:span.nappiwrappi.row
[:div.col-xs-8 {:style {:padding-left "0"}}
(when-not lukutila?
[napit/yleinen-ensisijainen "Tallenna" #(e! (tiedot/->TallennaBonus))
{:disabled (not (empty? (::lomake/puuttuvat-pakolliset-kentat bonus)))}])]
[:div.col-xs-4 {:style (merge
{:text-align "end" :float "right"}
(when (not lukutila?)
{:display "contents"}))}
(when (and (not lukutila?) (:id lomakkeen-tiedot))
[napit/kielteinen "Poista" (fn [_]
(varmista-kayttajalta/varmista-kayttajalta
{:otsikko "Bonuksen poistaminen"
:sisalto "Haluatko varmasti poistaa bonuksen? Toimintoa ei voi perua."
:modal-luokka "varmistus-modal"
:hyvaksy "Poista"
:toiminto-fn #(e! (tiedot/->PoistaBonus))}))
{:luokka "oikealle"}])
[napit/peruuta "Sulje" #(e! (tiedot/->TyhjennaLomake sulje-fn))]]]])}
[(let [hae-tpin-tiedot (comp hae-tpi-idlla :toimenpideinstanssi)
tpi (hae-tpin-tiedot lomakkeen-tiedot)]
{:otsikko "Bonus"
Laji on . on sanktion laji .
:nimi :laji
:tyyppi :valinta
:pakollinen? true
Valitse ainoa , on vain yksi .
Esimerkiksi ylläpitourakoiden tapauksessa on saatavilla vain " yllapidon_bonus "
:valitse-ainoa? true
:valinnat (sanktio-domain/luo-kustannustyypit (:tyyppi @nav/valittu-urakka) (:id @istunto/kayttaja) tpi)
:valinta-nayta #(or (sanktio-domain/bonuslaji->teksti %) "- Valitse tyyppi -")
::lomake/col-luokka "col-xs-12"
:validoi [[:ei-tyhja "Valitse laji"]]})
(when @tiedot-urakka/yllapitourakka?
{:otsikko "Kohde" :tyyppi :valinta :nimi :yllapitokohde
:pakollinen? false :muokattava? (constantly voi-muokata?)
::lomake/col-luokka "col-xs-12"
:valinnat yllapitokohteet :jos-tyhja "Ei valittavia kohteita"
:valinta-nayta (fn [arvo voi-muokata?]
(if (:id arvo)
(yllapitokohde-domain/yllapitokohde-tekstina
arvo
{:osoite {:tr-numero (:tr-numero arvo)
:tr-alkuosa (:tr-alkuosa arvo)
:tr-alkuetaisyys (:tr-alkuetaisyys arvo)
:tr-loppuosa (:tr-loppuosa arvo)
:tr-loppuetaisyys (:tr-loppuetaisyys arvo)}})
(if (and voi-muokata? (not arvo))
"- Valitse kohde -"
(if (and voi-muokata? (nil? (:id arvo)))
"Ei liity kohteeseen"
""))))})
{:otsikko "Perustelu"
:nimi :lisatieto
:tyyppi :text
:pakollinen? true
::lomake/col-luokka "col-xs-12"
:validoi [[:ei-tyhja "Anna perustelu"]]}
{:otsikko "Kulun kohdistus"
:nimi :toimenpideinstanssi
:tyyppi :valinta
:pakollinen? true
:valitse-oletus? true
:valinta-arvo :tpi_id
:valinta-nayta #(if % (:tpi_nimi %) " - valitse toimenpide -")
MHU urakoiden toimenpideinstanssi on . ei
:valinnat (if (= :teiden-hoito (:tyyppi @nav/valittu-urakka))
(filter #(= "23150" (:t2_koodi %)) @tiedot-urakka/urakan-toimenpideinstanssit)
@tiedot-urakka/urakan-toimenpideinstanssit)
::lomake/col-luokka "col-xs-12"
Koska MHU urakoilla on , niin ei anneta käyttäjän vaihtaa , mutta alueurakoille se
:disabled? (if (= :teiden-hoito (:tyyppi @nav/valittu-urakka)) true false)}
(lomake/ryhma
{:rivi? true}
{:otsikko "Summa"
:nimi :summa
:tyyppi :euro
:vaadi-positiivinen-numero? true
:pakollinen? true
::lomake/col-luokka "col-xs-4"
:validoi [[:ei-tyhja "Anna summa"] [:rajattu-numero 0 999999999 "Anna arvo väliltä 0 - 999 999 999"]]}
(let [valinnat (when (and
(<= urakan-alkuvuosi 2020)
(= :asiakastyytyvaisyysbonus (:laji lomakkeen-tiedot)))
[(:indeksi @nav/valittu-urakka) nil])]
{:otsikko "Indeksi"
:nimi :indeksi
:tyyppi :valinta
:disabled? (nil? valinnat)
::lomake/col-luokka "col-xs-4"
:valinnat (or valinnat [nil])
:valinta-nayta #(or % "Ei indeksiä")}))
(lomake/ryhma
{:rivi? true}
{:otsikko "Käsitelty"
Hox : päätyy , : ksi
.
:nimi :kasittelyaika
:tyyppi :pvm
:pakollinen? true
::lomake/col-luokka "col-xs-4"
:validoi [[:ei-tyhja "Valitse päivämäärä"]]
:aseta (fn [rivi arvo]
(cond-> rivi
ole , niin asetetaan
pvm
(nil? (:laskutuskuukausi-komp-tiedot rivi))
(assoc :perintapvm arvo)
Tallennetaan aina valittu käsittelyaika :
true
(assoc :kasittelyaika arvo)))}
(if (and voi-muokata? (not lukutila?))
{:otsikko "Laskutuskuukausi"
HOX : Sanktion tapauksessa laskutuskuukausi ' perintapvm'-sarakkeeseen .
( erilliskustannus - taulu ) ei ole ,
johon tämä . Lisäksi , yllapidon_bonus sanktiona .
Yhteneväisyyden vuoksi käytetään perintapvm '
:nimi :perintapvm
:pakollinen? true
:tyyppi :komponentti
::lomake/col-luokka "col-xs-6"
:huomauta [[:urakan-aikana-ja-hoitokaudella]]
:komponentti (fn [{:keys [muokkaa-lomaketta data]}]
(let [perintapvm (get-in data [:perintapvm])]
[:<>
[yleiset/livi-pudotusvalikko
{:data-cy "koontilaskun-kk-dropdown"
:vayla-tyyli? true
:skrollattava? true
:pakollinen? true
:valinta (or
joko valittua laskutuskuukautta , tai
(-> data :laskutuskuukausi-komp-tiedot)
jos käyttäjä ei tehnyt / muuttanut valintaa , käytetään arvoa
(when perintapvm
(some #(when (and
(= (pvm/vuosi perintapvm)
(:vuosi %))
(= (pvm/kuukausi perintapvm)
(:kuukausi %))) %)
laskutuskuukaudet)))
:valitse-fn #(muokkaa-lomaketta
(assoc data
Tallennetaan tieto valinnasta erikseen , jotta
muualla lomakkeessa .
:laskutuskuukausi-komp-tiedot %
Varsinainen perintapvm poimitaan valitun laskutuskuukauden pvm - kentästä .
:perintapvm (:pvm %)))
:format-fn :teksti}
laskutuskuukaudet]
Piilotetaan teksti ylläpitourakoilta , koska niillä ei ole
(when (not @tiedot-urakka/yllapitourakka?)
[:div.small-caption.padding-4 "Näkyy laskutusyhteenvedolla"])]))}
{:otsikko "Laskutuskuukausi"
:nimi :perintapvm
:fmt (fn [pvm]
näytettävä laskutuskuukausi suoraan lomakkeen avaimesta
(when pvm
(some #(when (and
(= (pvm/vuosi pvm) (pvm/vuosi (:pvm %)))
(= (pvm/kuukausi pvm) (pvm/kuukausi (:pvm %)))) (:teksti %))
laskutuskuukaudet)))
:pakollinen? true
:tyyppi :pvm
::lomake/col-luokka "col-xs-6"}))
{:otsikko "Käsittelytapa"
:nimi :kasittelytapa :tyyppi :valinta
:pakollinen? true
::lomake/col-luokka "col-xs-12"
:valinnat sanktio-domain/kasittelytavat
:valinta-nayta #(or (sanktio-domain/kasittelytapa->teksti %) "- valitse käsittelytapa -")}
Piilota lukutilassa kokonaan , koska lukutilaa .
(if-not lukutila?
{:otsikko "Liitteet" :nimi :liitteet :kaariva-luokka "sanktioliite"
:tyyppi :komponentti
::lomake/col-luokka "col-xs-12"
:komponentti (fn [_]
[liitteet/liitteet-ja-lisays urakka-id (get-in app [:lomake :liitteet])
{:uusi-liite-atom (r/wrap uusi-liite
#(e! (tiedot/->LisaaLiite %)))
:uusi-liite-teksti "Lisää liite"
:salli-poistaa-lisatty-liite? true
:poista-lisatty-liite-fn #(e! (tiedot/->PoistaLisattyLiite))
:salli-poistaa-tallennettu-liite? true
:nayta-lisatyt-liitteet? false
:poista-tallennettu-liite-fn #(e! (tiedot/->PoistaTallennettuLiite %))}])}
{:otsikko "Liitteet" :nimi :liitteet :kaariva-luokka "sanktioliite"
:tyyppi :komponentti
::lomake/col-luokka "col-xs-12"
:komponentti (fn [_]
[:div
(if (and (get-in app [:lomake :liitteet])
(not (empty? (get-in app [:lomake :liitteet]))))
(doall
(for [l (get-in app [:lomake :liitteet])]
^{:key l}
[liitteet/liitetiedosto l {:salli-poisto? false
:nayta-koko? true}]))
"Ei liitettä")])})]
lomakkeen-tiedot]))
(defn bonus-lomake
[sivupaneeli-auki?-atom avattu-bonus tallennus-onnistui-fn]
(let [tallennus-onnistui-fn (if (fn? tallennus-onnistui-fn) tallennus-onnistui-fn (constantly nil))
sulje-fn (fn [tallennus-onnistui?]
(when tallennus-onnistui?
(tallennus-onnistui-fn))
(reset! sivupaneeli-auki?-atom false))
bonukset-tila (r/atom {:liitteet-haettu? false
:lomake (or
Muokataan vanhaa
(when (some? (:id avattu-bonus))
avattu-bonus)
tai alustetaan
(tiedot/uusi-bonus))})]
(fn [_ _ _ lukutila? voi-muokata?]
[:<>
#_[harja.ui.debug/debug @bonukset-tila]
[tuck/tuck bonukset-tila
(r/partial bonus-lomake* sulje-fn lukutila? voi-muokata?)]])))
|
|
918e53d6acea3249c0ea209cb0596d92fd0e421e1dcb793947da33a0f94bf7cb | input-output-hk/plutus-apps | V1.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
{-# LANGUAGE DerivingVia #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MonoLocalBinds #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Ledger.Tx.Orphans.V1 where
import Ledger.Scripts.Orphans ()
import Codec.Serialise (Serialise)
import Data.Aeson (FromJSON (parseJSON), FromJSONKey, ToJSON (toJSON), ToJSONKey)
import Data.Aeson qualified as JSON
import Data.Aeson.Extras qualified as JSON
import Ledger.Credential.Orphans ()
import Ledger.Address.Orphans ()
import Ledger.Builtins.Orphans ()
import Ledger.Value.Orphans ()
import Plutus.V1.Ledger.Api
import Plutus.V1.Ledger.Bytes qualified as Bytes
import Plutus.V1.Ledger.Tx
deriving newtype instance Serialise LedgerBytes
deriving anyclass instance FromJSONKey LedgerBytes
deriving anyclass instance ToJSONKey LedgerBytes
instance ToJSON LedgerBytes where
toJSON = JSON.String . JSON.encodeByteString . Bytes.bytes
instance FromJSON LedgerBytes where
parseJSON v = Bytes.fromBytes <$> JSON.decodeByteString v
deriving anyclass instance ToJSON RedeemerPtr
deriving anyclass instance FromJSON RedeemerPtr
deriving anyclass instance ToJSONKey RedeemerPtr
deriving anyclass instance FromJSONKey RedeemerPtr
deriving anyclass instance Serialise RedeemerPtr
deriving anyclass instance ToJSON ScriptTag
deriving anyclass instance FromJSON ScriptTag
deriving anyclass instance Serialise ScriptTag
deriving anyclass instance ToJSON TxIn
deriving anyclass instance FromJSON TxIn
deriving anyclass instance Serialise TxIn
deriving anyclass instance ToJSON TxOut
deriving anyclass instance FromJSON TxOut
deriving anyclass instance Serialise TxOut
deriving anyclass instance ToJSON TxInType
deriving anyclass instance FromJSON TxInType
deriving anyclass instance Serialise TxInType
deriving anyclass instance ToJSON TxOutRef
deriving anyclass instance FromJSON TxOutRef
deriving anyclass instance ToJSONKey TxOutRef
deriving anyclass instance FromJSONKey TxOutRef
deriving anyclass instance Serialise TxOutRef
deriving anyclass instance ToJSON TxId
deriving anyclass instance FromJSON TxId
deriving anyclass instance ToJSONKey TxId
deriving anyclass instance FromJSONKey TxId
deriving anyclass instance Serialise TxId
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/5ff40dafcdb07483442093efb4eaa39d12f34880/plutus-ledger/src/Ledger/Tx/Orphans/V1.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DerivingVia #
# LANGUAGE OverloadedStrings #
# LANGUAGE TemplateHaskell # | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MonoLocalBinds #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Ledger.Tx.Orphans.V1 where
import Ledger.Scripts.Orphans ()
import Codec.Serialise (Serialise)
import Data.Aeson (FromJSON (parseJSON), FromJSONKey, ToJSON (toJSON), ToJSONKey)
import Data.Aeson qualified as JSON
import Data.Aeson.Extras qualified as JSON
import Ledger.Credential.Orphans ()
import Ledger.Address.Orphans ()
import Ledger.Builtins.Orphans ()
import Ledger.Value.Orphans ()
import Plutus.V1.Ledger.Api
import Plutus.V1.Ledger.Bytes qualified as Bytes
import Plutus.V1.Ledger.Tx
deriving newtype instance Serialise LedgerBytes
deriving anyclass instance FromJSONKey LedgerBytes
deriving anyclass instance ToJSONKey LedgerBytes
instance ToJSON LedgerBytes where
toJSON = JSON.String . JSON.encodeByteString . Bytes.bytes
instance FromJSON LedgerBytes where
parseJSON v = Bytes.fromBytes <$> JSON.decodeByteString v
deriving anyclass instance ToJSON RedeemerPtr
deriving anyclass instance FromJSON RedeemerPtr
deriving anyclass instance ToJSONKey RedeemerPtr
deriving anyclass instance FromJSONKey RedeemerPtr
deriving anyclass instance Serialise RedeemerPtr
deriving anyclass instance ToJSON ScriptTag
deriving anyclass instance FromJSON ScriptTag
deriving anyclass instance Serialise ScriptTag
deriving anyclass instance ToJSON TxIn
deriving anyclass instance FromJSON TxIn
deriving anyclass instance Serialise TxIn
deriving anyclass instance ToJSON TxOut
deriving anyclass instance FromJSON TxOut
deriving anyclass instance Serialise TxOut
deriving anyclass instance ToJSON TxInType
deriving anyclass instance FromJSON TxInType
deriving anyclass instance Serialise TxInType
deriving anyclass instance ToJSON TxOutRef
deriving anyclass instance FromJSON TxOutRef
deriving anyclass instance ToJSONKey TxOutRef
deriving anyclass instance FromJSONKey TxOutRef
deriving anyclass instance Serialise TxOutRef
deriving anyclass instance ToJSON TxId
deriving anyclass instance FromJSON TxId
deriving anyclass instance ToJSONKey TxId
deriving anyclass instance FromJSONKey TxId
deriving anyclass instance Serialise TxId
|
6088c220250c9f0f80d0da90367a5b8fe58f9e2c58294531f6262ddeb7116db4 | ocharles/hs-quake-3 | RenderGraph.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE ExplicitNamespaces #
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
module RenderGraph
( RenderNode(..)
, type (|>)(..)
, Cull, CullOp(..), cull
, GLIO, glIO
, MultiplePasses, multiplePasses
, BlendMode, blendMode
, BindTexture, bindTexture
, SetUniform, RenderGraph.setUniform
, DepthFunc, depthFunc
, AlphaFunc, alphaFunc
, Viewport, viewport
, MonoidalMap(..)
, GLSLType(..)
) where
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Data.Bits
import Data.Coerce
import Data.Foldable (toList)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
import Data.Map (Map)
import qualified Data.Map as Map
import GLObjects
import Graphics.GL.Compatibility45
import Linear
-- | The class of types that act as rendering nodes - generally operations that
-- manipulate OpenGL state.
class RenderNode a m where
draw :: a -> m ()
instance Monad m => RenderNode () m where
draw = return
-- Composing render graphs (functor composition)
infixr 6 |>
newtype (g |> f) a = Compose { getCompose :: g (f a) }
deriving (Functor)
instance Monoid (g (f a)) => Monoid ((g |> f) a) where
mempty = Compose mempty
mappend (Compose a) (Compose b) = Compose (a `mappend` b)
instance (RenderNode (g (f a)) m, Monad m) => RenderNode ((g |> f) a) m where
draw (Compose f) = draw f
-- Monoidal maps
newtype MonoidalMap k a = MonoidalMap { getMonoidalMap :: Map k a }
instance Functor (MonoidalMap k) where
fmap f (MonoidalMap a) = MonoidalMap (fmap f a)
instance (Monoid a, Ord k) =>
Monoid (MonoidalMap k a) where
mempty = MonoidalMap Map.empty
mappend (MonoidalMap a) (MonoidalMap b) =
MonoidalMap (Map.unionWith mappend a b)
mconcat =
coerce . Map.unionsWith mappend . (coerce :: [MonoidalMap k a] -> [Map k a])
-- glCullFace
data CullOp = CullNothing | CullFace GLuint
deriving (Eq, Ord)
newtype Cull a = Cull (MonoidalMap CullOp a)
deriving (Functor, Monoid)
cull :: CullOp -> a -> Cull a
cull op a = Cull (MonoidalMap (Map.singleton op a))
instance (MonadIO m, RenderNode a m) =>
RenderNode (Cull a) m where
draw (Cull items) = do
Map.foldrWithKey
(\cullop children k -> do
case cullop of
CullNothing -> glDisable GL_CULL_FACE
CullFace f -> do
glEnable GL_CULL_FACE
glCullFace f
draw children
k)
(return ())
(getMonoidalMap items)
Do arbitrary IO . GL state transitions could be violated here !
newtype GLIO a = GLIO { runGLIO :: (IO (), a) }
deriving (Monoid)
instance (MonadIO m, RenderNode a m) => RenderNode (GLIO a) m where
draw (GLIO (io, child)) = do
liftIO io
draw child
glIO :: IO () -> a -> GLIO a
glIO io a = GLIO (io, a)
-- Multi-pass rendering
newtype MultiplePasses a = MultiplePasses (MonoidalIntMap a)
deriving (Functor, Monoid)
instance (Applicative m, RenderNode a m) =>
RenderNode (MultiplePasses a) m where
draw (MultiplePasses (MonoidalIntMap passes)) =
IM.foldr (\a k -> draw a *> k) (pure ()) passes
multiplePasses :: Foldable f => f a -> MultiplePasses a
multiplePasses =
MultiplePasses . MonoidalIntMap . IM.fromDistinctAscList . zip [0 ..] . toList
-- Set blend mode
newtype BlendMode a = BlendMode (MonoidalMap (GLuint, GLuint) a)
deriving (Functor, Monoid)
blendMode :: (GLuint, GLuint) -> a -> BlendMode a
blendMode srcDst = BlendMode . MonoidalMap . Map.singleton srcDst
instance (MonadIO m, RenderNode a m) =>
RenderNode (BlendMode a) m where
draw (BlendMode m) =
Map.foldrWithKey
(\(srcBlend, destBlend) child next -> do
glBlendFunc srcBlend destBlend
draw child
next)
(return ())
(getMonoidalMap m)
-- Texture units
newtype BindTexture a = BindTexture (MonoidalIntMap a)
deriving (Functor, Monoid)
bindTexture :: GLuint -> a -> BindTexture a
bindTexture t = BindTexture . MonoidalIntMap . IM.singleton (fromIntegral t)
instance (MonadIO m, RenderNode a m) =>
RenderNode (BindTexture a) m where
draw (BindTexture t) =
IM.foldrWithKey
(\texture0 m next -> do
glActiveTexture GL_TEXTURE0
glBindTexture GL_TEXTURE_2D (fromIntegral texture0)
draw m
next)
(return ())
(getMonoidalIntMap t)
-- Monoidal IntMaps
newtype MonoidalIntMap a = MonoidalIntMap { getMonoidalIntMap :: IntMap a }
deriving (Functor)
instance Monoid a => Monoid (MonoidalIntMap a) where
mempty = MonoidalIntMap IM.empty
mappend (MonoidalIntMap a) (MonoidalIntMap b) = MonoidalIntMap (IM.unionWith mappend a b)
mconcat = coerce . IM.unionsWith mappend . (coerce :: [MonoidalIntMap a] -> [IntMap a])
-- Set uniform parameters
newtype SetUniform uniformType a = SetUniform (MonoidalMap (String, uniformType) a)
deriving (Functor, Monoid)
setUniform :: String -> uniformType -> a -> SetUniform uniformType a
setUniform k !v = SetUniform . MonoidalMap . Map.singleton (k, v)
class GLSLType a where
setter :: UniformSetter a
instance GLSLType Bool where
setter = bool
instance GLSLType (M33 Float) where
setter = m33
instance (RenderNode a (ReaderT (x, Program) IO), GLSLType k) =>
RenderNode (SetUniform k a) (ReaderT (x, Program) IO) where
draw (SetUniform m) =
Map.foldrWithKey
(\(name, v) children next -> do
ReaderT $ \(_, program) -> GLObjects.setUniform setter program name v
draw children
next)
(return ())
(getMonoidalMap m)
-- Setting depth functions
newtype DepthFunc a = DepthFunc (MonoidalMap GLuint a)
deriving (Functor, Monoid)
depthFunc :: GLuint -> a -> DepthFunc a
depthFunc d = DepthFunc . MonoidalMap . Map.singleton d
instance (RenderNode a m, MonadIO m) =>
RenderNode (DepthFunc a) m where
draw (DepthFunc m) =
Map.foldrWithKey
(\d child next -> do
glDepthFunc d
draw child
next)
(return ())
(getMonoidalMap m)
-- Alpha testing
newtype AlphaFunc a = AlphaFunc (MonoidalMap (Maybe (GLenum, GLclampf)) a)
deriving (Functor, Monoid)
alphaFunc :: Maybe (GLuint, GLclampf) -> a -> AlphaFunc a
alphaFunc d = AlphaFunc . MonoidalMap . Map.singleton d
instance (RenderNode a m, MonadIO m) =>
RenderNode (AlphaFunc a) m where
draw (AlphaFunc m) =
Map.foldrWithKey
(\d child next -> do
case d of
Just (func, ref) -> do
glEnable GL_ALPHA_TEST
glAlphaFunc func ref
Nothing -> glDisable GL_ALPHA_TEST
draw child
next)
(return ())
(getMonoidalMap m)
-- View from a camera, generally the top-most node in rendering.
data Viewport a = Viewport
{ viewViewport :: (GLint, GLint, GLint, GLint)
, viewChild :: a
} deriving (Functor)
instance (RenderNode a m, MonadIO m) => RenderNode (Viewport a) m where
draw (Viewport (x, y, w, h) child) = do
liftIO $ do
glViewport x y w h
glClearColor 0 0 0 0
glClear (GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT)
draw child
viewport :: (GLint, GLint, GLint, GLint) -> a -> Viewport a
viewport = Viewport
| null | https://raw.githubusercontent.com/ocharles/hs-quake-3/655f6ce2b04c69f5e05c01cf57356132aa711589/RenderGraph.hs | haskell | # LANGUAGE BangPatterns #
| The class of types that act as rendering nodes - generally operations that
manipulate OpenGL state.
Composing render graphs (functor composition)
Monoidal maps
glCullFace
Multi-pass rendering
Set blend mode
Texture units
Monoidal IntMaps
Set uniform parameters
Setting depth functions
Alpha testing
View from a camera, generally the top-most node in rendering. | # LANGUAGE ExplicitNamespaces #
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
module RenderGraph
( RenderNode(..)
, type (|>)(..)
, Cull, CullOp(..), cull
, GLIO, glIO
, MultiplePasses, multiplePasses
, BlendMode, blendMode
, BindTexture, bindTexture
, SetUniform, RenderGraph.setUniform
, DepthFunc, depthFunc
, AlphaFunc, alphaFunc
, Viewport, viewport
, MonoidalMap(..)
, GLSLType(..)
) where
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Data.Bits
import Data.Coerce
import Data.Foldable (toList)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
import Data.Map (Map)
import qualified Data.Map as Map
import GLObjects
import Graphics.GL.Compatibility45
import Linear
class RenderNode a m where
draw :: a -> m ()
instance Monad m => RenderNode () m where
draw = return
infixr 6 |>
newtype (g |> f) a = Compose { getCompose :: g (f a) }
deriving (Functor)
instance Monoid (g (f a)) => Monoid ((g |> f) a) where
mempty = Compose mempty
mappend (Compose a) (Compose b) = Compose (a `mappend` b)
instance (RenderNode (g (f a)) m, Monad m) => RenderNode ((g |> f) a) m where
draw (Compose f) = draw f
newtype MonoidalMap k a = MonoidalMap { getMonoidalMap :: Map k a }
instance Functor (MonoidalMap k) where
fmap f (MonoidalMap a) = MonoidalMap (fmap f a)
instance (Monoid a, Ord k) =>
Monoid (MonoidalMap k a) where
mempty = MonoidalMap Map.empty
mappend (MonoidalMap a) (MonoidalMap b) =
MonoidalMap (Map.unionWith mappend a b)
mconcat =
coerce . Map.unionsWith mappend . (coerce :: [MonoidalMap k a] -> [Map k a])
data CullOp = CullNothing | CullFace GLuint
deriving (Eq, Ord)
newtype Cull a = Cull (MonoidalMap CullOp a)
deriving (Functor, Monoid)
cull :: CullOp -> a -> Cull a
cull op a = Cull (MonoidalMap (Map.singleton op a))
instance (MonadIO m, RenderNode a m) =>
RenderNode (Cull a) m where
draw (Cull items) = do
Map.foldrWithKey
(\cullop children k -> do
case cullop of
CullNothing -> glDisable GL_CULL_FACE
CullFace f -> do
glEnable GL_CULL_FACE
glCullFace f
draw children
k)
(return ())
(getMonoidalMap items)
Do arbitrary IO . GL state transitions could be violated here !
newtype GLIO a = GLIO { runGLIO :: (IO (), a) }
deriving (Monoid)
instance (MonadIO m, RenderNode a m) => RenderNode (GLIO a) m where
draw (GLIO (io, child)) = do
liftIO io
draw child
glIO :: IO () -> a -> GLIO a
glIO io a = GLIO (io, a)
newtype MultiplePasses a = MultiplePasses (MonoidalIntMap a)
deriving (Functor, Monoid)
instance (Applicative m, RenderNode a m) =>
RenderNode (MultiplePasses a) m where
draw (MultiplePasses (MonoidalIntMap passes)) =
IM.foldr (\a k -> draw a *> k) (pure ()) passes
multiplePasses :: Foldable f => f a -> MultiplePasses a
multiplePasses =
MultiplePasses . MonoidalIntMap . IM.fromDistinctAscList . zip [0 ..] . toList
newtype BlendMode a = BlendMode (MonoidalMap (GLuint, GLuint) a)
deriving (Functor, Monoid)
blendMode :: (GLuint, GLuint) -> a -> BlendMode a
blendMode srcDst = BlendMode . MonoidalMap . Map.singleton srcDst
instance (MonadIO m, RenderNode a m) =>
RenderNode (BlendMode a) m where
draw (BlendMode m) =
Map.foldrWithKey
(\(srcBlend, destBlend) child next -> do
glBlendFunc srcBlend destBlend
draw child
next)
(return ())
(getMonoidalMap m)
newtype BindTexture a = BindTexture (MonoidalIntMap a)
deriving (Functor, Monoid)
bindTexture :: GLuint -> a -> BindTexture a
bindTexture t = BindTexture . MonoidalIntMap . IM.singleton (fromIntegral t)
instance (MonadIO m, RenderNode a m) =>
RenderNode (BindTexture a) m where
draw (BindTexture t) =
IM.foldrWithKey
(\texture0 m next -> do
glActiveTexture GL_TEXTURE0
glBindTexture GL_TEXTURE_2D (fromIntegral texture0)
draw m
next)
(return ())
(getMonoidalIntMap t)
newtype MonoidalIntMap a = MonoidalIntMap { getMonoidalIntMap :: IntMap a }
deriving (Functor)
instance Monoid a => Monoid (MonoidalIntMap a) where
mempty = MonoidalIntMap IM.empty
mappend (MonoidalIntMap a) (MonoidalIntMap b) = MonoidalIntMap (IM.unionWith mappend a b)
mconcat = coerce . IM.unionsWith mappend . (coerce :: [MonoidalIntMap a] -> [IntMap a])
newtype SetUniform uniformType a = SetUniform (MonoidalMap (String, uniformType) a)
deriving (Functor, Monoid)
setUniform :: String -> uniformType -> a -> SetUniform uniformType a
setUniform k !v = SetUniform . MonoidalMap . Map.singleton (k, v)
class GLSLType a where
setter :: UniformSetter a
instance GLSLType Bool where
setter = bool
instance GLSLType (M33 Float) where
setter = m33
instance (RenderNode a (ReaderT (x, Program) IO), GLSLType k) =>
RenderNode (SetUniform k a) (ReaderT (x, Program) IO) where
draw (SetUniform m) =
Map.foldrWithKey
(\(name, v) children next -> do
ReaderT $ \(_, program) -> GLObjects.setUniform setter program name v
draw children
next)
(return ())
(getMonoidalMap m)
newtype DepthFunc a = DepthFunc (MonoidalMap GLuint a)
deriving (Functor, Monoid)
depthFunc :: GLuint -> a -> DepthFunc a
depthFunc d = DepthFunc . MonoidalMap . Map.singleton d
instance (RenderNode a m, MonadIO m) =>
RenderNode (DepthFunc a) m where
draw (DepthFunc m) =
Map.foldrWithKey
(\d child next -> do
glDepthFunc d
draw child
next)
(return ())
(getMonoidalMap m)
newtype AlphaFunc a = AlphaFunc (MonoidalMap (Maybe (GLenum, GLclampf)) a)
deriving (Functor, Monoid)
alphaFunc :: Maybe (GLuint, GLclampf) -> a -> AlphaFunc a
alphaFunc d = AlphaFunc . MonoidalMap . Map.singleton d
instance (RenderNode a m, MonadIO m) =>
RenderNode (AlphaFunc a) m where
draw (AlphaFunc m) =
Map.foldrWithKey
(\d child next -> do
case d of
Just (func, ref) -> do
glEnable GL_ALPHA_TEST
glAlphaFunc func ref
Nothing -> glDisable GL_ALPHA_TEST
draw child
next)
(return ())
(getMonoidalMap m)
data Viewport a = Viewport
{ viewViewport :: (GLint, GLint, GLint, GLint)
, viewChild :: a
} deriving (Functor)
instance (RenderNode a m, MonadIO m) => RenderNode (Viewport a) m where
draw (Viewport (x, y, w, h) child) = do
liftIO $ do
glViewport x y w h
glClearColor 0 0 0 0
glClear (GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT)
draw child
viewport :: (GLint, GLint, GLint, GLint) -> a -> Viewport a
viewport = Viewport
|
94093e8e4c1e3395dc62478c329d6a48bad6487657fc12d65f00fec70d614e83 | eduardoaguacate/Object-Oriented-Haskell | TypeChecker.hs | module TypeChecker where
import Data.Decimal
import DataTypes
import Text.Show.Pretty
import Control.Monad
import Control.Monad.State
import Control.Monad.Identity
import Control.Monad.Trans.Class (lift)
import Control.Concurrent
import Control.Monad.Except
import SymbolTable
import ClassSymbolTable
import Expression
import Data.List (sortBy,sort,intercalate)
import Data.Ord
import Data.Function (on)
import MemoryAllocator
import Data.Either.Combinators
import System.Exit
-- import qualified Data.Map.Strict as Map
import qualified Data.HashMap.Strict as Map
import System.Console.Pretty (Color (..), Style (..), bgColor, color,
style, supportsPretty)
import Data.List (intercalate, maximumBy, union)
import Data.Ord (comparing)
data TCError a = IdentifierDeclared Identifier a
| IdentifierNotDeclared Identifier
| ParentClassNotFound ClassIdentifier a
| TypeNotFound Type a
| BadConstructor ClassIdentifier ClassIdentifier a
| ClassDeclared ClassIdentifier a
| InvalidArrayAssignment a
| ConstructorOnlyClasses a
| GeneralError a
| BadReturns a
| ErrorInStatement a
| ScopeError a
| ErrorInFunctionCall a
| ExpressionNotBoolean a
| BadForRange Integer Integer
| BadExpression a
instance (Show a) => Show (TCError a) where
show err = case err of
(IdentifierDeclared id a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Identifier "
++ (color Red . style Bold $ id )
++ (color White . style Bold $ " was already declared \n")))
(IdentifierNotDeclared id) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Identifier "
++ (color Red . style Bold $ id )
++ (color White . style Bold $ " not declared in \n")))
(ParentClassNotFound classId a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Parent class was never declared "
++ (color Red . style Bold $ classId )
++ (color White . style Bold $ " in \n"))
++ (color Red . style Bold $ show $ a ))
(TypeNotFound typ a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Type not found "
++ (color Red . style Bold $ show $ typ )
++ (color White . style Bold $ " in \n"))
++ (color Red . style Bold $ show $ a ))
(BadConstructor classId constructor a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Constructor name "
++ (color Red . style Bold $ constructor )
++ (color White . style Bold $ " should be the same as class name \n"))
++ (color Red . style Bold $ show $ classId ))
(ClassDeclared classId a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Class "
++ (color Red . style Bold $ classId )
++ (color White . style Bold $ " was already declared \n")))
(InvalidArrayAssignment a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Invalid array assignment in \n"
++ (color Red . style Bold $ show $ a )))
(ConstructorOnlyClasses a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Constructors can only be used in classes in \n"
++ (color Red . style Bold $ show $ a )))
(GeneralError a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "in \n"
++ (color Red . style Bold $ show $ a )))
(BadReturns a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "There are some bad return statements in function "
++ (color Red . style Bold $ show $ a )))
(ErrorInStatement a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "in statement \n"
++ (color Red . style Bold $ show $ a )))
(ScopeError a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Out of scope in \n"
++ (color Red . style Bold $ show $ a )))
(ErrorInFunctionCall a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "in function call \n"
++ (color Red . style Bold $ show $ a )))
(ExpressionNotBoolean a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Was expecting a boolean expression in \n"
++ (color Red . style Bold $ show $ a )))
(BadForRange lower upper) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Invalid for range \n"
++ (color Red . style Bold $ show $ lower )
++ (color White . style Bold $ ".." )
++ (color Red . style Bold $ show $ upper )))
(BadExpression a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Bad expression in \n"
++ (color Red . style Bold $ show $ a )))
data TCState = TCState
{ tcSymTab :: SymbolTable,
tcClassSymTab :: ClassSymbolTable,
tcAncestors :: AncestorsMap
}
deriving (Show)
setTCState :: SymbolTable -> ClassSymbolTable -> AncestorsMap -> TCState
setTCState s c i = (TCState s c i)
getTCState :: TCState -> (SymbolTable,ClassSymbolTable,AncestorsMap)
getTCState (TCState s c i) = (s,c,i)
modifyTCState (val,newTCState) = do
modify $ \s -> newTCState
type TypeChecker α = StateT TCState (Except (TCError String)) α
type TC = TypeChecker ()
runTypeChecker f = runExcept.runStateT f
exitIfFailure state = do
whenLeft state (\e ->
do
putStrLn.show $ e
exitFailure
)
updatedSymTabOfClass :: ClassIdentifier -> TC
updatedSymTabOfClass classIdentifier =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let updatedSymTabOfClass = (Map.insert classIdentifier symTab classSymTab)
modify $ \s -> (s { tcClassSymTab = updatedSymTabOfClass})
Primero se priorizaran
updatedSymTabOfClassWithParent :: ClassIdentifier -> ClassIdentifier -> TC
updatedSymTabOfClassWithParent classIdentifier parentClassIdentifier =
do
tcState <- get
let (symTabOfCurrentClass,classSymTab,aMap) = getTCState tcState
case (Map.lookup parentClassIdentifier classSymTab) of
Just symTabOfParent ->
do
let symTabInherited = (Map.intersection symTabOfCurrentClass symTabOfParent)
let symTabUnique = (Map.difference symTabOfCurrentClass symTabOfParent)
let newSymTab = Map.fromList (((Map.toList symTabInherited)) ++ (Map.toList symTabUnique))
let updatedSymTabOfClass = (Map.insert classIdentifier newSymTab classSymTab)
-- modify $ \s -> (s { tcSymTab = newSymTab})
modify $ \s -> (s { tcClassSymTab = updatedSymTabOfClass})
Con esta función se empieza el analisis . requiere es Program , nodo raíz del árbol abstracto de sintaxis .
Con esta función se empieza el analisis semántico. Lo único que se requiere es Program, el
nodo raíz del árbol abstracto de sintaxis.
-}
startSemanticAnalysis :: Program -> IO ()
startSemanticAnalysis (Program classList functionList varsList (Block statements)) = do
do
Primero , se analizan las clases . El Map.empty que se manda es el mapa de herencias que se en la etapa
-- de análisis semántico.
let stateAfterClasses = runTypeChecker (analyzeClasses classList) (setTCState emptySymbolTable emptyClassSymbolTable (Map.empty))
exitIfFailure stateAfterClasses
Después , tabla clases .
let (_,classSymbolTable,aMap) = getTCState (snd (fromRight' stateAfterClasses))
Se corre con . output sera la tabla programa principal
pero con . Es importante notar que aquí ahora se utiliza la tabla clases obtenidas
en el paso anterior .
let stateAfterFunctions = runTypeChecker (analyzeFunctions functionList globalScope Nothing) (setTCState emptySymbolTable classSymbolTable aMap)
exitIfFailure stateAfterFunctions
let (symbolTableWithFuncs,_,_) = getTCState (snd (fromRight' stateAfterFunctions))
Se corre con . output sera la tabla programa principal
pero con
let stateAfterVariables = runTypeChecker (analyzeVariables varsList globalScope Nothing) (setTCState symbolTableWithFuncs classSymbolTable aMap)
exitIfFailure stateAfterVariables
let (symbolTableWithFuncsVars,_,_) = getTCState (snd (fromRight' stateAfterVariables))
let returnListInMain = getReturnStatements statements
if (length returnListInMain > 0) then do
putStrLn $ "There shouldn't be returns in main"
else
do
Por último , se analizan los estatutos encontrados en el bloque principal del programa
let stateAfterMain = runTypeChecker (analyzeStatements statements defScope) (setTCState symbolTableWithFuncsVars classSymbolTable aMap)
exitIfFailure stateAfterMain
let (symbolTableStatements,classSymbolTable,aMap) = getTCState (snd (fromRight' stateAfterMain))
Se pasa a la etapa de alocación de memoria
el nodo raíz con la tabla final ,
la tabla clases y
-- el mapa de herencias
startMemoryAllocation (Program classList functionList varsList (Block statements)) symbolTableStatements classSymbolTable aMap
deepFilter :: [(Identifier,Symbol)] -> Identifier -> [(Identifier,Symbol)]
deepFilter [] _ = []
deepFilter ((identifier,(SymbolFunction params p1 (Block statements) p2 p3 p4 symTabFunc)) : rest) identifierParent
| identifier == identifierParent = ( deepFilter rest identifierParent )
| otherwise = let filteredSym = (Map.fromList ( deepFilter (Map.toList symTabFunc) identifierParent ) )
in let newSymTab = [(identifier,(SymbolFunction params p1 (Block statements) p2 p3 p4 filteredSym))]
in newSymTab ++ ( deepFilter rest identifierParent )
deepFilter (sym : rest) identifierParent = [sym] ++ (deepFilter rest identifierParent)
getClassName :: Class -> ClassIdentifier
getClassName (ClassInheritance classIdentifier _ _) = classIdentifier
getClassName (ClassNormal classIdentifier _) = classIdentifier
Analyze classes regresa una tabla y . , significa que hubo errores , false , no hubo errores
analyzeClasses :: [Class] -> TC
analyzeClasses [] = do return ()
analyzeClasses (cl : classes) =
do
tcState <- get
let (_,classSymTab,aMap) = getTCState tcState
let classIdentifier = getClassName cl
if Map.member classIdentifier classSymTab
then lift $ throwError (ClassDeclared classIdentifier "")
else do
let classSymTabWithOwnClass = (Map.insert classIdentifier Map.empty classSymTab)
let classStateAfterBlock = runTypeChecker (analyzeClassBlock cl) (setTCState emptySymbolTable classSymTabWithOwnClass aMap)
whenLeft classStateAfterBlock (lift.throwError)
whenRight classStateAfterBlock (modifyTCState)
analyzeClass cl
analyzeClasses classes
analyzeClassBlock :: Class -> TC
Debido a que se está heredando , hay que meter la symbol table de la clase padre en
analyzeClassBlock (ClassInheritance classIdentifier parentClass classBlock) =
do
tcState <- get
let (symTabOfCurrentClass,classSymTab,aMap) = getTCState tcState
case (Map.lookup parentClass classSymTab) of
Just symTabOfClass ->
do
let newSymTabOfCurrentClass = (Map.union (Map.fromList (sortBy (compare `on` fst) (Map.toList symTabOfClass))) symTabOfCurrentClass)
modify $ \s -> (s { tcSymTab = newSymTabOfCurrentClass})
case (Map.lookup parentClass aMap) of
Just classAncestors -> do
let ancestorsForCurrentClass = [parentClass] ++ classAncestors
let newAncestorMap = (Map.insert classIdentifier ancestorsForCurrentClass aMap)
modify $ \s -> (s { tcAncestors = newAncestorMap})
analyzeMembersOfClassBlock classBlock classIdentifier globalScope
updatedSymTabOfClassWithParent classIdentifier parentClass
Nothing -> do
let s = (ClassInheritance classIdentifier parentClass classBlock)
lift $ throwError (ParentClassNotFound parentClass (show s))
analyzeClassBlock (ClassNormal classIdentifier classBlock) = do
tcState <- get
let (symTabOfCurrentClass,classSymTab,aMap) = getTCState tcState
let newAncestorMap = (Map.insert classIdentifier [] aMap)
modify $ \s -> (s { tcAncestors = newAncestorMap})
analyzeMembersOfClassBlock classBlock classIdentifier globalScope
updatedSymTabOfClass classIdentifier
analyzeMembersOfClassBlock :: ClassBlock -> ClassIdentifier -> Scope -> TC
analyzeMembersOfClassBlock (ClassBlockNoConstructor classMembers) classIdentifier scp = do
analyzeClassMembers classMembers classIdentifier scp
updatedSymTabOfClass classIdentifier
analyzeMembersOfClassBlock (ClassBlock classMembers (ClassConstructor classIdConstructor params block)) classIdentifier scp =
do
if (classIdConstructor /= classIdentifier)
then do
lift $ throwError (BadConstructor classIdentifier classIdConstructor "")
else
do
analyzeClassMembers classMembers classIdentifier scp
analyzeFunction (Function (classIdentifier ++ "_constructor") TypeFuncReturnNothing params block) scp (Just True)
updatedSymTabOfClass classIdentifier
analyzeClassMembers :: [ClassMember] -> ClassIdentifier -> Scope -> TC
analyzeClassMembers [] _ _ = return ()
analyzeClassMembers (cm : cms) classIdentifier scp =
do
analyzeClassMember cm classIdentifier scp
updatedSymTabOfClass classIdentifier
analyzeClassMembers cms classIdentifier scp
updatedSymTabOfClass classIdentifier
analyzeClassMember :: ClassMember -> ClassIdentifier -> Scope -> TC
analyzeClassMember (ClassMemberAttribute (ClassAttributePublic variable)) classIdentifier scp = analyzeVariable variable scp (Just True)
analyzeClassMember (ClassMemberAttribute (ClassAttributePrivate variable)) classIdentifier scp = analyzeVariable variable scp (Just False)
analyzeClassMember (ClassMemberFunction (ClassFunctionPublic function)) classIdentifier scp = analyzeFunction function scp (Just True)
analyzeClassMember (ClassMemberFunction (ClassFunctionPrivate function)) classIdentifier scp = analyzeFunction function scp (Just False)
analyzeClass :: Class -> TC
analyzeClass (ClassInheritance subClass parentClass classBlock) =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (ClassInheritance subClass parentClass classBlock)
if Map.member parentClass classSymTab
then do
updatedSymTabOfClassWithParent subClass parentClass
let newClassSymTable = Map.insert -- , entonces
-- modify $ \s -> (s { tcClassSymTab = newClassSymTable})
Si el parent class no es miembro , entonces error , no clase no declarada
analyzeClass (ClassNormal classIdentifier classBlock) = do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (ClassNormal classIdentifier classBlock)
let newClassSymTable = Map.insert classIdentifier symTab classSymTab
modify $ \s -> (s { tcClassSymTab = newClassSymTable})
-- if Map.member classIdentifier classSymTab
-- then lift $ throwError (ClassDeclared classIdentifier (show s))
-- else
-- do
let newClassSymTable = Map.insert
-- modify $ \s -> (s { tcClassSymTab = newClassSymTable})
analyzeFunctions :: [Function] -> Scope -> Maybe Bool -> TC
analyzeFunctions [] _ _ = return ()
analyzeFunctions (func : funcs) scp isFuncPublic = do
analyzeFunction func scp isFuncPublic
analyzeFunctions funcs scp isFuncPublic
analyzeVariables :: [Variable] -> Scope -> Maybe Bool -> TC
analyzeVariables [] _ _ = return ()
analyzeVariables (var : vars) scp isVarPublic = do
analyzeVariable var scp isVarPublic
analyzeVariables vars scp isVarPublic
analyzeVariable :: Variable -> Scope -> Maybe Bool -> TC
analyzeVariable (VariableNoAssignment dataType identifiers) scp isVarPublic =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (VariableNoAssignment dataType identifiers)
existe ese tipo
if (checkTypeExistance dataType classSymTab)
then insertIdentifiers identifiers (SymbolVar {dataType = dataType, scope = scp, isPublic = isVarPublic})
Tipo no existe
analyzeVariable (VariableAssignmentLiteralOrVariable dataType identifier literalOrVariable) scp isVarPublic =
En esta parte el tipo este declarado , el literal or variable exista y que la asignacion sea correcta
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (VariableAssignmentLiteralOrVariable dataType identifier literalOrVariable)
existe ese tipo
if (checkTypeExistance dataType classSymTab) && (checkLiteralOrVariableInSymbolTable scp literalOrVariable symTab) && (checkDataTypes scp dataType literalOrVariable symTab aMap)
then insertInSymbolTable identifier (SymbolVar {dataType = dataType, scope = scp, isPublic = isVarPublic})
else lift $ throwError (GeneralError (show s))
analyzeVariable (VariableAssignment1D dataType identifier literalOrVariables) scp isVarPublic =
En esta parte lista de asignaciones concuerde con el tipo de dato declarado
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (VariableAssignment1D dataType identifier literalOrVariables)
case dataType of
TypePrimitive _ (("[",size,"]") : []) ->
makeCheckFor1DAssignment size symTab classSymTab s aMap
TypeClassId _ (("[",size,"]") : []) ->
makeCheckFor1DAssignment size symTab classSymTab s aMap
_ -> lift $ throwError (InvalidArrayAssignment (show s))
where
makeCheckFor1DAssignment size symTab classSymTab s aMap = if (checkTypeExistance dataType classSymTab)
&& (checkLiteralOrVariablesAndDataTypes scp dataType literalOrVariables symTab aMap)
&& ((length literalOrVariables) <= fromIntegral size)
then insertInSymbolTable identifier (SymbolVar {dataType = dataType, scope = scp, isPublic = isVarPublic})
else lift $ throwError (GeneralError (show s))
analyzeVariable (VariableAssignment2D dataType identifier listOfLiteralOrVariables) scp isVarPublic =
En esta parte lista de asignaciones concuerde con el tipo de dato declarado
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (VariableAssignment2D dataType identifier listOfLiteralOrVariables)
case dataType of
TypePrimitive _ (("[",sizeRows,"]") : ("[",sizeCols,"]") : []) ->
makeCheckFor2DAssignment sizeRows sizeCols symTab classSymTab s aMap
TypeClassId _ (("[",sizeRows,"]") : ("[",sizeCols,"]") : []) ->
makeCheckFor2DAssignment sizeRows sizeCols symTab classSymTab s aMap
_ -> lift $ throwError (InvalidArrayAssignment (show s))
where
makeCheckFor2DAssignment sizeRows sizeCols symTab classSymTab s aMap= if (checkTypeExistance dataType classSymTab) &&
(checkLiteralOrVariablesAndDataTypes2D scp dataType listOfLiteralOrVariables symTab aMap)
checamos que sea el numero
&& ((getLongestList listOfLiteralOrVariables) <= fromIntegral sizeCols)
then insertInSymbolTable identifier (SymbolVar {dataType = dataType, scope = scp, isPublic = isVarPublic})
else lift $ throwError (GeneralError (show s))
getLongestList :: [[LiteralOrVariable]] -> Int
getLongestList [] = 0
getLongestList (x : xs) = max (length x) (getLongestList xs)
analyzeVariable (VariableAssignmentObject dataType identifier (ObjectCreation classIdentifier params)) scp isVarPublic =
En esta parte lista de asignaciones concuerde con el tipo de dato declarado
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (VariableAssignmentObject dataType identifier (ObjectCreation classIdentifier params))
case dataType of
TypePrimitive _ _ -> lift $ throwError (ConstructorOnlyClasses (show s))
Checamos si el constructor es del mismo tipo que la clase
TypeClassId classIdentifierDecl [] -> do
if ((doesClassDeriveFromClass classIdentifierDecl (TypeClassId classIdentifier []) aMap) || (classIdentifierDecl == classIdentifier))
Checamos los parametros que se mandan con los del constructor
&& (checkIfParamsAreCorrect scp params classIdentifier symTab classSymTab aMap)
then insertInSymbolTable identifier (SymbolVar {dataType = dataType, scope = scp, isPublic = isVarPublic})
else lift $ throwError (GeneralError (show s))
analyzeVariable var _ _ = lift $ throwError (GeneralError (show var))
filterFuncs :: Symbol -> Bool
filterFuncs (SymbolFunction _ _ _ _ _ _ _) = False
filterFuncs _ = False
isReturnStatement :: Statement -> Bool
isReturnStatement (ReturnStatement ret) = True
isReturnStatement _ = False
analyzeFunction :: Function -> Scope -> Maybe Bool -> TC
analyzeFunction (Function identifier (TypeFuncReturnPrimitive primitive arrayDimension) params (Block statements)) scp isPublic =
do
tcState <- get
let (symTab',classSymTab,aMap) = getTCState tcState
let symTabWithParamsState = runTypeChecker (analyzeFuncParams params) (setTCState emptySymbolTable classSymTab aMap)
whenLeft symTabWithParamsState (lift.throwError)
whenRight classStateAfterBlock
let (newFuncSymTab,_,_) = getTCState (snd (fromRight' symTabWithParamsState))
let ( symTab',classSymTab , aMap ) = getTCState tcState
let s = (Function identifier (TypeFuncReturnPrimitive primitive arrayDimension) params (Block statements))
if not ( Map.member identifier symTab ) then -- Esto se comenta para que se override de las funciones
if ((Map.size (Map.intersection symTab' newFuncSymTab)) /= 0) then lift $ throwError (GeneralError (show s))
else do
let symTab = (Map.fromList (deepFilter (Map.toList symTab') identifier))
let symTabFuncWithOwnFunc = Map.insert identifier (SymbolFunction {returnType = (Just (TypePrimitive primitive arrayDimension)), scope = scp, body = (Block []), shouldReturn = True ,isPublic = isPublic, symbolTable = newFuncSymTab, params = params}) symTab
let newSymTabForFunc = (Map.union (Map.union symTabFuncWithOwnFunc symTab) newFuncSymTab)
-- modify $ \s -> (s { tcSymTab = newSymTabForFunc})
let symTabWithStatementsState = runTypeChecker (analyzeStatements statements scp) (setTCState newSymTabForFunc classSymTab aMap)
whenLeft symTabWithStatementsState (lift.throwError)
let (symTabFuncFinished,_,_) = getTCState (snd (fromRight' symTabWithStatementsState))
let ( , _ , _ ) = getTCState tcState
let isLastStatementReturn = isReturnStatement (last $ statements)
let updatedSymTabFunc = Map.insert identifier (SymbolFunction {returnType = (Just (TypePrimitive primitive arrayDimension)), scope = scp, body = (Block statements), shouldReturn = True ,isPublic = isPublic, symbolTable = (Map.filterWithKey (\k _ -> k /= identifier) symTabFuncFinished), params = params}) symTab
if (areReturnTypesOk isLastStatementReturn scp (TypePrimitive primitive arrayDimension) statements updatedSymTabFunc symTabFuncFinished classSymTab aMap)
then
modify $ \s -> (s { tcSymTab = updatedSymTabFunc } )
else lift $ throwError (BadReturns identifier)
analyzeFunction (Function identifier (TypeFuncReturnClassId classIdentifier arrayDimension) params (Block statements)) scp isPublic =
do
tcState <- get
let (symTab',classSymTab,aMap) = getTCState tcState
let symTabWithParamsState = runTypeChecker (analyzeFuncParams params) (setTCState emptySymbolTable classSymTab aMap)
whenLeft symTabWithParamsState (lift.throwError)
whenRight classStateAfterBlock
let (newFuncSymTab,_,_) = getTCState (snd (fromRight' symTabWithParamsState))
let ( symTab',classSymTab , aMap ) = getTCState tcState
let s = (Function identifier (TypeFuncReturnClassId classIdentifier arrayDimension) params (Block statements))
if not ( Map.member identifier symTab ) then -- Esto se comenta para que se override de las funciones
if ((Map.size (Map.intersection symTab' newFuncSymTab)) /= 0) then lift $ throwError (GeneralError (show s))
else do
let symTab = (Map.fromList (deepFilter (Map.toList symTab') identifier))
let symTabFuncWithOwnFunc = Map.insert identifier (SymbolFunction {returnType = (Just (TypeClassId classIdentifier arrayDimension)), scope = scp, body = (Block []), shouldReturn = True ,isPublic = isPublic, symbolTable = newFuncSymTab, params = params}) symTab
let newSymTabForFunc = (Map.union (Map.union symTabFuncWithOwnFunc symTab) newFuncSymTab)
-- modify $ \s -> (s { tcSymTab = newSymTabForFunc})
let symTabWithStatementsState = runTypeChecker (analyzeStatements statements scp) (setTCState newSymTabForFunc classSymTab aMap)
whenLeft symTabWithStatementsState (lift.throwError)
let (symTabFuncFinished,_,_) = getTCState (snd (fromRight' symTabWithStatementsState))
let ( , _ , _ ) = getTCState tcState
let isLastStatementReturn = isReturnStatement (last $ statements)
let updatedSymTabFunc = Map.insert identifier (SymbolFunction {returnType = (Just (TypeClassId classIdentifier arrayDimension)), scope = scp, body = (Block statements), shouldReturn = True ,isPublic = isPublic, symbolTable = (Map.filterWithKey (\k _ -> k /= identifier) symTabFuncFinished), params = params}) symTab
if (areReturnTypesOk isLastStatementReturn scp (TypeClassId classIdentifier arrayDimension) statements updatedSymTabFunc symTabFuncFinished classSymTab aMap)
then
modify $ \s -> (s { tcSymTab = updatedSymTabFunc } )
else lift $ throwError (BadReturns identifier)
Como no regresa nada , no hay que buscar que regrese algo
analyzeFunction (Function identifier (TypeFuncReturnNothing) params (Block statements)) scp isPublic =
if not ( Map.member identifier symTab ) -- Esto se comenta para que se override de las funciones
do
tcState <- get
let (symTab',classSymTab,aMap) = getTCState tcState
let symTabWithParamsState = runTypeChecker (analyzeFuncParams params) (setTCState emptySymbolTable classSymTab aMap)
whenLeft symTabWithParamsState (lift.throwError)
whenRight classStateAfterBlock
let (newFuncSymTab,_,_) = getTCState (snd (fromRight' symTabWithParamsState))
let ( symTab',classSymTab , aMap ) = getTCState tcState
let s = (Function identifier (TypeFuncReturnNothing) params (Block statements))
if not ( Map.member identifier symTab ) then -- Esto se comenta para que se override de las funciones
if ( ((Map.size (Map.intersection symTab' newFuncSymTab)) /= 0) || (length (getReturnStatements statements)) > 0) then lift $ throwError (GeneralError (show s))
else do
let symTab = (Map.fromList (deepFilter (Map.toList symTab') identifier))
let symTabFuncWithOwnFunc = Map.insert identifier (SymbolFunction {returnType = Nothing, scope = scp, body = (Block []), shouldReturn = True ,isPublic = isPublic, symbolTable = newFuncSymTab, params = params}) symTab
let newSymTabForFunc = (Map.union (Map.union symTabFuncWithOwnFunc symTab) newFuncSymTab)
-- modify $ \s -> (s { tcSymTab = newSymTabForFunc})
let symTabWithStatementsState = runTypeChecker (analyzeStatements statements scp) (setTCState newSymTabForFunc classSymTab aMap)
whenLeft symTabWithStatementsState (lift.throwError)
let (symTabFuncFinished,_,_) = getTCState (snd (fromRight' symTabWithStatementsState))
let ( , _ , _ ) = getTCState tcState
let updatedSymTabFunc = Map.insert identifier (SymbolFunction {returnType = Nothing, scope = scp, body = (Block statements), shouldReturn = True ,isPublic = isPublic, symbolTable = (Map.filterWithKey (\k _ -> k /= identifier) symTabFuncFinished), params = params}) symTab
modify $ \s -> (s { tcSymTab = updatedSymTabFunc } )
areReturnTypesOk :: Bool -> Scope -> Type -> [Statement] -> SymbolTable -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Bool
areReturnTypesOk isThereAReturnStatement _ _ [] _ _ _ _ = isThereAReturnStatement
areReturnTypesOk isThereAReturnStatement scp funcRetType ((ReturnStatement ret) : []) symTab ownFuncSymTab classTab aMap =
checkCorrectReturnTypes scp funcRetType ret symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType ((ConditionStatement (If _ (Block statements))) : []) symTab ownFuncSymTab classTab aMap =
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statements symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType ((ConditionStatement (IfElse _ (Block statements) (Block statementsElse))) : []) symTab ownFuncSymTab classTab aMap =
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statements symTab ownFuncSymTab classTab aMap &&
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statementsElse symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType ((CaseStatement (Case expressionToMatch expAndBlock otherwiseStatements)) : []) symTab ownFuncSymTab classTab aMap =
(foldl (\bool f -> (bool && (areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType (snd f) symTab ownFuncSymTab classTab aMap))) True expAndBlock ) &&
(areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType otherwiseStatements symTab ownFuncSymTab classTab aMap)
areReturnTypesOk isThereAReturnStatement scp funcRetType ((ConditionStatement (If _ (Block statements))) : sts) symTab ownFuncSymTab classTab aMap =
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statements symTab ownFuncSymTab classTab aMap &&
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType sts symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType ((ConditionStatement (IfElse _ (Block statements) (Block statementsElse))) : sts) symTab ownFuncSymTab classTab aMap =
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statements symTab ownFuncSymTab classTab aMap &&
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statementsElse symTab ownFuncSymTab classTab aMap &&
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType sts symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType ((CaseStatement (Case expressionToMatch expAndBlock otherwiseStatements)) : sts) symTab ownFuncSymTab classTab aMap =
(foldl (\bool f -> (bool && (areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType (snd f) symTab ownFuncSymTab classTab aMap))) True expAndBlock ) &&
(areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType otherwiseStatements symTab ownFuncSymTab classTab aMap)
&& areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType sts symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType (_ : sts) symTab ownFuncSymTab classTab aMap = areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType sts symTab ownFuncSymTab classTab aMap
returns que , inclusive si estan en statements anidados
getReturnStatements :: [Statement] -> [Return]
getReturnStatements [] = []
getReturnStatements ((ReturnStatement returnExp) : sts) = (returnExp) : (getReturnStatements sts)
getReturnStatements ((ConditionStatement (If _ (Block statements))) : sts) = (getReturnStatements statements) ++ (getReturnStatements sts)
getReturnStatements ((ConditionStatement (IfElse _ (Block statements) (Block statementsElse))) : sts) = (getReturnStatements statements) ++ (getReturnStatements statementsElse) ++ (getReturnStatements sts)
getReturnStatements ((CaseStatement (Case expressionToMatch expAndBlock otherwiseStatements)) : sts) = (foldl (\rets f -> (rets ++ (getReturnStatements (snd f)))) [] expAndBlock ) ++ (getReturnStatements otherwiseStatements) ++ (getReturnStatements sts)
getReturnStatements ((CycleStatement (CycleWhile (While _ (Block statements)))) : sts) = (getReturnStatements statements) ++ (getReturnStatements sts)
getReturnStatements ((CycleStatement (CycleFor (For _ _ (Block statements)))) : sts) = (getReturnStatements statements) ++ (getReturnStatements sts)
getReturnStatements (_ : sts) = (getReturnStatements sts)
analyzeFuncParams :: [(Type,Identifier)] -> TC
analyzeFuncParams [] = return ()
analyzeFuncParams ((dataType,identifier) : rest) =
do
analyzeVariable ((VariableNoAssignment dataType [identifier])) globalScope Nothing
analyzeFuncParams rest
El tipo de regreso de una funcion solo puede ser un elemento atomico !
checkCorrectReturnTypes :: Scope -> Type -> Return -> SymbolTable -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Bool
checkCorrectReturnTypes scp dataType (ReturnExp expression) symTab ownFuncSymTab classTab aMap =
case (preProcessExpression scp expression (Map.union symTab ownFuncSymTab) classTab aMap) of
Just (TypePrimitive prim arrayDim) -> (TypePrimitive prim arrayDim) == dataType
Just (TypeClassId classId arrayDim) -> case dataType of
(TypeClassId parentClassId arrayDim2) -> (arrayDim == arrayDim2) && ((doesClassDeriveFromClass classId dataType aMap) || ((TypeClassId parentClassId arrayDim2) == (TypeClassId classId arrayDim)))
_ -> False
_ -> False
Checamos aqui que la constructor
checkIfParamsAreCorrect :: Scope -> [Params] -> ClassIdentifier -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Bool
checkIfParamsAreCorrect scp sendingParams classIdentifier symTab classTab aMap =
case (Map.lookup classIdentifier classTab) of
Just symbolTableOfClass ->
case (Map.lookup (classIdentifier ++ "_constructor") symbolTableOfClass) of
Just (symbolFunc) -> (compareListOfTypesWithFuncCall scp (map (\f -> fst f) (params symbolFunc)) sendingParams symTab classTab aMap)
Nothing -> False
Nothing -> False
analyzeStatements :: [Statement] -> Scope -> TC
analyzeStatements [] _ = return ()
analyzeStatements (st : sts) scp = do
analyzeStatement st scp
analyzeStatements sts scp
analyzeStatement :: Statement -> Scope -> TC
analyzeStatement (AssignStatement assignment) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
if (isAssignmentOk assignment scp symTab classSymTab aMap)
then return ()
else lift $ throwError (ErrorInStatement (show assignment))
analyzeStatement (DisplayStatement displays) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
if (analyzeDisplays displays symTab classSymTab aMap)
then return ()
else lift $ throwError (ErrorInStatement (show displays))
where
analyzeDisplays [] _ _ _ = True
analyzeDisplays (disp : disps) symTab classSymTab aMap =
analyzeDisplay disp scp symTab classSymTab aMap
&& analyzeDisplays disps symTab classSymTab aMap
analyzeStatement (ReadStatement (Reading identifier)) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive _ []) varScp _) ->
if varScp >= scp then
return ()
else lift $ throwError (ScopeError identifier)
_ -> lift $ throwError (IdentifierNotDeclared identifier)
analyzeStatement (DPMStatement assignment) scp = analyzeStatement (AssignStatement assignment) scp
analyzeStatement (FunctionCallStatement functionCall) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
if (analyzeFunctionCall functionCall scp symTab classSymTab aMap)
then return ()
else lift $ throwError (ErrorInFunctionCall (show functionCall))
analyzeStatement (VariableStatement var) scp = analyzeVariable var scp Nothing
analyzeStatement (ConditionStatement (If expression (Block statements))) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (expressionTypeChecker scp expression symTab classSymTab aMap) of
Si la expresión del if ,
Right (TypePrimitive PrimitiveBool []) -> analyzeStatements statements (scp - 1)
De lo contrario , no se en el if
_ -> lift $ throwError (ExpressionNotBoolean (show expression))
analyzeStatement (ConditionStatement (IfElse expression (Block statements) (Block statements2))) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (expressionTypeChecker scp expression symTab classSymTab aMap) of
Si la expresión del if ,
Right (TypePrimitive PrimitiveBool []) ->
do
analyzeStatements statements (scp - 1)
analyzeStatements statements2 (scp - 1)
De lo contrario , no se en el if
_ -> lift $ throwError (ExpressionNotBoolean (show expression))
analyzeStatement (CaseStatement (Case expressionToMatch expAndBlock otherwiseStatements)) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (expressionTypeChecker scp expressionToMatch symTab classSymTab aMap) of
Right dataTypeToMatch ->
do
analyzeCases scp expAndBlock dataTypeToMatch
analyzeStatements otherwiseStatements (scp - 1)
Left err -> lift $ throwError (GeneralError (show err))
analyzeStatement (CycleStatement (CycleWhile (While expression (Block statements)))) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (expressionTypeChecker scp expression symTab classSymTab aMap) of
Right (TypePrimitive PrimitiveBool []) -> analyzeStatements statements (scp - 1)
_ -> lift $ throwError (ExpressionNotBoolean (show expression))
analyzeStatement (CycleStatement (CycleFor (For lowerRange greaterRange (Block statements)))) scp =
if (greaterRange >= lowerRange)
then analyzeStatements statements (scp - 1)
else lift $ throwError (BadForRange lowerRange greaterRange)
analyzeStatement (CycleStatement (CycleForVar statements)) scp = analyzeStatements statements scp
analyzeStatement (ReturnStatement (ReturnFunctionCall functionCall)) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let isFuncCallOk = analyzeFunctionCall functionCall scp symTab classSymTab aMap
if (isFuncCallOk) then return ()
else lift $ throwError (ErrorInFunctionCall (show functionCall))
analyzeStatement (ReturnStatement (ReturnExp expression)) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just expType -> return ()
Nothing -> lift $ throwError (BadExpression (show expression))
analyzeCases :: Scope -> [(Expression,[Statement])] -> Type -> TC
analyzeCases scp [] _ = return ()
analyzeCases scp ((e,statements) : es) dataTypeToMatch =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (expressionTypeChecker scp e symTab classSymTab aMap) of
Right dataTypeOfExp ->
if (dataTypeOfExp == dataTypeToMatch) then
do
analyzeStatements statements (scp - 1)
analyzeCases scp es dataTypeToMatch
else lift $ throwError (GeneralError "Case head expression is different from expressions to match")
Left _ -> lift $ throwError (GeneralError "Case with a bad formed expression")
analyzeDisplay :: Display -> Scope -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Bool
analyzeDisplay (DisplayLiteralOrVariable (VarIdentifier identifier) _) scp symTab classTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim _) varScp _) ->
varScp >= scp
Just (SymbolVar (TypeClassId classIdentifier _) varScp _) ->
varScp >= scp
_ -> False
Podemos desplegar primitivos sin problemas
analyzeDisplay (DisplayLiteralOrVariable _ _) scp symTab classTab aMap = True
analyzeDisplay (DisplayObjMem (ObjectMember objectIdentifier attrIdentifier) _) scp symTab classTab aMap =
case (Map.lookup objectIdentifier symTab) of
Just (SymbolVar (TypeClassId classIdentifier _) objScp _) ->
if (objScp >= scp)
then
case (Map.lookup classIdentifier classTab) of
Just symbolTableOfClass ->
case (Map.lookup attrIdentifier symbolTableOfClass) of
Si y solo si es publico el atributo ,
Just (SymbolVar attrDataType attrScp (Just True)) ->
True
_ -> False
_ -> False
else False
_ -> False
analyzeDisplay (DisplayFunctionCall functionCall _) scp symTab classTab aMap =
analyzeFunctionCall functionCall scp symTab classTab aMap
analyzeDisplay (DisplayVarArrayAccess identifier ((ArrayAccessExpression expressionIndex) : []) _ ) scp symTab classTab aMap=
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",size,"]") : [])) varScp _ ) ->
if (varScp >= scp) then
let typeIndexExp = (preProcessExpression scp expressionIndex symTab classTab aMap)
in case typeIndexExp of
Just (TypePrimitive PrimitiveInteger _) ->
True
Just (TypePrimitive PrimitiveInt _) ->
True
_ -> False
else False
Just (SymbolVar (TypeClassId classIdentifier (("[",size,"]") : [])) varScp _ ) ->
if (varScp >= scp) then
let typeIndexExp = (preProcessExpression scp expressionIndex symTab classTab aMap)
in case typeIndexExp of
Just (TypePrimitive PrimitiveInteger _) ->
True
Just (TypePrimitive PrimitiveInt _) ->
True
_ -> False
else False
_ -> False
analyzeDisplay (DisplayVarArrayAccess identifier ((ArrayAccessExpression innerExpRow) : (ArrayAccessExpression innerExpCol) : []) _ ) scp symTab classTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",rows,"]") : ("[",columns,"]") : [])) varScp _ ) ->
if (varScp >= scp)
then
let typeRowExp = (expressionTypeChecker scp innerExpRow symTab classTab aMap)
typeColExp = (expressionTypeChecker scp innerExpCol symTab classTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) -> True
Right (TypePrimitive PrimitiveInteger []) -> True
_ -> False
else False
else False
Just (SymbolVar (TypeClassId classIdentifier (("[",rows,"]") : ("[",cols,"]") : [])) varScp _ ) ->
if (varScp >= scp)
then
let typeRowExp = (expressionTypeChecker scp innerExpRow symTab classTab aMap)
typeColExp = (expressionTypeChecker scp innerExpCol symTab classTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) -> True
Right (TypePrimitive PrimitiveInteger []) -> True
_ -> False
else False
else False
_ -> False
isAssignmentOk :: Assignment -> Scope -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Bool
isAssignmentOk (AssignmentExpression identifier expression) scp symTab classSymTab aMap = case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim accessExpression) varScp _) ->
Si el scope de esta variable es mayor , accederlo
if (varScp >= scp)
then
let typeExp = (preProcessExpression scp expression symTab classSymTab aMap)
in case typeExp of
Just typeUnwrapped ->
typeUnwrapped == (TypePrimitive prim accessExpression)
_ -> False
else False
Just (SymbolVar (TypeClassId classIdentifier dimOfIdentifier) varScp _) ->
Si el scope de esta variable es mayor , accederlo
if (varScp >= scp)
then let typeExp = (preProcessExpression scp expression symTab classSymTab aMap)
in case typeExp of
Just (TypeClassId classId dimExpression) ->
(dimOfIdentifier == dimExpression) && ((doesClassDeriveFromClass classId (TypeClassId classIdentifier dimOfIdentifier) aMap) || (classIdentifier == classId ))
_ -> False
else False
_ -> False
isAssignmentOk (AssignmentObjectMember identifier (ObjectMember objectIdentifier attrIdentifier)) scp symTab classSymTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar dataType varScp _) ->
if (varScp >= scp)
then
case (Map.lookup objectIdentifier symTab) of
Just (SymbolVar (TypeClassId classIdentifier []) objScp _) ->
if (objScp >= scp)
then
case (Map.lookup classIdentifier classSymTab) of
Just symbolTableOfClass ->
case (Map.lookup attrIdentifier symbolTableOfClass) of
Si y solo si es publico el atributo ,
Just (SymbolVar attrDataType attrScp (Just True)) ->
case attrDataType of
(TypeClassId subClass arrayDim) ->
case dataType of
(TypeClassId parentClass arrayDimPClass) ->
(arrayDim == arrayDimPClass) && ((doesClassDeriveFromClass subClass dataType aMap) || ((TypeClassId subClass arrayDim) == dataType))
_ -> False
dt -> (dt == dataType)
_ -> False
_ -> False
else False
_ -> False
else False
_ -> False
isAssignmentOk (AssignmentObjectMemberExpression (ObjectMember objectIdentifier attrIdentifier) expression) scp symTab classSymTab aMap =
case (Map.lookup objectIdentifier symTab) of
Just (SymbolVar (TypeClassId classIdentifier _) objScp _) ->
if (objScp >= scp)
then
case (Map.lookup classIdentifier classSymTab) of
Just symbolTableOfClass ->
case (Map.lookup attrIdentifier symbolTableOfClass) of
Si y solo si es publico el atributo ,
Just (SymbolVar attrDataType attrScp (Just True)) ->
let typeExp = (preProcessExpression scp expression symTab classSymTab aMap)
in case typeExp of
Just (TypePrimitive prim arrayAccessExp) ->
(TypePrimitive prim arrayAccessExp) == attrDataType
Just (TypeClassId subClass arrayAccessExp) ->
case attrDataType of
(TypeClassId parentClass arrayDim) ->
(arrayDim == arrayAccessExp) && ((doesClassDeriveFromClass subClass (TypeClassId parentClass arrayDim) aMap) || (TypeClassId subClass arrayAccessExp) == (TypeClassId parentClass arrayDim) )
_ -> False
_ -> False
_ -> False
_ -> False
else False
_ -> False
isAssignmentOk (AssignmentArrayExpression identifier ((ArrayAccessExpression innerExp) : []) expression) scp symTab classSymTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",size,"]") : [])) varScp _) ->
if (varScp >= scp)
then
let typeIndexExp = (expressionTypeChecker scp innerExp symTab classSymTab aMap)
in case typeIndexExp of
Right (TypePrimitive PrimitiveInt []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypePrimitive primExp _) -> primExp == prim
_ -> False
Right (TypePrimitive PrimitiveInteger []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypePrimitive primExp _) -> primExp == prim
_ -> False
_ -> False
else False
Just (SymbolVar (TypeClassId classIdentifier (("[",size,"]") : [])) varScp _) ->
if (varScp >= scp)
then
let typeIndexExp = (expressionTypeChecker scp innerExp symTab classSymTab aMap)
in case typeIndexExp of
Right (TypePrimitive PrimitiveInt []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypeClassId classId []) -> (doesClassDeriveFromClass classId (TypeClassId classIdentifier (("[",size,"]") : [])) aMap)
|| classId == classIdentifier
_ -> False
Right (TypePrimitive PrimitiveInteger []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypeClassId classId []) -> (doesClassDeriveFromClass classId (TypeClassId classIdentifier (("[",size,"]") : [])) aMap)
|| classId == classIdentifier
_ -> False
_ -> False
else False
_ -> False
isAssignmentOk (AssignmentArrayExpression identifier ((ArrayAccessExpression innerExpRow) : (ArrayAccessExpression innerExpCol) : []) expression) scp symTab classSymTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",sizeRows,"]") : ("[",sizeCols,"]") : [])) varScp _) ->
if (varScp >= scp)
then
let typeRowExp = (expressionTypeChecker scp innerExpRow symTab classSymTab aMap)
typeColExp = (expressionTypeChecker scp innerExpCol symTab classSymTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypePrimitive primAssignment []) ->
primAssignment == prim
_ -> False
Right (TypePrimitive PrimitiveInteger []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypePrimitive primAssignment []) ->
primAssignment == prim
_ -> False
_ -> False
else False
else False
Just (SymbolVar (TypeClassId classIdentifier (("[",sizeRows,"]") : ("[",sizeCols,"]") : [])) varScp _) ->
if (varScp >= scp)
then
let typeRowExp = (expressionTypeChecker scp innerExpRow symTab classSymTab aMap)
typeColExp = (expressionTypeChecker scp innerExpCol symTab classSymTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypeClassId classIdAssignment []) ->
(doesClassDeriveFromClass classIdAssignment (TypeClassId classIdentifier (("[",sizeRows,"]") : ("[",sizeCols,"]") : [])) aMap) || classIdentifier == classIdAssignment
_ -> False
Right (TypePrimitive PrimitiveInteger []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypeClassId classIdAssignment []) ->
(doesClassDeriveFromClass classIdAssignment (TypeClassId classIdentifier (("[",sizeRows,"]") : ("[",sizeCols,"]") : [])) aMap) || classIdentifier == classIdAssignment
_ -> False
_ -> False
else False
else False
_ -> False
isAssignmentOk _ _ _ _ _ = False
insertIdentifiers :: [Identifier] -> Symbol -> TC
insertIdentifiers [] _ = return ()
insertIdentifiers (identifier : ids) symbol =
do
insertInSymbolTable identifier symbol
insertIdentifiers ids symbol
insertInSymbolTable :: Identifier -> Symbol -> TC
insertInSymbolTable identifier symbol =
Si esta ese identificador en la tabla , entonces regreso error
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
if Map.member identifier symTab
then lift $ throwError (IdentifierDeclared identifier "")
else do
let newSymTab = (Map.insert identifier symbol symTab)
modify $ \s -> (s {tcSymTab = newSymTab})
una lista de literales o variables sea del tipo receptor
checkLiteralOrVariablesAndDataTypes :: Scope -> Type -> [LiteralOrVariable] -> SymbolTable -> AncestorsMap -> Bool
checkLiteralOrVariablesAndDataTypes _ _ [] _ _ = True
checkLiteralOrVariablesAndDataTypes scp dataType (litVar : litVars) symTab aMap =
if (checkLiteralOrVariableInSymbolTable scp litVar symTab) && (checkArrayAssignment scp dataType litVar symTab aMap)
then checkLiteralOrVariablesAndDataTypes scp dataType litVars symTab aMap
Alguna literal o variable asignada no existe , o bien , esta asignando no concuerda con la declaracion
checkLiteralOrVariableInSymbolTable :: Scope -> LiteralOrVariable -> SymbolTable -> Bool
checkLiteralOrVariableInSymbolTable scp (VarIdentifier identifier) symTab =
case (Map.lookup identifier symTab) of
Just (SymbolVar _ varScp _) ->
varScp >= scp
_ -> False
var identifier , entonces regresamos true , o sea , sin error
checkTypeExistance :: Type -> ClassSymbolTable -> Bool
checkTypeExistance (TypeClassId classIdentifier _) classTab =
case (Map.lookup classIdentifier classTab) of
Just _ -> True -- Si existe esa clase
El identificador que se esta asignando no esta en ningun
checkTypeExistance _ _ = True -- Todos lo demas regresa true
checkLiteralOrVariablesAndDataTypes2D :: Scope -> Type -> [[LiteralOrVariable]] -> SymbolTable -> AncestorsMap -> Bool
checkLiteralOrVariablesAndDataTypes2D _ _ [] _ _ = True
checkLiteralOrVariablesAndDataTypes2D scp dataType (listOfLitVars : rest) symTab aMap =
if (checkLiteralOrVariablesAndDataTypes scp dataType listOfLitVars symTab aMap)
then checkLiteralOrVariablesAndDataTypes2D scp dataType rest symTab aMap
Alguna literal o variable asignada no existe , o bien , esta asignando no concuerda con la declaracion
Podriamos necesitar preprocesar una expresion en busqueda de un literal or variable que sea clase
preProcessExpression :: Scope -> Expression -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Maybe Type
preProcessExpression scp (ExpressionLitVar (VarIdentifier identifier)) symTab _ aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypeClassId classIdentifier accessExpression) varScp _)
| varScp >= scp ->
Just (TypeClassId classIdentifier accessExpression)
| otherwise -> Nothing
Just (SymbolVar (TypePrimitive prim accessExpression) varScp _)
| varScp >= scp ->
Just (TypePrimitive prim accessExpression)
| otherwise -> Nothing
_ -> Nothing
preProcessExpression scp (ExpressionFuncCall functionCall) symTab classSymTab aMap = if (analyzeFunctionCall functionCall scp symTab classSymTab aMap) then
functionCallType functionCall scp symTab classSymTab
else Nothing
preProcessExpression scp (ExpressionVarArray identifier ((ArrayAccessExpression expressionIndex) : [])) symTab classSymTab aMap =
-- Checamos que sea una matriz ese identificador
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",size,"]") : []) ) varScp _)
| varScp >= scp ->
let typeIndexExp = (expressionTypeChecker scp expressionIndex symTab classSymTab aMap)
in case typeIndexExp of
Right (TypePrimitive PrimitiveInt []) -> Just (TypePrimitive prim [])
Right (TypePrimitive PrimitiveInteger []) -> Just (TypePrimitive prim [])
_ -> Nothing
| otherwise -> Nothing
Just (SymbolVar (TypeClassId classIdentifier (("[",size,"]") : []) ) varScp _)
| varScp >= scp ->
let typeIndexExp = (expressionTypeChecker scp expressionIndex symTab classSymTab aMap)
in case typeIndexExp of
Right (TypePrimitive PrimitiveInt []) -> Just (TypeClassId classIdentifier [])
Right (TypePrimitive PrimitiveInteger []) -> Just (TypeClassId classIdentifier [])
_ -> Nothing
| otherwise -> Nothing
_ -> Nothing
preProcessExpression scp (ExpressionVarArray identifier ((ArrayAccessExpression rowExp) : (ArrayAccessExpression colExp) : [])) symTab classSymTab aMap =
-- Checamos que sea una matriz ese identificador
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",rows,"]") : ("[",cols,"]") : [])) varScp _)
| varScp >= scp ->
let typeRowExp = (expressionTypeChecker scp rowExp symTab classSymTab aMap)
typeColExp = (expressionTypeChecker scp colExp symTab classSymTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) -> Just (TypePrimitive prim [])
Right (TypePrimitive PrimitiveInteger []) -> Just (TypePrimitive prim [])
_ -> Nothing
else Nothing
| otherwise -> Nothing
Just (SymbolVar (TypeClassId classIdentifier (("[",rows,"]") : ("[",cols,"]") : [])) varScp _)
| varScp >= scp ->
let typeRowExp = (expressionTypeChecker scp rowExp symTab classSymTab aMap)
typeColExp = (expressionTypeChecker scp colExp symTab classSymTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) -> Just (TypeClassId classIdentifier [])
Right (TypePrimitive PrimitiveInteger []) -> Just (TypeClassId classIdentifier [])
_ -> Nothing
else Nothing
| otherwise -> Nothing
_ -> Nothing
preProcessExpression scp expression symTab classSymTab aMap = case (expressionTypeChecker scp expression symTab classSymTab aMap) of
Right dtExp -> (Just dtExp)
_ -> Nothing
| null | https://raw.githubusercontent.com/eduardoaguacate/Object-Oriented-Haskell/2f6192ca98513886cbedffa7429c87c44ffdcf05/Analysis/TypeChecker.hs | haskell | import qualified Data.Map.Strict as Map
modify $ \s -> (s { tcSymTab = newSymTab})
de análisis semántico.
el mapa de herencias
, entonces
modify $ \s -> (s { tcClassSymTab = newClassSymTable})
if Map.member classIdentifier classSymTab
then lift $ throwError (ClassDeclared classIdentifier (show s))
else
do
modify $ \s -> (s { tcClassSymTab = newClassSymTable})
Esto se comenta para que se override de las funciones
modify $ \s -> (s { tcSymTab = newSymTabForFunc})
Esto se comenta para que se override de las funciones
modify $ \s -> (s { tcSymTab = newSymTabForFunc})
Esto se comenta para que se override de las funciones
Esto se comenta para que se override de las funciones
modify $ \s -> (s { tcSymTab = newSymTabForFunc})
Si existe esa clase
Todos lo demas regresa true
Checamos que sea una matriz ese identificador
Checamos que sea una matriz ese identificador | module TypeChecker where
import Data.Decimal
import DataTypes
import Text.Show.Pretty
import Control.Monad
import Control.Monad.State
import Control.Monad.Identity
import Control.Monad.Trans.Class (lift)
import Control.Concurrent
import Control.Monad.Except
import SymbolTable
import ClassSymbolTable
import Expression
import Data.List (sortBy,sort,intercalate)
import Data.Ord
import Data.Function (on)
import MemoryAllocator
import Data.Either.Combinators
import System.Exit
import qualified Data.HashMap.Strict as Map
import System.Console.Pretty (Color (..), Style (..), bgColor, color,
style, supportsPretty)
import Data.List (intercalate, maximumBy, union)
import Data.Ord (comparing)
data TCError a = IdentifierDeclared Identifier a
| IdentifierNotDeclared Identifier
| ParentClassNotFound ClassIdentifier a
| TypeNotFound Type a
| BadConstructor ClassIdentifier ClassIdentifier a
| ClassDeclared ClassIdentifier a
| InvalidArrayAssignment a
| ConstructorOnlyClasses a
| GeneralError a
| BadReturns a
| ErrorInStatement a
| ScopeError a
| ErrorInFunctionCall a
| ExpressionNotBoolean a
| BadForRange Integer Integer
| BadExpression a
instance (Show a) => Show (TCError a) where
show err = case err of
(IdentifierDeclared id a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Identifier "
++ (color Red . style Bold $ id )
++ (color White . style Bold $ " was already declared \n")))
(IdentifierNotDeclared id) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Identifier "
++ (color Red . style Bold $ id )
++ (color White . style Bold $ " not declared in \n")))
(ParentClassNotFound classId a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Parent class was never declared "
++ (color Red . style Bold $ classId )
++ (color White . style Bold $ " in \n"))
++ (color Red . style Bold $ show $ a ))
(TypeNotFound typ a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Type not found "
++ (color Red . style Bold $ show $ typ )
++ (color White . style Bold $ " in \n"))
++ (color Red . style Bold $ show $ a ))
(BadConstructor classId constructor a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Constructor name "
++ (color Red . style Bold $ constructor )
++ (color White . style Bold $ " should be the same as class name \n"))
++ (color Red . style Bold $ show $ classId ))
(ClassDeclared classId a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Class "
++ (color Red . style Bold $ classId )
++ (color White . style Bold $ " was already declared \n")))
(InvalidArrayAssignment a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Invalid array assignment in \n"
++ (color Red . style Bold $ show $ a )))
(ConstructorOnlyClasses a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Constructors can only be used in classes in \n"
++ (color Red . style Bold $ show $ a )))
(GeneralError a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "in \n"
++ (color Red . style Bold $ show $ a )))
(BadReturns a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "There are some bad return statements in function "
++ (color Red . style Bold $ show $ a )))
(ErrorInStatement a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "in statement \n"
++ (color Red . style Bold $ show $ a )))
(ScopeError a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Out of scope in \n"
++ (color Red . style Bold $ show $ a )))
(ErrorInFunctionCall a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "in function call \n"
++ (color Red . style Bold $ show $ a )))
(ExpressionNotBoolean a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Was expecting a boolean expression in \n"
++ (color Red . style Bold $ show $ a )))
(BadForRange lower upper) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Invalid for range \n"
++ (color Red . style Bold $ show $ lower )
++ (color White . style Bold $ ".." )
++ (color Red . style Bold $ show $ upper )))
(BadExpression a) -> (color Red . style Bold $ "error \n"
++ (color White . style Bold $ "Bad expression in \n"
++ (color Red . style Bold $ show $ a )))
data TCState = TCState
{ tcSymTab :: SymbolTable,
tcClassSymTab :: ClassSymbolTable,
tcAncestors :: AncestorsMap
}
deriving (Show)
setTCState :: SymbolTable -> ClassSymbolTable -> AncestorsMap -> TCState
setTCState s c i = (TCState s c i)
getTCState :: TCState -> (SymbolTable,ClassSymbolTable,AncestorsMap)
getTCState (TCState s c i) = (s,c,i)
modifyTCState (val,newTCState) = do
modify $ \s -> newTCState
type TypeChecker α = StateT TCState (Except (TCError String)) α
type TC = TypeChecker ()
runTypeChecker f = runExcept.runStateT f
exitIfFailure state = do
whenLeft state (\e ->
do
putStrLn.show $ e
exitFailure
)
updatedSymTabOfClass :: ClassIdentifier -> TC
updatedSymTabOfClass classIdentifier =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let updatedSymTabOfClass = (Map.insert classIdentifier symTab classSymTab)
modify $ \s -> (s { tcClassSymTab = updatedSymTabOfClass})
Primero se priorizaran
updatedSymTabOfClassWithParent :: ClassIdentifier -> ClassIdentifier -> TC
updatedSymTabOfClassWithParent classIdentifier parentClassIdentifier =
do
tcState <- get
let (symTabOfCurrentClass,classSymTab,aMap) = getTCState tcState
case (Map.lookup parentClassIdentifier classSymTab) of
Just symTabOfParent ->
do
let symTabInherited = (Map.intersection symTabOfCurrentClass symTabOfParent)
let symTabUnique = (Map.difference symTabOfCurrentClass symTabOfParent)
let newSymTab = Map.fromList (((Map.toList symTabInherited)) ++ (Map.toList symTabUnique))
let updatedSymTabOfClass = (Map.insert classIdentifier newSymTab classSymTab)
modify $ \s -> (s { tcClassSymTab = updatedSymTabOfClass})
Con esta función se empieza el analisis . requiere es Program , nodo raíz del árbol abstracto de sintaxis .
Con esta función se empieza el analisis semántico. Lo único que se requiere es Program, el
nodo raíz del árbol abstracto de sintaxis.
-}
startSemanticAnalysis :: Program -> IO ()
startSemanticAnalysis (Program classList functionList varsList (Block statements)) = do
do
Primero , se analizan las clases . El Map.empty que se manda es el mapa de herencias que se en la etapa
let stateAfterClasses = runTypeChecker (analyzeClasses classList) (setTCState emptySymbolTable emptyClassSymbolTable (Map.empty))
exitIfFailure stateAfterClasses
Después , tabla clases .
let (_,classSymbolTable,aMap) = getTCState (snd (fromRight' stateAfterClasses))
Se corre con . output sera la tabla programa principal
pero con . Es importante notar que aquí ahora se utiliza la tabla clases obtenidas
en el paso anterior .
let stateAfterFunctions = runTypeChecker (analyzeFunctions functionList globalScope Nothing) (setTCState emptySymbolTable classSymbolTable aMap)
exitIfFailure stateAfterFunctions
let (symbolTableWithFuncs,_,_) = getTCState (snd (fromRight' stateAfterFunctions))
Se corre con . output sera la tabla programa principal
pero con
let stateAfterVariables = runTypeChecker (analyzeVariables varsList globalScope Nothing) (setTCState symbolTableWithFuncs classSymbolTable aMap)
exitIfFailure stateAfterVariables
let (symbolTableWithFuncsVars,_,_) = getTCState (snd (fromRight' stateAfterVariables))
let returnListInMain = getReturnStatements statements
if (length returnListInMain > 0) then do
putStrLn $ "There shouldn't be returns in main"
else
do
Por último , se analizan los estatutos encontrados en el bloque principal del programa
let stateAfterMain = runTypeChecker (analyzeStatements statements defScope) (setTCState symbolTableWithFuncsVars classSymbolTable aMap)
exitIfFailure stateAfterMain
let (symbolTableStatements,classSymbolTable,aMap) = getTCState (snd (fromRight' stateAfterMain))
Se pasa a la etapa de alocación de memoria
el nodo raíz con la tabla final ,
la tabla clases y
startMemoryAllocation (Program classList functionList varsList (Block statements)) symbolTableStatements classSymbolTable aMap
deepFilter :: [(Identifier,Symbol)] -> Identifier -> [(Identifier,Symbol)]
deepFilter [] _ = []
deepFilter ((identifier,(SymbolFunction params p1 (Block statements) p2 p3 p4 symTabFunc)) : rest) identifierParent
| identifier == identifierParent = ( deepFilter rest identifierParent )
| otherwise = let filteredSym = (Map.fromList ( deepFilter (Map.toList symTabFunc) identifierParent ) )
in let newSymTab = [(identifier,(SymbolFunction params p1 (Block statements) p2 p3 p4 filteredSym))]
in newSymTab ++ ( deepFilter rest identifierParent )
deepFilter (sym : rest) identifierParent = [sym] ++ (deepFilter rest identifierParent)
getClassName :: Class -> ClassIdentifier
getClassName (ClassInheritance classIdentifier _ _) = classIdentifier
getClassName (ClassNormal classIdentifier _) = classIdentifier
Analyze classes regresa una tabla y . , significa que hubo errores , false , no hubo errores
analyzeClasses :: [Class] -> TC
analyzeClasses [] = do return ()
analyzeClasses (cl : classes) =
do
tcState <- get
let (_,classSymTab,aMap) = getTCState tcState
let classIdentifier = getClassName cl
if Map.member classIdentifier classSymTab
then lift $ throwError (ClassDeclared classIdentifier "")
else do
let classSymTabWithOwnClass = (Map.insert classIdentifier Map.empty classSymTab)
let classStateAfterBlock = runTypeChecker (analyzeClassBlock cl) (setTCState emptySymbolTable classSymTabWithOwnClass aMap)
whenLeft classStateAfterBlock (lift.throwError)
whenRight classStateAfterBlock (modifyTCState)
analyzeClass cl
analyzeClasses classes
analyzeClassBlock :: Class -> TC
Debido a que se está heredando , hay que meter la symbol table de la clase padre en
analyzeClassBlock (ClassInheritance classIdentifier parentClass classBlock) =
do
tcState <- get
let (symTabOfCurrentClass,classSymTab,aMap) = getTCState tcState
case (Map.lookup parentClass classSymTab) of
Just symTabOfClass ->
do
let newSymTabOfCurrentClass = (Map.union (Map.fromList (sortBy (compare `on` fst) (Map.toList symTabOfClass))) symTabOfCurrentClass)
modify $ \s -> (s { tcSymTab = newSymTabOfCurrentClass})
case (Map.lookup parentClass aMap) of
Just classAncestors -> do
let ancestorsForCurrentClass = [parentClass] ++ classAncestors
let newAncestorMap = (Map.insert classIdentifier ancestorsForCurrentClass aMap)
modify $ \s -> (s { tcAncestors = newAncestorMap})
analyzeMembersOfClassBlock classBlock classIdentifier globalScope
updatedSymTabOfClassWithParent classIdentifier parentClass
Nothing -> do
let s = (ClassInheritance classIdentifier parentClass classBlock)
lift $ throwError (ParentClassNotFound parentClass (show s))
analyzeClassBlock (ClassNormal classIdentifier classBlock) = do
tcState <- get
let (symTabOfCurrentClass,classSymTab,aMap) = getTCState tcState
let newAncestorMap = (Map.insert classIdentifier [] aMap)
modify $ \s -> (s { tcAncestors = newAncestorMap})
analyzeMembersOfClassBlock classBlock classIdentifier globalScope
updatedSymTabOfClass classIdentifier
analyzeMembersOfClassBlock :: ClassBlock -> ClassIdentifier -> Scope -> TC
analyzeMembersOfClassBlock (ClassBlockNoConstructor classMembers) classIdentifier scp = do
analyzeClassMembers classMembers classIdentifier scp
updatedSymTabOfClass classIdentifier
analyzeMembersOfClassBlock (ClassBlock classMembers (ClassConstructor classIdConstructor params block)) classIdentifier scp =
do
if (classIdConstructor /= classIdentifier)
then do
lift $ throwError (BadConstructor classIdentifier classIdConstructor "")
else
do
analyzeClassMembers classMembers classIdentifier scp
analyzeFunction (Function (classIdentifier ++ "_constructor") TypeFuncReturnNothing params block) scp (Just True)
updatedSymTabOfClass classIdentifier
analyzeClassMembers :: [ClassMember] -> ClassIdentifier -> Scope -> TC
analyzeClassMembers [] _ _ = return ()
analyzeClassMembers (cm : cms) classIdentifier scp =
do
analyzeClassMember cm classIdentifier scp
updatedSymTabOfClass classIdentifier
analyzeClassMembers cms classIdentifier scp
updatedSymTabOfClass classIdentifier
analyzeClassMember :: ClassMember -> ClassIdentifier -> Scope -> TC
analyzeClassMember (ClassMemberAttribute (ClassAttributePublic variable)) classIdentifier scp = analyzeVariable variable scp (Just True)
analyzeClassMember (ClassMemberAttribute (ClassAttributePrivate variable)) classIdentifier scp = analyzeVariable variable scp (Just False)
analyzeClassMember (ClassMemberFunction (ClassFunctionPublic function)) classIdentifier scp = analyzeFunction function scp (Just True)
analyzeClassMember (ClassMemberFunction (ClassFunctionPrivate function)) classIdentifier scp = analyzeFunction function scp (Just False)
analyzeClass :: Class -> TC
analyzeClass (ClassInheritance subClass parentClass classBlock) =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (ClassInheritance subClass parentClass classBlock)
if Map.member parentClass classSymTab
then do
updatedSymTabOfClassWithParent subClass parentClass
Si el parent class no es miembro , entonces error , no clase no declarada
analyzeClass (ClassNormal classIdentifier classBlock) = do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (ClassNormal classIdentifier classBlock)
let newClassSymTable = Map.insert classIdentifier symTab classSymTab
modify $ \s -> (s { tcClassSymTab = newClassSymTable})
let newClassSymTable = Map.insert
analyzeFunctions :: [Function] -> Scope -> Maybe Bool -> TC
analyzeFunctions [] _ _ = return ()
analyzeFunctions (func : funcs) scp isFuncPublic = do
analyzeFunction func scp isFuncPublic
analyzeFunctions funcs scp isFuncPublic
analyzeVariables :: [Variable] -> Scope -> Maybe Bool -> TC
analyzeVariables [] _ _ = return ()
analyzeVariables (var : vars) scp isVarPublic = do
analyzeVariable var scp isVarPublic
analyzeVariables vars scp isVarPublic
analyzeVariable :: Variable -> Scope -> Maybe Bool -> TC
analyzeVariable (VariableNoAssignment dataType identifiers) scp isVarPublic =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (VariableNoAssignment dataType identifiers)
existe ese tipo
if (checkTypeExistance dataType classSymTab)
then insertIdentifiers identifiers (SymbolVar {dataType = dataType, scope = scp, isPublic = isVarPublic})
Tipo no existe
analyzeVariable (VariableAssignmentLiteralOrVariable dataType identifier literalOrVariable) scp isVarPublic =
En esta parte el tipo este declarado , el literal or variable exista y que la asignacion sea correcta
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (VariableAssignmentLiteralOrVariable dataType identifier literalOrVariable)
existe ese tipo
if (checkTypeExistance dataType classSymTab) && (checkLiteralOrVariableInSymbolTable scp literalOrVariable symTab) && (checkDataTypes scp dataType literalOrVariable symTab aMap)
then insertInSymbolTable identifier (SymbolVar {dataType = dataType, scope = scp, isPublic = isVarPublic})
else lift $ throwError (GeneralError (show s))
analyzeVariable (VariableAssignment1D dataType identifier literalOrVariables) scp isVarPublic =
En esta parte lista de asignaciones concuerde con el tipo de dato declarado
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (VariableAssignment1D dataType identifier literalOrVariables)
case dataType of
TypePrimitive _ (("[",size,"]") : []) ->
makeCheckFor1DAssignment size symTab classSymTab s aMap
TypeClassId _ (("[",size,"]") : []) ->
makeCheckFor1DAssignment size symTab classSymTab s aMap
_ -> lift $ throwError (InvalidArrayAssignment (show s))
where
makeCheckFor1DAssignment size symTab classSymTab s aMap = if (checkTypeExistance dataType classSymTab)
&& (checkLiteralOrVariablesAndDataTypes scp dataType literalOrVariables symTab aMap)
&& ((length literalOrVariables) <= fromIntegral size)
then insertInSymbolTable identifier (SymbolVar {dataType = dataType, scope = scp, isPublic = isVarPublic})
else lift $ throwError (GeneralError (show s))
analyzeVariable (VariableAssignment2D dataType identifier listOfLiteralOrVariables) scp isVarPublic =
En esta parte lista de asignaciones concuerde con el tipo de dato declarado
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (VariableAssignment2D dataType identifier listOfLiteralOrVariables)
case dataType of
TypePrimitive _ (("[",sizeRows,"]") : ("[",sizeCols,"]") : []) ->
makeCheckFor2DAssignment sizeRows sizeCols symTab classSymTab s aMap
TypeClassId _ (("[",sizeRows,"]") : ("[",sizeCols,"]") : []) ->
makeCheckFor2DAssignment sizeRows sizeCols symTab classSymTab s aMap
_ -> lift $ throwError (InvalidArrayAssignment (show s))
where
makeCheckFor2DAssignment sizeRows sizeCols symTab classSymTab s aMap= if (checkTypeExistance dataType classSymTab) &&
(checkLiteralOrVariablesAndDataTypes2D scp dataType listOfLiteralOrVariables symTab aMap)
checamos que sea el numero
&& ((getLongestList listOfLiteralOrVariables) <= fromIntegral sizeCols)
then insertInSymbolTable identifier (SymbolVar {dataType = dataType, scope = scp, isPublic = isVarPublic})
else lift $ throwError (GeneralError (show s))
getLongestList :: [[LiteralOrVariable]] -> Int
getLongestList [] = 0
getLongestList (x : xs) = max (length x) (getLongestList xs)
analyzeVariable (VariableAssignmentObject dataType identifier (ObjectCreation classIdentifier params)) scp isVarPublic =
En esta parte lista de asignaciones concuerde con el tipo de dato declarado
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let s = (VariableAssignmentObject dataType identifier (ObjectCreation classIdentifier params))
case dataType of
TypePrimitive _ _ -> lift $ throwError (ConstructorOnlyClasses (show s))
Checamos si el constructor es del mismo tipo que la clase
TypeClassId classIdentifierDecl [] -> do
if ((doesClassDeriveFromClass classIdentifierDecl (TypeClassId classIdentifier []) aMap) || (classIdentifierDecl == classIdentifier))
Checamos los parametros que se mandan con los del constructor
&& (checkIfParamsAreCorrect scp params classIdentifier symTab classSymTab aMap)
then insertInSymbolTable identifier (SymbolVar {dataType = dataType, scope = scp, isPublic = isVarPublic})
else lift $ throwError (GeneralError (show s))
analyzeVariable var _ _ = lift $ throwError (GeneralError (show var))
filterFuncs :: Symbol -> Bool
filterFuncs (SymbolFunction _ _ _ _ _ _ _) = False
filterFuncs _ = False
isReturnStatement :: Statement -> Bool
isReturnStatement (ReturnStatement ret) = True
isReturnStatement _ = False
analyzeFunction :: Function -> Scope -> Maybe Bool -> TC
analyzeFunction (Function identifier (TypeFuncReturnPrimitive primitive arrayDimension) params (Block statements)) scp isPublic =
do
tcState <- get
let (symTab',classSymTab,aMap) = getTCState tcState
let symTabWithParamsState = runTypeChecker (analyzeFuncParams params) (setTCState emptySymbolTable classSymTab aMap)
whenLeft symTabWithParamsState (lift.throwError)
whenRight classStateAfterBlock
let (newFuncSymTab,_,_) = getTCState (snd (fromRight' symTabWithParamsState))
let ( symTab',classSymTab , aMap ) = getTCState tcState
let s = (Function identifier (TypeFuncReturnPrimitive primitive arrayDimension) params (Block statements))
if ((Map.size (Map.intersection symTab' newFuncSymTab)) /= 0) then lift $ throwError (GeneralError (show s))
else do
let symTab = (Map.fromList (deepFilter (Map.toList symTab') identifier))
let symTabFuncWithOwnFunc = Map.insert identifier (SymbolFunction {returnType = (Just (TypePrimitive primitive arrayDimension)), scope = scp, body = (Block []), shouldReturn = True ,isPublic = isPublic, symbolTable = newFuncSymTab, params = params}) symTab
let newSymTabForFunc = (Map.union (Map.union symTabFuncWithOwnFunc symTab) newFuncSymTab)
let symTabWithStatementsState = runTypeChecker (analyzeStatements statements scp) (setTCState newSymTabForFunc classSymTab aMap)
whenLeft symTabWithStatementsState (lift.throwError)
let (symTabFuncFinished,_,_) = getTCState (snd (fromRight' symTabWithStatementsState))
let ( , _ , _ ) = getTCState tcState
let isLastStatementReturn = isReturnStatement (last $ statements)
let updatedSymTabFunc = Map.insert identifier (SymbolFunction {returnType = (Just (TypePrimitive primitive arrayDimension)), scope = scp, body = (Block statements), shouldReturn = True ,isPublic = isPublic, symbolTable = (Map.filterWithKey (\k _ -> k /= identifier) symTabFuncFinished), params = params}) symTab
if (areReturnTypesOk isLastStatementReturn scp (TypePrimitive primitive arrayDimension) statements updatedSymTabFunc symTabFuncFinished classSymTab aMap)
then
modify $ \s -> (s { tcSymTab = updatedSymTabFunc } )
else lift $ throwError (BadReturns identifier)
analyzeFunction (Function identifier (TypeFuncReturnClassId classIdentifier arrayDimension) params (Block statements)) scp isPublic =
do
tcState <- get
let (symTab',classSymTab,aMap) = getTCState tcState
let symTabWithParamsState = runTypeChecker (analyzeFuncParams params) (setTCState emptySymbolTable classSymTab aMap)
whenLeft symTabWithParamsState (lift.throwError)
whenRight classStateAfterBlock
let (newFuncSymTab,_,_) = getTCState (snd (fromRight' symTabWithParamsState))
let ( symTab',classSymTab , aMap ) = getTCState tcState
let s = (Function identifier (TypeFuncReturnClassId classIdentifier arrayDimension) params (Block statements))
if ((Map.size (Map.intersection symTab' newFuncSymTab)) /= 0) then lift $ throwError (GeneralError (show s))
else do
let symTab = (Map.fromList (deepFilter (Map.toList symTab') identifier))
let symTabFuncWithOwnFunc = Map.insert identifier (SymbolFunction {returnType = (Just (TypeClassId classIdentifier arrayDimension)), scope = scp, body = (Block []), shouldReturn = True ,isPublic = isPublic, symbolTable = newFuncSymTab, params = params}) symTab
let newSymTabForFunc = (Map.union (Map.union symTabFuncWithOwnFunc symTab) newFuncSymTab)
let symTabWithStatementsState = runTypeChecker (analyzeStatements statements scp) (setTCState newSymTabForFunc classSymTab aMap)
whenLeft symTabWithStatementsState (lift.throwError)
let (symTabFuncFinished,_,_) = getTCState (snd (fromRight' symTabWithStatementsState))
let ( , _ , _ ) = getTCState tcState
let isLastStatementReturn = isReturnStatement (last $ statements)
let updatedSymTabFunc = Map.insert identifier (SymbolFunction {returnType = (Just (TypeClassId classIdentifier arrayDimension)), scope = scp, body = (Block statements), shouldReturn = True ,isPublic = isPublic, symbolTable = (Map.filterWithKey (\k _ -> k /= identifier) symTabFuncFinished), params = params}) symTab
if (areReturnTypesOk isLastStatementReturn scp (TypeClassId classIdentifier arrayDimension) statements updatedSymTabFunc symTabFuncFinished classSymTab aMap)
then
modify $ \s -> (s { tcSymTab = updatedSymTabFunc } )
else lift $ throwError (BadReturns identifier)
Como no regresa nada , no hay que buscar que regrese algo
analyzeFunction (Function identifier (TypeFuncReturnNothing) params (Block statements)) scp isPublic =
do
tcState <- get
let (symTab',classSymTab,aMap) = getTCState tcState
let symTabWithParamsState = runTypeChecker (analyzeFuncParams params) (setTCState emptySymbolTable classSymTab aMap)
whenLeft symTabWithParamsState (lift.throwError)
whenRight classStateAfterBlock
let (newFuncSymTab,_,_) = getTCState (snd (fromRight' symTabWithParamsState))
let ( symTab',classSymTab , aMap ) = getTCState tcState
let s = (Function identifier (TypeFuncReturnNothing) params (Block statements))
if ( ((Map.size (Map.intersection symTab' newFuncSymTab)) /= 0) || (length (getReturnStatements statements)) > 0) then lift $ throwError (GeneralError (show s))
else do
let symTab = (Map.fromList (deepFilter (Map.toList symTab') identifier))
let symTabFuncWithOwnFunc = Map.insert identifier (SymbolFunction {returnType = Nothing, scope = scp, body = (Block []), shouldReturn = True ,isPublic = isPublic, symbolTable = newFuncSymTab, params = params}) symTab
let newSymTabForFunc = (Map.union (Map.union symTabFuncWithOwnFunc symTab) newFuncSymTab)
let symTabWithStatementsState = runTypeChecker (analyzeStatements statements scp) (setTCState newSymTabForFunc classSymTab aMap)
whenLeft symTabWithStatementsState (lift.throwError)
let (symTabFuncFinished,_,_) = getTCState (snd (fromRight' symTabWithStatementsState))
let ( , _ , _ ) = getTCState tcState
let updatedSymTabFunc = Map.insert identifier (SymbolFunction {returnType = Nothing, scope = scp, body = (Block statements), shouldReturn = True ,isPublic = isPublic, symbolTable = (Map.filterWithKey (\k _ -> k /= identifier) symTabFuncFinished), params = params}) symTab
modify $ \s -> (s { tcSymTab = updatedSymTabFunc } )
areReturnTypesOk :: Bool -> Scope -> Type -> [Statement] -> SymbolTable -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Bool
areReturnTypesOk isThereAReturnStatement _ _ [] _ _ _ _ = isThereAReturnStatement
areReturnTypesOk isThereAReturnStatement scp funcRetType ((ReturnStatement ret) : []) symTab ownFuncSymTab classTab aMap =
checkCorrectReturnTypes scp funcRetType ret symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType ((ConditionStatement (If _ (Block statements))) : []) symTab ownFuncSymTab classTab aMap =
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statements symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType ((ConditionStatement (IfElse _ (Block statements) (Block statementsElse))) : []) symTab ownFuncSymTab classTab aMap =
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statements symTab ownFuncSymTab classTab aMap &&
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statementsElse symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType ((CaseStatement (Case expressionToMatch expAndBlock otherwiseStatements)) : []) symTab ownFuncSymTab classTab aMap =
(foldl (\bool f -> (bool && (areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType (snd f) symTab ownFuncSymTab classTab aMap))) True expAndBlock ) &&
(areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType otherwiseStatements symTab ownFuncSymTab classTab aMap)
areReturnTypesOk isThereAReturnStatement scp funcRetType ((ConditionStatement (If _ (Block statements))) : sts) symTab ownFuncSymTab classTab aMap =
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statements symTab ownFuncSymTab classTab aMap &&
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType sts symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType ((ConditionStatement (IfElse _ (Block statements) (Block statementsElse))) : sts) symTab ownFuncSymTab classTab aMap =
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statements symTab ownFuncSymTab classTab aMap &&
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType statementsElse symTab ownFuncSymTab classTab aMap &&
areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType sts symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType ((CaseStatement (Case expressionToMatch expAndBlock otherwiseStatements)) : sts) symTab ownFuncSymTab classTab aMap =
(foldl (\bool f -> (bool && (areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType (snd f) symTab ownFuncSymTab classTab aMap))) True expAndBlock ) &&
(areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType otherwiseStatements symTab ownFuncSymTab classTab aMap)
&& areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType sts symTab ownFuncSymTab classTab aMap
areReturnTypesOk isThereAReturnStatement scp funcRetType (_ : sts) symTab ownFuncSymTab classTab aMap = areReturnTypesOk isThereAReturnStatement (scp - 1) funcRetType sts symTab ownFuncSymTab classTab aMap
returns que , inclusive si estan en statements anidados
getReturnStatements :: [Statement] -> [Return]
getReturnStatements [] = []
getReturnStatements ((ReturnStatement returnExp) : sts) = (returnExp) : (getReturnStatements sts)
getReturnStatements ((ConditionStatement (If _ (Block statements))) : sts) = (getReturnStatements statements) ++ (getReturnStatements sts)
getReturnStatements ((ConditionStatement (IfElse _ (Block statements) (Block statementsElse))) : sts) = (getReturnStatements statements) ++ (getReturnStatements statementsElse) ++ (getReturnStatements sts)
getReturnStatements ((CaseStatement (Case expressionToMatch expAndBlock otherwiseStatements)) : sts) = (foldl (\rets f -> (rets ++ (getReturnStatements (snd f)))) [] expAndBlock ) ++ (getReturnStatements otherwiseStatements) ++ (getReturnStatements sts)
getReturnStatements ((CycleStatement (CycleWhile (While _ (Block statements)))) : sts) = (getReturnStatements statements) ++ (getReturnStatements sts)
getReturnStatements ((CycleStatement (CycleFor (For _ _ (Block statements)))) : sts) = (getReturnStatements statements) ++ (getReturnStatements sts)
getReturnStatements (_ : sts) = (getReturnStatements sts)
analyzeFuncParams :: [(Type,Identifier)] -> TC
analyzeFuncParams [] = return ()
analyzeFuncParams ((dataType,identifier) : rest) =
do
analyzeVariable ((VariableNoAssignment dataType [identifier])) globalScope Nothing
analyzeFuncParams rest
El tipo de regreso de una funcion solo puede ser un elemento atomico !
checkCorrectReturnTypes :: Scope -> Type -> Return -> SymbolTable -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Bool
checkCorrectReturnTypes scp dataType (ReturnExp expression) symTab ownFuncSymTab classTab aMap =
case (preProcessExpression scp expression (Map.union symTab ownFuncSymTab) classTab aMap) of
Just (TypePrimitive prim arrayDim) -> (TypePrimitive prim arrayDim) == dataType
Just (TypeClassId classId arrayDim) -> case dataType of
(TypeClassId parentClassId arrayDim2) -> (arrayDim == arrayDim2) && ((doesClassDeriveFromClass classId dataType aMap) || ((TypeClassId parentClassId arrayDim2) == (TypeClassId classId arrayDim)))
_ -> False
_ -> False
Checamos aqui que la constructor
checkIfParamsAreCorrect :: Scope -> [Params] -> ClassIdentifier -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Bool
checkIfParamsAreCorrect scp sendingParams classIdentifier symTab classTab aMap =
case (Map.lookup classIdentifier classTab) of
Just symbolTableOfClass ->
case (Map.lookup (classIdentifier ++ "_constructor") symbolTableOfClass) of
Just (symbolFunc) -> (compareListOfTypesWithFuncCall scp (map (\f -> fst f) (params symbolFunc)) sendingParams symTab classTab aMap)
Nothing -> False
Nothing -> False
analyzeStatements :: [Statement] -> Scope -> TC
analyzeStatements [] _ = return ()
analyzeStatements (st : sts) scp = do
analyzeStatement st scp
analyzeStatements sts scp
analyzeStatement :: Statement -> Scope -> TC
analyzeStatement (AssignStatement assignment) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
if (isAssignmentOk assignment scp symTab classSymTab aMap)
then return ()
else lift $ throwError (ErrorInStatement (show assignment))
analyzeStatement (DisplayStatement displays) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
if (analyzeDisplays displays symTab classSymTab aMap)
then return ()
else lift $ throwError (ErrorInStatement (show displays))
where
analyzeDisplays [] _ _ _ = True
analyzeDisplays (disp : disps) symTab classSymTab aMap =
analyzeDisplay disp scp symTab classSymTab aMap
&& analyzeDisplays disps symTab classSymTab aMap
analyzeStatement (ReadStatement (Reading identifier)) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive _ []) varScp _) ->
if varScp >= scp then
return ()
else lift $ throwError (ScopeError identifier)
_ -> lift $ throwError (IdentifierNotDeclared identifier)
analyzeStatement (DPMStatement assignment) scp = analyzeStatement (AssignStatement assignment) scp
analyzeStatement (FunctionCallStatement functionCall) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
if (analyzeFunctionCall functionCall scp symTab classSymTab aMap)
then return ()
else lift $ throwError (ErrorInFunctionCall (show functionCall))
analyzeStatement (VariableStatement var) scp = analyzeVariable var scp Nothing
analyzeStatement (ConditionStatement (If expression (Block statements))) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (expressionTypeChecker scp expression symTab classSymTab aMap) of
Si la expresión del if ,
Right (TypePrimitive PrimitiveBool []) -> analyzeStatements statements (scp - 1)
De lo contrario , no se en el if
_ -> lift $ throwError (ExpressionNotBoolean (show expression))
analyzeStatement (ConditionStatement (IfElse expression (Block statements) (Block statements2))) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (expressionTypeChecker scp expression symTab classSymTab aMap) of
Si la expresión del if ,
Right (TypePrimitive PrimitiveBool []) ->
do
analyzeStatements statements (scp - 1)
analyzeStatements statements2 (scp - 1)
De lo contrario , no se en el if
_ -> lift $ throwError (ExpressionNotBoolean (show expression))
analyzeStatement (CaseStatement (Case expressionToMatch expAndBlock otherwiseStatements)) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (expressionTypeChecker scp expressionToMatch symTab classSymTab aMap) of
Right dataTypeToMatch ->
do
analyzeCases scp expAndBlock dataTypeToMatch
analyzeStatements otherwiseStatements (scp - 1)
Left err -> lift $ throwError (GeneralError (show err))
analyzeStatement (CycleStatement (CycleWhile (While expression (Block statements)))) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (expressionTypeChecker scp expression symTab classSymTab aMap) of
Right (TypePrimitive PrimitiveBool []) -> analyzeStatements statements (scp - 1)
_ -> lift $ throwError (ExpressionNotBoolean (show expression))
analyzeStatement (CycleStatement (CycleFor (For lowerRange greaterRange (Block statements)))) scp =
if (greaterRange >= lowerRange)
then analyzeStatements statements (scp - 1)
else lift $ throwError (BadForRange lowerRange greaterRange)
analyzeStatement (CycleStatement (CycleForVar statements)) scp = analyzeStatements statements scp
analyzeStatement (ReturnStatement (ReturnFunctionCall functionCall)) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
let isFuncCallOk = analyzeFunctionCall functionCall scp symTab classSymTab aMap
if (isFuncCallOk) then return ()
else lift $ throwError (ErrorInFunctionCall (show functionCall))
analyzeStatement (ReturnStatement (ReturnExp expression)) scp =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just expType -> return ()
Nothing -> lift $ throwError (BadExpression (show expression))
analyzeCases :: Scope -> [(Expression,[Statement])] -> Type -> TC
analyzeCases scp [] _ = return ()
analyzeCases scp ((e,statements) : es) dataTypeToMatch =
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
case (expressionTypeChecker scp e symTab classSymTab aMap) of
Right dataTypeOfExp ->
if (dataTypeOfExp == dataTypeToMatch) then
do
analyzeStatements statements (scp - 1)
analyzeCases scp es dataTypeToMatch
else lift $ throwError (GeneralError "Case head expression is different from expressions to match")
Left _ -> lift $ throwError (GeneralError "Case with a bad formed expression")
analyzeDisplay :: Display -> Scope -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Bool
analyzeDisplay (DisplayLiteralOrVariable (VarIdentifier identifier) _) scp symTab classTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim _) varScp _) ->
varScp >= scp
Just (SymbolVar (TypeClassId classIdentifier _) varScp _) ->
varScp >= scp
_ -> False
Podemos desplegar primitivos sin problemas
analyzeDisplay (DisplayLiteralOrVariable _ _) scp symTab classTab aMap = True
analyzeDisplay (DisplayObjMem (ObjectMember objectIdentifier attrIdentifier) _) scp symTab classTab aMap =
case (Map.lookup objectIdentifier symTab) of
Just (SymbolVar (TypeClassId classIdentifier _) objScp _) ->
if (objScp >= scp)
then
case (Map.lookup classIdentifier classTab) of
Just symbolTableOfClass ->
case (Map.lookup attrIdentifier symbolTableOfClass) of
Si y solo si es publico el atributo ,
Just (SymbolVar attrDataType attrScp (Just True)) ->
True
_ -> False
_ -> False
else False
_ -> False
analyzeDisplay (DisplayFunctionCall functionCall _) scp symTab classTab aMap =
analyzeFunctionCall functionCall scp symTab classTab aMap
analyzeDisplay (DisplayVarArrayAccess identifier ((ArrayAccessExpression expressionIndex) : []) _ ) scp symTab classTab aMap=
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",size,"]") : [])) varScp _ ) ->
if (varScp >= scp) then
let typeIndexExp = (preProcessExpression scp expressionIndex symTab classTab aMap)
in case typeIndexExp of
Just (TypePrimitive PrimitiveInteger _) ->
True
Just (TypePrimitive PrimitiveInt _) ->
True
_ -> False
else False
Just (SymbolVar (TypeClassId classIdentifier (("[",size,"]") : [])) varScp _ ) ->
if (varScp >= scp) then
let typeIndexExp = (preProcessExpression scp expressionIndex symTab classTab aMap)
in case typeIndexExp of
Just (TypePrimitive PrimitiveInteger _) ->
True
Just (TypePrimitive PrimitiveInt _) ->
True
_ -> False
else False
_ -> False
analyzeDisplay (DisplayVarArrayAccess identifier ((ArrayAccessExpression innerExpRow) : (ArrayAccessExpression innerExpCol) : []) _ ) scp symTab classTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",rows,"]") : ("[",columns,"]") : [])) varScp _ ) ->
if (varScp >= scp)
then
let typeRowExp = (expressionTypeChecker scp innerExpRow symTab classTab aMap)
typeColExp = (expressionTypeChecker scp innerExpCol symTab classTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) -> True
Right (TypePrimitive PrimitiveInteger []) -> True
_ -> False
else False
else False
Just (SymbolVar (TypeClassId classIdentifier (("[",rows,"]") : ("[",cols,"]") : [])) varScp _ ) ->
if (varScp >= scp)
then
let typeRowExp = (expressionTypeChecker scp innerExpRow symTab classTab aMap)
typeColExp = (expressionTypeChecker scp innerExpCol symTab classTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) -> True
Right (TypePrimitive PrimitiveInteger []) -> True
_ -> False
else False
else False
_ -> False
isAssignmentOk :: Assignment -> Scope -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Bool
isAssignmentOk (AssignmentExpression identifier expression) scp symTab classSymTab aMap = case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim accessExpression) varScp _) ->
Si el scope de esta variable es mayor , accederlo
if (varScp >= scp)
then
let typeExp = (preProcessExpression scp expression symTab classSymTab aMap)
in case typeExp of
Just typeUnwrapped ->
typeUnwrapped == (TypePrimitive prim accessExpression)
_ -> False
else False
Just (SymbolVar (TypeClassId classIdentifier dimOfIdentifier) varScp _) ->
Si el scope de esta variable es mayor , accederlo
if (varScp >= scp)
then let typeExp = (preProcessExpression scp expression symTab classSymTab aMap)
in case typeExp of
Just (TypeClassId classId dimExpression) ->
(dimOfIdentifier == dimExpression) && ((doesClassDeriveFromClass classId (TypeClassId classIdentifier dimOfIdentifier) aMap) || (classIdentifier == classId ))
_ -> False
else False
_ -> False
isAssignmentOk (AssignmentObjectMember identifier (ObjectMember objectIdentifier attrIdentifier)) scp symTab classSymTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar dataType varScp _) ->
if (varScp >= scp)
then
case (Map.lookup objectIdentifier symTab) of
Just (SymbolVar (TypeClassId classIdentifier []) objScp _) ->
if (objScp >= scp)
then
case (Map.lookup classIdentifier classSymTab) of
Just symbolTableOfClass ->
case (Map.lookup attrIdentifier symbolTableOfClass) of
Si y solo si es publico el atributo ,
Just (SymbolVar attrDataType attrScp (Just True)) ->
case attrDataType of
(TypeClassId subClass arrayDim) ->
case dataType of
(TypeClassId parentClass arrayDimPClass) ->
(arrayDim == arrayDimPClass) && ((doesClassDeriveFromClass subClass dataType aMap) || ((TypeClassId subClass arrayDim) == dataType))
_ -> False
dt -> (dt == dataType)
_ -> False
_ -> False
else False
_ -> False
else False
_ -> False
isAssignmentOk (AssignmentObjectMemberExpression (ObjectMember objectIdentifier attrIdentifier) expression) scp symTab classSymTab aMap =
case (Map.lookup objectIdentifier symTab) of
Just (SymbolVar (TypeClassId classIdentifier _) objScp _) ->
if (objScp >= scp)
then
case (Map.lookup classIdentifier classSymTab) of
Just symbolTableOfClass ->
case (Map.lookup attrIdentifier symbolTableOfClass) of
Si y solo si es publico el atributo ,
Just (SymbolVar attrDataType attrScp (Just True)) ->
let typeExp = (preProcessExpression scp expression symTab classSymTab aMap)
in case typeExp of
Just (TypePrimitive prim arrayAccessExp) ->
(TypePrimitive prim arrayAccessExp) == attrDataType
Just (TypeClassId subClass arrayAccessExp) ->
case attrDataType of
(TypeClassId parentClass arrayDim) ->
(arrayDim == arrayAccessExp) && ((doesClassDeriveFromClass subClass (TypeClassId parentClass arrayDim) aMap) || (TypeClassId subClass arrayAccessExp) == (TypeClassId parentClass arrayDim) )
_ -> False
_ -> False
_ -> False
_ -> False
else False
_ -> False
isAssignmentOk (AssignmentArrayExpression identifier ((ArrayAccessExpression innerExp) : []) expression) scp symTab classSymTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",size,"]") : [])) varScp _) ->
if (varScp >= scp)
then
let typeIndexExp = (expressionTypeChecker scp innerExp symTab classSymTab aMap)
in case typeIndexExp of
Right (TypePrimitive PrimitiveInt []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypePrimitive primExp _) -> primExp == prim
_ -> False
Right (TypePrimitive PrimitiveInteger []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypePrimitive primExp _) -> primExp == prim
_ -> False
_ -> False
else False
Just (SymbolVar (TypeClassId classIdentifier (("[",size,"]") : [])) varScp _) ->
if (varScp >= scp)
then
let typeIndexExp = (expressionTypeChecker scp innerExp symTab classSymTab aMap)
in case typeIndexExp of
Right (TypePrimitive PrimitiveInt []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypeClassId classId []) -> (doesClassDeriveFromClass classId (TypeClassId classIdentifier (("[",size,"]") : [])) aMap)
|| classId == classIdentifier
_ -> False
Right (TypePrimitive PrimitiveInteger []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypeClassId classId []) -> (doesClassDeriveFromClass classId (TypeClassId classIdentifier (("[",size,"]") : [])) aMap)
|| classId == classIdentifier
_ -> False
_ -> False
else False
_ -> False
isAssignmentOk (AssignmentArrayExpression identifier ((ArrayAccessExpression innerExpRow) : (ArrayAccessExpression innerExpCol) : []) expression) scp symTab classSymTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",sizeRows,"]") : ("[",sizeCols,"]") : [])) varScp _) ->
if (varScp >= scp)
then
let typeRowExp = (expressionTypeChecker scp innerExpRow symTab classSymTab aMap)
typeColExp = (expressionTypeChecker scp innerExpCol symTab classSymTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypePrimitive primAssignment []) ->
primAssignment == prim
_ -> False
Right (TypePrimitive PrimitiveInteger []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypePrimitive primAssignment []) ->
primAssignment == prim
_ -> False
_ -> False
else False
else False
Just (SymbolVar (TypeClassId classIdentifier (("[",sizeRows,"]") : ("[",sizeCols,"]") : [])) varScp _) ->
if (varScp >= scp)
then
let typeRowExp = (expressionTypeChecker scp innerExpRow symTab classSymTab aMap)
typeColExp = (expressionTypeChecker scp innerExpCol symTab classSymTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypeClassId classIdAssignment []) ->
(doesClassDeriveFromClass classIdAssignment (TypeClassId classIdentifier (("[",sizeRows,"]") : ("[",sizeCols,"]") : [])) aMap) || classIdentifier == classIdAssignment
_ -> False
Right (TypePrimitive PrimitiveInteger []) ->
case (preProcessExpression scp expression symTab classSymTab aMap) of
Just (TypeClassId classIdAssignment []) ->
(doesClassDeriveFromClass classIdAssignment (TypeClassId classIdentifier (("[",sizeRows,"]") : ("[",sizeCols,"]") : [])) aMap) || classIdentifier == classIdAssignment
_ -> False
_ -> False
else False
else False
_ -> False
isAssignmentOk _ _ _ _ _ = False
insertIdentifiers :: [Identifier] -> Symbol -> TC
insertIdentifiers [] _ = return ()
insertIdentifiers (identifier : ids) symbol =
do
insertInSymbolTable identifier symbol
insertIdentifiers ids symbol
insertInSymbolTable :: Identifier -> Symbol -> TC
insertInSymbolTable identifier symbol =
Si esta ese identificador en la tabla , entonces regreso error
do
tcState <- get
let (symTab,classSymTab,aMap) = getTCState tcState
if Map.member identifier symTab
then lift $ throwError (IdentifierDeclared identifier "")
else do
let newSymTab = (Map.insert identifier symbol symTab)
modify $ \s -> (s {tcSymTab = newSymTab})
una lista de literales o variables sea del tipo receptor
checkLiteralOrVariablesAndDataTypes :: Scope -> Type -> [LiteralOrVariable] -> SymbolTable -> AncestorsMap -> Bool
checkLiteralOrVariablesAndDataTypes _ _ [] _ _ = True
checkLiteralOrVariablesAndDataTypes scp dataType (litVar : litVars) symTab aMap =
if (checkLiteralOrVariableInSymbolTable scp litVar symTab) && (checkArrayAssignment scp dataType litVar symTab aMap)
then checkLiteralOrVariablesAndDataTypes scp dataType litVars symTab aMap
Alguna literal o variable asignada no existe , o bien , esta asignando no concuerda con la declaracion
checkLiteralOrVariableInSymbolTable :: Scope -> LiteralOrVariable -> SymbolTable -> Bool
checkLiteralOrVariableInSymbolTable scp (VarIdentifier identifier) symTab =
case (Map.lookup identifier symTab) of
Just (SymbolVar _ varScp _) ->
varScp >= scp
_ -> False
var identifier , entonces regresamos true , o sea , sin error
checkTypeExistance :: Type -> ClassSymbolTable -> Bool
checkTypeExistance (TypeClassId classIdentifier _) classTab =
case (Map.lookup classIdentifier classTab) of
El identificador que se esta asignando no esta en ningun
checkLiteralOrVariablesAndDataTypes2D :: Scope -> Type -> [[LiteralOrVariable]] -> SymbolTable -> AncestorsMap -> Bool
checkLiteralOrVariablesAndDataTypes2D _ _ [] _ _ = True
checkLiteralOrVariablesAndDataTypes2D scp dataType (listOfLitVars : rest) symTab aMap =
if (checkLiteralOrVariablesAndDataTypes scp dataType listOfLitVars symTab aMap)
then checkLiteralOrVariablesAndDataTypes2D scp dataType rest symTab aMap
Alguna literal o variable asignada no existe , o bien , esta asignando no concuerda con la declaracion
Podriamos necesitar preprocesar una expresion en busqueda de un literal or variable que sea clase
preProcessExpression :: Scope -> Expression -> SymbolTable -> ClassSymbolTable -> AncestorsMap -> Maybe Type
preProcessExpression scp (ExpressionLitVar (VarIdentifier identifier)) symTab _ aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypeClassId classIdentifier accessExpression) varScp _)
| varScp >= scp ->
Just (TypeClassId classIdentifier accessExpression)
| otherwise -> Nothing
Just (SymbolVar (TypePrimitive prim accessExpression) varScp _)
| varScp >= scp ->
Just (TypePrimitive prim accessExpression)
| otherwise -> Nothing
_ -> Nothing
preProcessExpression scp (ExpressionFuncCall functionCall) symTab classSymTab aMap = if (analyzeFunctionCall functionCall scp symTab classSymTab aMap) then
functionCallType functionCall scp symTab classSymTab
else Nothing
preProcessExpression scp (ExpressionVarArray identifier ((ArrayAccessExpression expressionIndex) : [])) symTab classSymTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",size,"]") : []) ) varScp _)
| varScp >= scp ->
let typeIndexExp = (expressionTypeChecker scp expressionIndex symTab classSymTab aMap)
in case typeIndexExp of
Right (TypePrimitive PrimitiveInt []) -> Just (TypePrimitive prim [])
Right (TypePrimitive PrimitiveInteger []) -> Just (TypePrimitive prim [])
_ -> Nothing
| otherwise -> Nothing
Just (SymbolVar (TypeClassId classIdentifier (("[",size,"]") : []) ) varScp _)
| varScp >= scp ->
let typeIndexExp = (expressionTypeChecker scp expressionIndex symTab classSymTab aMap)
in case typeIndexExp of
Right (TypePrimitive PrimitiveInt []) -> Just (TypeClassId classIdentifier [])
Right (TypePrimitive PrimitiveInteger []) -> Just (TypeClassId classIdentifier [])
_ -> Nothing
| otherwise -> Nothing
_ -> Nothing
preProcessExpression scp (ExpressionVarArray identifier ((ArrayAccessExpression rowExp) : (ArrayAccessExpression colExp) : [])) symTab classSymTab aMap =
case (Map.lookup identifier symTab) of
Just (SymbolVar (TypePrimitive prim (("[",rows,"]") : ("[",cols,"]") : [])) varScp _)
| varScp >= scp ->
let typeRowExp = (expressionTypeChecker scp rowExp symTab classSymTab aMap)
typeColExp = (expressionTypeChecker scp colExp symTab classSymTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) -> Just (TypePrimitive prim [])
Right (TypePrimitive PrimitiveInteger []) -> Just (TypePrimitive prim [])
_ -> Nothing
else Nothing
| otherwise -> Nothing
Just (SymbolVar (TypeClassId classIdentifier (("[",rows,"]") : ("[",cols,"]") : [])) varScp _)
| varScp >= scp ->
let typeRowExp = (expressionTypeChecker scp rowExp symTab classSymTab aMap)
typeColExp = (expressionTypeChecker scp colExp symTab classSymTab aMap)
in if (typeColExp == typeRowExp) then
case typeRowExp of
Right (TypePrimitive PrimitiveInt []) -> Just (TypeClassId classIdentifier [])
Right (TypePrimitive PrimitiveInteger []) -> Just (TypeClassId classIdentifier [])
_ -> Nothing
else Nothing
| otherwise -> Nothing
_ -> Nothing
preProcessExpression scp expression symTab classSymTab aMap = case (expressionTypeChecker scp expression symTab classSymTab aMap) of
Right dtExp -> (Just dtExp)
_ -> Nothing
|
3beade881c4d4bc859671a18aa715d2aeca742e791d15c9903cc6c33ee84e56c | janestreet/sexp | query.ml | open Core
open Sexp_app
type output_mode =
| Sexp
| Count
| Silent
type t =
{ inputs : unit Located.t
; output_mode : output_mode
; allow_empty_output : bool
; labeled : bool
; group : bool
; machine : bool
; fail_on_parse_error : bool
; perform_query : Sexp_ext.t -> on_result:(Sexp.t -> unit) -> unit
}
type parameters = t
let singleton x = Lazy_list.cons x (Lazy_list.empty ())
let scan lexbuf ~fail_on_parse_error =
Lazy_list.build ~seed:() ~f:(fun () ->
try
match Sexp.scan_sexp_opt lexbuf with
| None -> None
| Some sexp -> Some (Sexp_ext.t_of_sexp sexp, ())
with
| _ignored_exn when not fail_on_parse_error -> None)
;;
module Transform : sig
type t
val make : parameters -> t
val initialize_source : t -> string -> Sexp.t -> unit
val finalize_source : t -> string -> unit
val finalize_all : t -> unit
val any_output : t -> bool
end = struct
type t =
{ initialize_source : string -> Sexp.t -> unit
; process_sexp : Sexp.t -> unit
; finalize_source : string -> unit
; finalize_all : unit -> unit
; any_output : bool ref
}
let initialize_source t label = t.initialize_source label
let finalize_source t label = t.finalize_source label
let finalize_all t = t.finalize_all ()
let any_output t = t.any_output.contents
let with_label label sexp = Sexp.List [ Sexp.Atom label; sexp ]
let make_count t ~f =
let count = ref 0 in
let process_sexp _sexp = incr count in
if t.labeled
then (
let finalize_source label =
let sexp = with_label label (Int.sexp_of_t !count) in
count := 0;
f sexp
in
let finalize_all = ignore in
process_sexp, finalize_source, finalize_all)
else (
let finalize_source = ignore in
let finalize_all () =
let count = Int.sexp_of_t !count in
f count
in
process_sexp, finalize_source, finalize_all)
;;
let make t =
let any_output = ref t.allow_empty_output in
let sexp_output = if t.machine then Sexp.output else Sexp.output_hum in
let process_sexp sexp =
sexp_output stdout sexp;
print_endline ""
in
let process_output ~f =
if t.allow_empty_output
then f
else
fun sexp ->
f sexp;
any_output := true
in
let process_sexp, finalize_source, finalize_all =
match t.output_mode with
| Sexp -> process_output ~f:process_sexp, ignore, ignore
| Count -> make_count t ~f:(process_output ~f:process_sexp)
| Silent -> process_output ~f:ignore, ignore, ignore
in
let initialize_source =
if t.labeled
then (fun label ->
();
fun sexp -> process_sexp (with_label label sexp))
else fun _ -> process_sexp
in
{ initialize_source; process_sexp; finalize_source; finalize_all; any_output }
;;
end
let execute t =
let transform = Transform.make t in
let channels = Located.channels t.inputs in
let input =
Located.map channels ~f:(fun chan ->
let sexps =
scan (Lexing.from_channel chan) ~fail_on_parse_error:t.fail_on_parse_error
in
if t.group then singleton (Sexp_ext.List sexps) else sexps)
in
let iter_source label sexps =
let process_sexp = Transform.initialize_source transform label in
Lazy_list.iter sexps ~f:(fun sexp -> t.perform_query sexp ~on_result:process_sexp);
Transform.finalize_source transform label
in
Located.iter input ~f:iter_source;
Transform.finalize_all transform;
exit (if Transform.any_output transform then 0 else 1)
;;
| null | https://raw.githubusercontent.com/janestreet/sexp/56e485b3cbf8a43e1a8d7647b0df31b27053febf/bin/query.ml | ocaml | open Core
open Sexp_app
type output_mode =
| Sexp
| Count
| Silent
type t =
{ inputs : unit Located.t
; output_mode : output_mode
; allow_empty_output : bool
; labeled : bool
; group : bool
; machine : bool
; fail_on_parse_error : bool
; perform_query : Sexp_ext.t -> on_result:(Sexp.t -> unit) -> unit
}
type parameters = t
let singleton x = Lazy_list.cons x (Lazy_list.empty ())
let scan lexbuf ~fail_on_parse_error =
Lazy_list.build ~seed:() ~f:(fun () ->
try
match Sexp.scan_sexp_opt lexbuf with
| None -> None
| Some sexp -> Some (Sexp_ext.t_of_sexp sexp, ())
with
| _ignored_exn when not fail_on_parse_error -> None)
;;
module Transform : sig
type t
val make : parameters -> t
val initialize_source : t -> string -> Sexp.t -> unit
val finalize_source : t -> string -> unit
val finalize_all : t -> unit
val any_output : t -> bool
end = struct
type t =
{ initialize_source : string -> Sexp.t -> unit
; process_sexp : Sexp.t -> unit
; finalize_source : string -> unit
; finalize_all : unit -> unit
; any_output : bool ref
}
let initialize_source t label = t.initialize_source label
let finalize_source t label = t.finalize_source label
let finalize_all t = t.finalize_all ()
let any_output t = t.any_output.contents
let with_label label sexp = Sexp.List [ Sexp.Atom label; sexp ]
let make_count t ~f =
let count = ref 0 in
let process_sexp _sexp = incr count in
if t.labeled
then (
let finalize_source label =
let sexp = with_label label (Int.sexp_of_t !count) in
count := 0;
f sexp
in
let finalize_all = ignore in
process_sexp, finalize_source, finalize_all)
else (
let finalize_source = ignore in
let finalize_all () =
let count = Int.sexp_of_t !count in
f count
in
process_sexp, finalize_source, finalize_all)
;;
let make t =
let any_output = ref t.allow_empty_output in
let sexp_output = if t.machine then Sexp.output else Sexp.output_hum in
let process_sexp sexp =
sexp_output stdout sexp;
print_endline ""
in
let process_output ~f =
if t.allow_empty_output
then f
else
fun sexp ->
f sexp;
any_output := true
in
let process_sexp, finalize_source, finalize_all =
match t.output_mode with
| Sexp -> process_output ~f:process_sexp, ignore, ignore
| Count -> make_count t ~f:(process_output ~f:process_sexp)
| Silent -> process_output ~f:ignore, ignore, ignore
in
let initialize_source =
if t.labeled
then (fun label ->
();
fun sexp -> process_sexp (with_label label sexp))
else fun _ -> process_sexp
in
{ initialize_source; process_sexp; finalize_source; finalize_all; any_output }
;;
end
let execute t =
let transform = Transform.make t in
let channels = Located.channels t.inputs in
let input =
Located.map channels ~f:(fun chan ->
let sexps =
scan (Lexing.from_channel chan) ~fail_on_parse_error:t.fail_on_parse_error
in
if t.group then singleton (Sexp_ext.List sexps) else sexps)
in
let iter_source label sexps =
let process_sexp = Transform.initialize_source transform label in
Lazy_list.iter sexps ~f:(fun sexp -> t.perform_query sexp ~on_result:process_sexp);
Transform.finalize_source transform label
in
Located.iter input ~f:iter_source;
Transform.finalize_all transform;
exit (if Transform.any_output transform then 0 else 1)
;;
|
|
bf386bcf248d4169658dc477cf21d8e6085d317cfdfc3ce0859d8c44348007f0 | adventuring/tootsville.net | i18n+l10n.lisp | (in-package :oliphaunt)
Internationalization and Localization Support
(define-constant +language-names+
'((:en "English" "English" "Language")
(:es "Español" "Spanish" "Idioma")
(:fr "Français" "French" "Langue")
(:ga "Gaeilge" "Irish" "Teanga")
(:ru "Русский" "Russian" "Язык")
(:la "Lingua Latina" "Latin" "Lingua"))
:test 'equalp)
(define-condition language-not-implemented-warning (warning)
((language :initarg :language :reader language-not-implemented)
(fn :initarg :function :reader language-not-implemented-function))
(:report (lambda (c s)
(format s "There is not an implementation of ƒ ~A for language ~A ~@[~{~*(~A/~A)~}~]"
(slot-value c 'fn)
(slot-value c 'language)
(assoc (language-not-implemented c) +language-names+)))))
(defmacro defun-lang (function (&rest lambda-list) &body bodies)
(let ((underlying (intern (concatenate 'string (string function) "%"))))
#+test-i18n
(let ((implemented (mapcar #'car bodies)))
(unless (every (rcurry #'member implemented)
(mapcar #'car +language-names+))
(warn "Defining ƒ ~A with partial language support: ~{~{~% • ~5A: ~20A ~:[ ✗ ~; ✓ ~]~}~}"
function
(mapcar (lambda (language)
(list (car language)
(third language)
(member (car language) implemented)))
+language-names+))))
`(progn
(defgeneric ,underlying (language ,@lambda-list)
,@(mapcar (lambda (body)
(let ((match (car body))
(code (cdr body)))
(unless (assoc match +language-names+)
(warn "Defining a handler for unrecognized language-code ~A in ƒ ~A"
match function))
`(:method ((language (eql ,match)) ,@lambda-list)
,@code)))
bodies)
(:method ((language t) ,@lambda-list)
(warn 'language-not-implemented-warning :language language :function ',function)
(,underlying :en ,@lambda-list)))
(defun ,function (,@lambda-list)
(,underlying (or (get-lang) :en)
,@lambda-list)))))
(defun char-string (char)
(make-string 1 :initial-element char))
(defun irish-broad-vowel-p (char)
(member char '(#\a #\o #\u #\á #\ó #\ú)))
(defun irish-broad-ending-p (word)
(irish-broad-vowel-p (last-elt (remove-if-not #'irish-vowel-p word))))
;;; Genders of words which cannot be guessed by their declensions
(defvar irish-gender-dictionary (make-hash-table :test 'equal))
(dolist (word ($$$ adharc baintreach báisteach buíon caor cearc
ciall cloch cos craobh críoch cros dámh
dealbh eangach fadhb fearg ficheall fréamh
gaoth géag gealt girseach grian iall iníon
lámh leac long luch méar mian mias muc
nead pian sceach scian scornach slat
sluasaid srón téad tonn ubh banríon Cáisc
cuid díolaim Eoraip feag feoil muir scread
rogha teanga bearna veain beach))
(setf (gethash word irish-gender-dictionary) :f))
(dolist (word ($$$ am anam áth béas bláth cath cíos cith
crios dath dream droim eas fíon flaith
greim loch lus luach modh rámh rang
rás roth rud sioc taom teas tréad
im sliabh ainm máistir seans club dlí
rince coláiste))
(setf (gethash word irish-gender-dictionary) :m))
(defvar irish-declension-dictionary (make-hash-table :test 'equal))
(dolist (word ($$$ im sliabh
adharc baintreach báisteach buíon caor cearc ciall
cloch cos craobh críoch cros dámh dealbh eangach
fadhb fearg ficheall fréamh gaoth géag gealt
girseach grian iall iníon lámh leac long luch
méar mian mias muc nead pian sceach scian
scornach slat sluasaid srón téad tonn ubh))
(setf (gethash word irish-declension-dictionary) 2))
(dolist (word ($$$ am anam áth béas bláth cath cíos cith crios
dath dream droim eas fíon flaith greim
loch lus luach modh rámh rang rás roth rud
sioc taom teas tréad
banríon Cáisc cuid díolaim Eoraip
feag feoil muir scread))
(setf (gethash word irish-declension-dictionary) 3))
(dolist (word ($$$ rogha teanga bearna ainm máistir seans
club veain dlí rince))
(setf (gethash word irish-declension-dictionary) 4))
(defvar english-gender-dictionary (make-hash-table :test 'equal))
(dolist (word '(car automobile ship plane
airplane boat vessel
cat kitty hen chick peahen
girl woman lady miss mistress mrs ms
chauffeuse masseuse stewardess
madam))
(setf (gethash (string word) english-gender-dictionary) :f))
(dolist (word '(man boy guy bloke fellow dude
dog cock rooster peacock
mister master mr))
(setf (gethash (string word) english-gender-dictionary) :m))
(defun latin-normalize (string)
(regex-replace-pairs '(("i" "j")
("v" "u")
("w" "uu")
("æ" "ae")
("œ" "oe"))
(string-downcase string)))
(defun latin-presentation-form (string)
(funcall (letter-case string)
(regex-replace-pairs '(("ae" "æ")
("oe" "œ")
("u" "v"))
(string-downcase string))))
;; Determine the gender and declension of a word
(defun-lang gender-of (noun)
(:en (if-let ((gender (gethash (string-upcase noun) english-gender-dictionary)))
gender
:n))
(:es (string-ends-with-case noun
("o" :m)
("a" :f)
(otherwise :m)))
(:fr (if (member (last-elt noun) '(#\e #\E))
:f
:m))
(:la (or (gethash (latin-normalize noun) latin-gender-dictionary)
(case (declension-of noun)
(1 :f)
(2 (string-ends-with-case noun
("us" :m)
("um" :n)))
(3 :m) ; totally random guess
(4 :f)
(5 :f))))
(:ga (or (gethash (string-downcase noun) irish-gender-dictionary)
(string-ends-with-case noun
(("e" "í") :f)
(($$$ a o e u i
á ó é ú í
ín) :m)
(($$$ áil úil ail úint cht irt) :f)
(($$$ éir eoir óir úir) :m)
(("óg" "eog" "lann") :f)
(otherwise
(if (irish-broad-ending-p noun)
:m
:f))))))
(defun-lang declension-of (noun)
(:en nil)
(:la (if-let (genitive (gethash (latin-normalize noun) latin-genitives))
(string-ends-with-case genitive
("ae" 1)
("ēī" 5)
("ī" 2)
("is" 3)
("ūs" 4)))
(string-ends-with-case noun ; bad fallback
("a" 1)
could be 4 , but less likely …
("um" 2)
("ēs" 5)
(otherwise 3)))
(:ga (if-let ((overrule (gethash noun irish-declension-dictionary)))
overrule
(cond
((or (eql (last-elt noun) #\e)
(eql (last-elt noun) #\í)
(irish-vowel-p (last-elt noun))
(string-ends "ín" noun)) 4)
((or (member noun '("áil" "úil" "ail" "úint" "cht" "irt"
"éir" "eoir" "óir" "úir")
:test #'string-ending)) 3)
((or (string-ends "eog" noun)
(string-ends "óg" noun)
(string-ends "lann" noun)
(not (irish-broad-ending-p noun))) 2)
((irish-broad-ending-p noun) 1)
(t (warn "Can't guess declension () of “~a”" noun))))))
(defvar latin-genitives (make-hash-table :test #'equal))
(defvar latin-gender-dictionary (make-hash-table :test #'equal))
(let ((array (mapcar (lambda (word)
(let ((parts (split-sequence #\space (substitute #\space #\, word) :remove-empty-subseqs t :count 3)))
(if (char= (elt (elt parts 1) 0) #\-)
(list (elt parts 0) (keyword* (elt parts 1)) (keyword* (elt parts 2)))
(list (elt parts 0) (elt parts 1) (keyword* (elt parts 2))))))
'("accola -ae m"
"advena -ae m"
"agricola, -ae, m"
"agripeta, -ae m"
"alienigena -ae m"
"alipta -ae m"
"aliptes aliptae m"
"amniclola -ae m"
"anagnostes anagnostae m"
"analecta, -ae m"
"anguigena, -ae m"
"anthias, -ae m"
"archipirata, -ae m"
"artopta, -ae m"
"athleta, -ae m"
"auriga, -ae m"
"Abnoba, -ae m"
"Acestes, Acestae m"
"Achates, -ae m"
"Acmonides, -ae m"
"Actorides, -ae m"
"Aeeta, -ae m"
"Aeneas, -ae m"
"Aenides, -ae m"
"Agamemnonides, -ae m"
"Agrippa, -ae m"
"Ahala, -ae m"
"Amisia, -ae m"
"Amphiaraides, -ae m"
"Ampycides, -ae m"
"Amyntas, -ae m"
"Amyntiades, -ae m"
"Anas, Anae m"
"Anaxagoras, -ae m"
"Anchises, -ae m"
"Anchisiades, -ae m"
"Antiphates, -ae m"
"Antisthenes, -ae m"
"Aonides, -ae m"
"Apolloniates, -ae m"
"Appenninicola, -ae c"
"Appenninigena, -ae c"
"Arabarches, -ae m"
"Archias, -ae m"
"Arestorides, -ae m"
"Asopiades, -ae m"
"Astacides, -ae m"
"Athamantiades, -ae m"
"Atlantiades, -ae m"
"Atrida Atridae m"
"Atrides, Atridae m"
"Atta, -ae m"
"Aurigena, -ae m"
"Axona, -ae m"
"brabeuta, -ae m"
"bucaeda, -ae m"
"Bacchiadae, -ārum m"
"Bagoas, -ae m"
"Bagrada, -ae m"
"Baptae, -ārum m"
"Barcas, -ae m"
"Bastarnae -ārum m"
"Basternae, -ārum m"
"Battiades, -ae m"
"Belgae, -ārum m"
"Bellerophontes, -ae m"
"Belides, -ae m"
"Bootes, -ae m"
"Boreas, -ae m"
"cacula, -ae m"
"caecias, -ae m"
"cataphractes, -ae m"
"cerastes, -ae m"
"choraules, -ae m"
"citharista, -ae m"
"clepta, -ae m"
"cometes, -ae m"
"conchita, -ae m"
"conlega, -ae m"
"convenae, -ārum c"
"conviva, -ae m"
"coprea, -ae m"
"Caligula, -ae m"
"Caracalla, -ae m"
"Catilina, -ae m"
"Cecropides, -ae m"
"Celtae, -ārum m"
"Charondas, -ae m"
"Chrysas, -ae m"
"Chryses, -ae m"
"Cinga, -ae m"
"Cinna, -ae m"
"Cinyras, -ae m"
"Clinias, -ae m"
"Cliniades, -ae m"
"Columella, -ae m"
"Cotta, -ae m"
"Crotoniates, -ae m"
"Crotopiades, -ae m"
"danista, -ae m"
"dioecetes, -ae m"
"draconigena, -ae m"
"drapeta, -ae m"
"Dalmatae, -ārum m"
"Dolabella, -ae m"
"etesiae, -ārum m"
"Eleates, -ae m"
"Eumolpidae, -ārum m"
"faeniseca, -ae m"
"fratricida, -ae m"
"geometres, -ae m"
"grammatista, -ae m"
"gumia, -ae m"
"Galatae, -ārum m"
"Galba, -ae m"
"Gangaridae, -ārum m "
"Geta, -ae, m"
"Gorgias, -ae m"
"Graiugena, -ae m"
"Gyas, -ae m"
"Gyges, -ae m"
"halophanta, -ae m"
"heuretes, -ae m"
"hybrida hybridae m"
"hibrida -ae m"
"hippotoxota, -ae m"
"homicida, -ae c"
"Heraclides, -ae m"
"Herma -ae m"
"Hermes Hermae m"
"Hilotae, -ārum m"
"Ilotae Itolārum m"
"Hippias, -ae m"
"Hippomenes, -ae m"
"Hippotades, -ae m"
"ignigena, -ae m"
"incola, -ae m"
"Ianigena, -ae m"
"Iarbas (Iarba), -ae"
"Iliades, -ae m"
"Iuba, -ae m"
"Iugurtha, -ae m"
"Iura, -ae m"
"lanista, -ae m"
"latebricola, -ae m"
"lixa, -ae m"
"Ladas, -ae m"
"Lamia, -ae m"
"Lapithae, -ārum m"
"Leonidas, -ae m"
"nauta, -ae m"
"parricida, -ae m"
"pirata, -ae m"
"poeta, -ae m"
"Proca, -ae m"
"tata, -ae m"
"umbraticola, -ae m"
"xiphias, -ae m"
))))
(flet ((apply-genitive (gen* nom)
(etypecase gen*
(string gen*)
(keyword (ecase gen*
(:-ae (if (char= (last-elt nom) #\a)
(strcat nom "e")
(strcat nom "ae")))
((:-arum :-ārum) (strcat (if (string-ends "ae" nom)
(subseq nom (- (length nom) 2))
nom)
"ārum"))
((:-ī :-i) (strcat (if (or (string-ends "um" nom)
(string-ends "us" nom))
(subseq nom 0 (- (length nom) 2))
nom)
"ī"))
((:-orum :-ōrum) (strcat (if (string-ends "ae" nom)
(subseq nom (- (length nom) 2))
nom)
"ōrum"))
(:-is (strcat nom "is"))
(:-ium (strcat nom "ium"))
((:-us :-ūs) (strcat (if (string-ends "us" nom)
(subseq nom 0 (- (length nom) 2))
nom)
"ūs"))
((:-ei :-ēī) (if (string-ends "ēs" nom)
(strcat (subseq nom 0 (- (length nom) 1)) "ī")
(strcat nom "ēī"))))))))
(dolist (word array)
(destructuring-bind (nom gen* &optional gender) word
(let ((gen (apply-genitive gen* nom)))
(setf (gethash (latin-normalize nom) latin-genitives) (latin-normalize gen))
(when gender
(setf (gethash (latin-normalize nom) latin-gender-dictionary) gender)))))))
(let ((words ($$$ aidiacht aiste anáil bacach bád bádóir
báicéir baincéir bainis béal buidéal caint
cat céad ceadúnas ceann ceart cinnúint
cléreach cliabh cogadh coileach coláiste
comhairle deis dochtúir))
(genders (list :f :f :f :m :m
:m :m :m :f :m :m
:f :m :m :m :m :m
:f :m :m :m :m
:m :f :f :m))
(declensions (list 3 4 3 1 1
3 3 3 2 1
1 2 1 1 1 1
1 3 1 1 1 1
4 4 2 3)))
(loop for word in words
for gender in genders
for declension in declensions
for c-g = (gender-of% :ga word)
for c-decl = (declension-of% :ga word)
do (assert (and (eql gender c-g) (eql declension c-decl))
nil
"~a is ~a, ~:r declension (computed ~:[✗~;✓~]~a ~:[✗~;✓~], ~:r declension)"
word gender declension
(eql gender c-g) (or c-g "could not decide")
(eql declension c-decl) (or c-decl "could not compute"))))
;;; Presentation and internalized forms.
(defun internalize-irish (word)
"Remove presentation forms for Irish"
(substitute-map '(#\ı #\i
#\ɑ #\a
#\⁊ #\&) word))
(defun present-irish (word)
"Create a “read-only” string that looks nicer, including the use of
dotless-i (ı) and the letter “latin alpha,“ (ɑ), the Tironian ampersand,
and fixing up some irregular hyphenation rules.
This is the preferred (although frequently enough, not the observed)
presentation form for Irish."
(let ((word1 (substitute-map '(#\i #\ı
#\a #\ɑ
#\A #\Ɑ
#\⁊ #\&) word)))
(when (or (search "t-" word1)
(search "n-" word1))
(setf word1 (cl-ppcre:regex-replace "\\b([tn])-([AOEUIÁÓÉÚÍ])" word1
"\\1\\2")))
(when (or (search "de " word1)
(search "do " word1)
(search "me " word1)
(search "ba " word1))
(setf word1 (cl-ppcre:register-groups-bind
(prelude preposition fh initial after)
("^(.*)\\b(ba|de|mo|do)\\s+(fh)?([aoeuiAOEUIáóéúíÁÓÉÚÍ])(.*)$"
word1)
(strcat prelude (char-string (elt preposition 0))
"'" ; apostrophe
fh initial after))))))
(defun irish-eclipsis (word)
"In certian grammatical constructions, the first consonant of an Irish
word may be “eclipsed” to change its sound. "
(strcat (case (elt word 0)
(#\b "m")
(#\c "g")
(#\d "n")
(#\f "bh")
(#\g "n")
(#\p "b")
(#\t "d")
((#\a #\o #\e #\u #\i
#\á #\ó #\é #\ú #\í) "n-")
(otherwise "")) word))
(defun irish-downcase-eclipsed (word)
"In Irish, eclipsis-added characters shouldn't be capitalized with the
rest of the word; e.g. as an “bPoblacht.“
It's technically allowed, but discouraged, in ALL CAPS writing."
(cond
((member (subseq word 0 2)
'("MB" "GC" "ND" "NG" "BP" "DT")
:test 'string-equal)
(strcat (string-downcase (subseq word 0 1))
(funcall (letter-case word) (subseq word 1))))
((string-equal (subseq word 0 3) "BHF")
(strcat "bh"
(funcall (letter-case word) (subseq word 2))))
(t word)))
(assert (equal (irish-downcase-eclipsed "Bpoblacht") "bPoblacht"))
(assert (equal (irish-downcase-eclipsed "BHFEAR") "bhFEAR"))
(defmacro with-irish-endings ((word) &body body)
`(block irish-endings
(let* ((last-vowel (or (position-if #'irish-vowel-p ,word :from-end t)
(progn
(warn "No vowels in ,word? ~A" ,word)
(return-from irish-endings ,word))))
(last-vowels-start
(if (and (plusp last-vowel)
(irish-vowel-p (elt ,word (1- last-vowel))))
(if (and (< 1 last-vowel)
(irish-vowel-p (elt ,word (- last-vowel 2))))
(- last-vowel 2)
(1- last-vowel))
last-vowel))
(vowels (subseq ,word last-vowels-start (1+ last-vowel)))
(ending (subseq ,word last-vowels-start)))
(flet ((replace-vowels (replacement)
(strcat (subseq ,word 0 last-vowels-start) replacement
(subseq ,word (1+ last-vowel))))
(replace-ending (replacement)
(strcat (subseq ,word 0 last-vowels-start) replacement))
(add-after-vowels (addition)
(strcat (subseq ,word 0 (1+ last-vowel)) addition
(subseq ,word (1+ last-vowel)))))
,@body))))
(defun caolú (word)
"Caolú is the Irish version of palatalisation."
(with-irish-endings (word)
(cond
((= (length word) last-vowel) word)
((or (string-equal "each" ending)
(string-equal "íoch" ending)) (replace-ending "igh"))
((string-equal "ach" ending) (replace-ending "aigh"))
(t
(string-case vowels
(("éa" "ia") (replace-vowels "éi"))
("ea" (replace-vowels "i")) ;; or ei; when?
(("io" "iu") (replace-vowels "i"))
("ío" (replace-vowels "í"))
(otherwise
(add-after-vowels "i")))))))
(assert (equalp (mapcar #'caolú
'("leanbh" "fear" "cliabh" "coileach" "leac"
"ceart" "céad" "líon" "bacach" "pian"
"neart" "léann" "míol" "gaiscíoch"))
'("linbh" "fir" "cléibh" "coiligh" "lic"
"cirt" "céid" "lín" "bacaigh" "péin"
"nirt" "léinn" "míl" "gaiscigh")))
NOTE : is asserted , but I think they meant fear→fir ?
;;; ditto for gaiscíoch→gaiscígh (gaiscigh)
(defun coimriú (word)
"Irish syncopation (shortening a syllable)"
(let* ((last-vowel-pos (position-if #'irish-vowel-p word :from-end t))
(ending-start (loop with index = last-vowel-pos
if (irish-vowel-p (elt word index))
do (setf index (1- index))
else return (1+ index))))
(if (or (= 1 (syllable-count% :ga word))
(= (1- (length word)) last-vowel-pos)
(find (elt word last-vowel-pos) "áóéúí")
( long - vowel - p% : ( subseq word ending - start ) ) ?
(not (find (elt word (1- ending-start)) "lmnr")))
word
(let* ((tail (subseq word (1+ last-vowel-pos)))
(tail (if (member tail '("rr" "ll" "mm") :test 'string-equal)
(subseq tail 0 1)
tail))
(prefix (subseq word (1- ending-start))))
(cl-ppcre:regex-replace
"(dn|nd)"
(cl-ppcre:regex-replace
"(ln|nl|dl)" ;; dl retained in writing?
(strcat prefix tail)
"ll")
"nn")))))
(defun leathnú (word)
"Make a word broad (in Irish)"
(with-irish-endings (word)
;; (format *trace-output* "~& Leathnú word ~A vowels ~A"
;; word vowels)
(let ((base (string-case vowels
(("ei" "i") (replace-vowels "ea"))
("éi" (replace-vowels "éa"))
("í" (replace-vowels "ío"))
("ui" (replace-vowels "o"))
("aí" (replace-vowels "aío"))
(otherwise
(if (and (< 1 (length vowels))
(char= #\i (last-elt vowels)))
(replace-vowels (subseq vowels 0 (1- (length vowels))))
word)))))
(strcat base
(case (last-elt base)
((#\r #\l #\m #\n) "a")
(otherwise ""))))))
(let ((slender-words '("múinteoir" "bliain" "feoil" "dochtúir" "fuil"
"baincéir" "greim" "móin" "altóir" "muir"))
(broad-words '("múinteora" "bliana" "feola" "dochtúra" "fola"
"baincéara" "greama" "móna" "altóra" "mara")))
(unless (equalp (mapcar #'leathnú slender-words) broad-words)
(#+irish-cerror
cerror
#+irish-cerror
"Continue, and look foolish when speaking Irish"
#-irish-cerror
warn
"The LEATHNÚ function (used in Irish grammar) is being tested
with a set of known-good word-forms, but something has gone awry
and it has failed to properly “broaden” the ending of one or
more of the words in the test set.
Slender forms: ~{~A~^, ~}
Computed broad forms: ~{~A~^, ~}
Correct broad forms: ~{~A~^, ~}"
slender-words (mapcar #'leathnú slender-words) broad-words)))
(defun leathnaítear (word)
"LEATHNAÍTEAR (lenition) is used to change the leading consonant in
certain situations in Irish grammar.
This does NOT enforce the dntls+dts nor m+bp exceptions.
Note that LEATHNÚ applies this to the final consonant, instead."
(flet ((lenite ()
(strcat (subseq word 0 1)
"h"
(subseq word 1))))
(cond
((member (elt word 0) '(#\b #\c #\d #\f #\g #\m #\p #\t))
(lenite))
((and (char= #\s (elt word 0))
(not (member (elt word 1) '(#\c #\p #\t #\m #\f))))
(lenite))
(t word))))
(defun-lang syllable-count (string)
(:en (loop
with counter = 0
with last-vowel-p = nil
for char across (string-downcase string)
for vowelp = (member char '(#\a #\o #\e #\u #\i))
when (or (and vowelp
(not last-vowel-p))
(member char '(#\é #\ö #\ï)))
do (incf counter)
do (setf last-vowel-p vowelp)
finally (return (max 1
(if (and (char= char #\e)
(not last-vowel-p))
(1- counter)
counter)))))
(:es (loop
with counter = 0
with last-i-p = nil
for char across (string-downcase string)
for vowelp = (member char '(#\a #\o #\e #\u #\i))
when (or (and vowelp
(not last-i-p))
(member char '(#\á #\ó #\é #\ú #\í)))
do (incf counter)
do (setf last-i-p (eql char #\i))
finally (return (max 1 counter))))
(:la (loop
with counter = 0
for char across (latin-normalize string)
when (member char '(#\a #\o #\e #\u #\i))
do (incf counter)
when (member char '(#\ā #\ē #\ī #\ō #\ū))
do (incf counter 2)
finally (return (max 1 counter))))
(:ga (loop
with counter = 0
with last-vowel-p = nil
for char across (string-downcase string)
for vowelp = (irish-vowel-p char)
when (and vowelp
(not last-vowel-p))
do (incf counter)
do (setf last-vowel-p vowelp)
finally (return (max 1 counter)))))
(defun-lang diphthongp (letters)
(:en (member (string-downcase letters)
($$$ ow ou ie igh oi oo ea ee ai) :test #'string-beginning))
(:la (member (string-downcase letters)
($$$ ae au ai ou ei) :test #'string-beginning))
(:ga (member (string-downcase letters)
($$$ ae eo ao abh amh agh adh)
:test #'string-beginning)))
(defun vowelp (letter)
(find letter "aoeuiáóéúíýàòèùìỳäöëüïÿāōēūīãõẽũĩỹąęųįøæœåŭαοευιωаоеуийюяэыё"))
(defun-lang long-vowel-p (syllable)
(:la (let* ((first-vowel-pos (position-if #'vowelp syllable))
(first-vowel (elt syllable first-vowel-pos)))
(and first-vowel-pos
(or (find first-vowel "āōēūī" :test #'char=)
(diphthongp% :la (subseq syllable first-vowel-pos))))))
(:ru (some (rcurry #'find "юяиеёь" :test #'char=) syllable))
(:en (if (and (= 2 (length syllable))
(not (vowelp (elt syllable 0)))
(alpha-char-p (elt syllable 0))
(vowelp (elt syllable 1)))
;; be, by, so, to, et al.
t
(let* ((first-vowel-pos (position-if #'vowelp syllable))
(first-vowel (elt syllable first-vowel-pos)))
(and first-vowel-pos
(or (find first-vowel "āōēūī" :test #'char=)
(and (find first-vowel "aoeui")
(or (and (< (1+ first-vowel-pos) (length syllable))
(find (elt syllable (1+ first-vowel-pos))
"aoeuiy"))
(and (< (+ 2 first-vowel-pos) (length syllable))
(find (elt syllable (+ 2 first-vowel-pos))
"aoeuiy")
(not (eql #\w (elt syllable (1+ first-vowel-pos))))
(not (eql #\x (elt syllable
(1+ first-vowel-pos))))))))))))
(:ga (etypecase syllable
(character
(find syllable "áóéúí"))
(string
(let* ((first-vowel-pos (position-if #'irish-vowel-p syllable))
(first-vowel (elt syllable first-vowel-pos)))
(or (find first-vowel "áóéúí")
(diphthongp% :ga (subseq syllable first-vowel-pos))))))))
(defun irish-plural-form (string)
(let* ((gender (gender-of% :ga string))
(declension (declension-of% :ga string))
(syllables (syllable-count% :ga string))
(multi-syllabic (< 1 syllables))
(len (length string)))
( format t " ~ & ~a = . ~:a , ~r syllable~:p "
;; string declension gender syllables)
(string-case string
;; some very irregular ones
("seoid" "seoda")
("bean" "mná")
("grasta" "grásta")
;; oliphaunt: probably irregulars?
("súil" "súila")
("deoir" "deora")
("cuibreach" "cubraigha")
;; oliphaunt: there are a few more irregulars to add, too.
(otherwise
(flet ((lessen (less)
(subseq string 0 (- len less))))
(cond
4 * -iú
(string-ends "iú" string))
;; observed, oliphaunt
(strcat (lessen 2) "ithe"))
4 * -ú
(eql (last-elt string) #\ú))
;; observed, oliphaunt
(strcat (lessen 1) "uíthe"))
4 ♀ [ rlnm]í
(eq :f gender)
(member (elt string (- len 2))
'(#\r #\l #\n #\m))
(eql (last-elt string) #\í))
(strcat (lessen 1) "ithe"))
4 ♀ [ íe ]
(eq :f gender)
(or (eql (last-elt string) #\í)
(eql (last-elt string) #\e))
(not (eql (elt string (- len 2)) #\t))
(not (eql (elt string (- len 2)) #\l)))
(strcat (lessen 1) "t" (last-elt string)))
4 - a
(eql (last-elt string) #\a))
(strcat string "í"))
1 ♂ , 2 ♀ long+r ( 1 - syl . )
(or (and (eq :m gender)
(= 1 declension))
(and (eq :f gender)
(= 2 declension)))
(char= #\r (last-elt string))
(or (diphthongp% :ga (subseq string
(- len 2)
len))
(long-vowel-p% :ga (elt string (- len 1)))))
(strcat string "tha") ; or -the
)
1 ♂ ,2 ♀ long+[ln ] ( 1 - syl . )
(or (and (eq :m gender)
(= 1 declension))
(and (eq :f gender)
(= 2 declension))
(= 3 declension))
(or (char= #\l (last-elt string))
(char= #\n (last-elt string)))
(or (diphthongp% :ga (subseq string
(1+ (or
(position-if (complement #'irish-vowel-p)
(subseq string 0 (1- len))
:from-end t)
-1))
len))
(long-vowel-p% :ga (elt string (- len 1)))))
(strcat string "ta") ; or -te?
)
2 ♀ -oeg & c ; 1 ♀ -ach ; 3/4 *
(eq :f gender)
(or (string-ends "eog" string)
(string-ends "óg" string)
(string-ends "lann" string)
(and multi-syllabic
(string-ends "each" string))
(equal string "binn")
(equal string "deoir")))
(and (= 1 declension)
(eq :f gender)
(string-ends "ach" string))
(= 3 declension)
(= 4 declension))
(leathnú string))
1 ♂ ,2 ♀ -ach , 3 * -éir & c , 4 * -ín,-a,-e ( mult . )
(or ;; (and (eq :m gender)
(= 1 declension )
;; (or (string-ends "adh" string)
( string - ends " " string ) ) )
(and (eq :f gender)
(= 2 declension)
(or (not (irish-broad-ending-p string))
(string-ends "ach" string)))
(and (= 3 declension)
(member string
'("éir" "eoir" "óir" "úir"
"cht" "áint" "úint" "irt")
:test #'string-ending))
(and (= 4 declension)
(or (string-ends "ín" string)
(string-ends "a" string)
(string-ends "e" string)))))
(strcat string "í")
;; rules read:
;; • add -(a)í
;; • -(e)adh, -(e)ach → (a)í
;; • -e → í
)
2 ♀
(eq :f gender))
(strcat string
(if (irish-broad-ending-p string)
"a"
"e")))
1 ♂ ,2 ♀ ,3 ♂ ,4 * — ( 1 - syl )
(or (and (eq :m gender)
(= 1 declension)
(not (irish-broad-ending-p string)))
(and (eq :f gender)
(= 2 declension)
(not (irish-broad-ending-p string)))
(and (eq :m gender)
(= 3 declension))
(= 4 declension)))
(strcat string "anna") ; -(e)anna??
)
1 ♂ , -[lnr ] ; 2 ♀ * , 3 -i[lnr ] , 4 * — 2 syl .
(eq :m gender)
(= 1 declension)
(let ((last (last-elt string)))
(or (char= #\l last)
(char= #\n last)
(char= #\r last))))
(and (= 2 declension)
(eq :f gender))
(and (= 3 declension)
(or (string-ends "il" string)
(string-ends "in" string)
(string-ends "ir" string)))
(= 4 declension))
(strcat string "acha") ; or -eacha
)
((and (= 1 declension) ; 1♂*
(eq :m gender))
(caolú string)
#+ (or)
((and (= 1 declension)
(eq :m gender))
;;; XXX probably special-case based on ending?
(strcat (coimriú string) "e")))
3 *
(strcat (coimriú string) "a"))
(t (warn "Unable to figure out the plural form of “~A” (~:R decl. ~A)"
string declension gender)
string)))))))
English exceptional plurals dictionaries .
(defvar english-defective-plurals (make-hash-table :test 'equal)
"Words with no actual plural forms")
(dolist (word ($$$ bison buffalo deer duck fish moose
pike plankton salmon sheep squid swine
trout algae marlin
furniture information
cannon blues iris cactus
meatus status specie
benshi otaku samurai
kiwi kowhai Māori Maori
marae tui waka wikiwiki
Swiss Québécois omnibus
Cherokee Cree Comanche Delaware Hopi
Iroquois Kiowa Navajo Ojibwa Sioux Zuni))
(setf (gethash word english-defective-plurals) word))
(defvar english-irregular-plurals (make-hash-table :test 'equal)
"Words whose plurals cannot be guessed using the heuristics")
(defvar english-irregular-plurals-reverse (make-hash-table :test 'equal)
"Words whose plurals cannot be guessed using the heuristics")
(loop for (s pl) in '(("child" "children") ("ox" "oxen")
("cow" "kine") ("foot" "feet")
("louse" "lice") ("mouse" "mice")
("tooth" "teeth") ("die" "dice") ("person" "people")
("genus" "genera") ("campus" "campuses")
("viscus" "viscera") ("virus" "viruses")
("opus" "opera") ("corpus" "corpera")
("cherub" "cherubim")
("person" "people") ; contentious, but usually right
("seraph" "seraphim") ("kibbutz" "kibbutzim")
("inuk" "inuit") ("inukshuk" "inukshuit")
("Iqalummiuq" "Iqalummiut")
("Nunavimmiuq" "Nunavimmiut")
("Nunavummiuq" "Nunavummiut")
("aide-de-camp" "aides-de-camp"))
do (setf (gethash s english-irregular-plurals) pl)
do (setf (gethash pl english-irregular-plurals-reverse) s))
(defun make-english-plural (string)
"Attempt to pluralize STRING using some heuristics that should work
well enough for many (most) English words. At least, an improvement upon
~:P …"
(when (search "person" string :test #'char-equal)
(setf string (regex-replace-pairs '(("PERSON" . "PEOPLE")
("person" . "people")) string)))
(funcall (letter-case string)
(let ((s (string-downcase string)))
(flet ((lessen (n)
(subseq s 0 (- (length s) n))))
(or (gethash s english-defective-plurals)
(gethash s english-irregular-plurals)
(string-ends-with-case s
;; Naturally, all of these are completely hueristic
;; and often incomplete, but they appear to cover
;; most irregular words without affecting too very
;; many words that they shouldn't.
("penny" (strcat (lessen 4) "ence"))
("eau" (strcat s "x"))
(("ies" "ese" "fish") s)
("ife" (strcat (lessen 2) "ves"))
(("eef" "eaf" "oaf") (strcat (lessen 1) "ves"))
("on" (strcat (lessen 2) "a"))
("ma" (strcat s "ta"))
(("ix" "ex") (strcat (lessen 1) "ces"))
("nx" (strcat (lessen 1) "ges"))
(("tum" "dum" "rum") (strcat (lessen 2) "a"))
(("nus" "rpus" "tus" "cus" "bus"
"lus" "eus" "gus" "mus") (strcat (lessen 2) "i"))
(("mna" "ula" "dia") (strcat (lessen 1) "ae"))
("pus" (strcat (lessen 2) "odes"))
("man" (strcat (lessen 2) "en"))
(("s" "x") (strcat s "es"))
("ey" (strcat s "s"))
("y" (let ((penult (elt s (- (length s) 2)))
(antepenult (elt s (- (length s) 3))))
(if (and (or (eql #\r penult) (char= #\l penult))
(vowelp antepenult))
(strcat (lessen 1) (char-string penult) "ies")
(strcat (lessen 1) "ies"))))
(otherwise
(strcat s "s"))))))))
(defun make-english-singular (string)
(when (search "people" string :test #'char-equal)
(setf string (regex-replace-pairs '(("PEOPLE" . "PERSON")
("people" . "person")) string)))
(funcall (letter-case string)
(let ((s (string-downcase string)))
(flet ((lessen (n)
(subseq s 0 (- (length s) n))))
(or (gethash s english-defective-plurals)
(gethash s english-irregular-plurals-reverse)
(string-ends-with-case s
("pence" (strcat (lessen 4) "enny"))
("eaux" (lessen 1))
(("ese" "fish") s)
(("eeves" "eaves" "oaves") (strcat (lessen 3) "f"))
("ives" (strcat (lessen 3) "fe"))
("mata" (lessen 2))
("oices" (lessen 1))
(("eces" "ices") (strcat (lessen 3) "x"))
(("ynges" "anges") (strcat (lessen 3) "x"))
("ae" (lessen 1))
("a" (strcat (lessen 1) "um")) ; could have easily been "on" though.
("i" (strcat (lessen 1) "us"))
("podes" (strcat (lessen 4) "us"))
("men" (strcat (lessen 2) "an"))
("im" (lessen 2))
(("ses" "xes") (lessen 2))
("ies" (strcat (lessen 3) "y"))
("s" (lessen 1))
(otherwise s)))))))
(loop for (sing pl) on ($$$
person-in-place people-in-places
country countries
monkey monkeys
penny pence
corpus corpera
octopus octopodes
deer deer
mouse mice
sword swords
address addresses
person-hour people-hours
woman women
child children
loaf loaves
knife knives
car cars
phalanx phalanges
larynx larynges
invoice invoices
) by #'cddr
do (assert (equal (make-english-singular pl) sing))
do (assert (equal (make-english-plural sing) pl)))
(defun-lang plural (count string)
(:en
(if (= 1 count)
string
(funcall
(letter-case string)
(make-english-plural string))))
(:fr (if (= 1 count)
string
FIXME
(t (funcall (letter-case string)
(strcat string "s"))))))
(:es (if (= 1 count)
string
FIXME
(t (funcall (letter-case string)
(strcat string "s"))))))
(:ga
(if (= 1 count)
string
(funcall (letter-case string)
(irish-plural-form string)))))
(defun-lang singular (plural-string)
(:en (make-english-singular plural-string)))
;;; Make sure that we create correct plural forms
(defun post-irish-plurals ()
(let ((singulars ($$$ bád fear béal íasc síol bacach taoiseach gaiscíoch
deireadh saol
beach bos scornach eaglais aisling
cainteoir gnólacht tincéir am
adhmáil beannacht ban-aba canúint droim
bata ciste cailín runaí rí bus
ordú cruinniú
bearna féile
aidiacht aiste anáil bacach bádóir
báicéir baincéir bainis béal buidéal caint
cat céad ceadúnas ceann ceart cinnúint
cléreach cliabh cogadh coileach coláiste
comhairle deis dochtúir
súil deoir cuibreach))
(plurals ($$$ báid fir béil éisc síl bacaigh taoisigh gaiscigh
deirí saolta
beacha bosa scornacha eaglaisí aislingí
cainteorí gnólachtaí tincéirí amanna
admhálacha beannachtaí ban-abaí canúintí dromanna
bataí cistí cailíní runaithe rithe busanna
orduíthe cruinnithe
bearnaí féilte
aidiachta aiste anála bacaigh bádóra báiceára
baincéara bainise béil buidéil cainte cait céid
ceadúnais cinn cirt cinniúna clérigh
cléibh cogaidh coiligh coláiste
comhairle deise dochtúra
súila deora cubraigha)))
(let ((computed (loop for s in singulars
collecting (plural% :ga 2 s))))
(loop for s in singulars
for pl in plurals
for c-pl in computed
if (equal pl c-pl)
count 1 into good
else do
(warn "Failure in Irish plural: ~A ⇒ ✓ ~A (got ✗“~A”) — ~:r decl. ~A"
s pl c-pl (declension-of% :ga s)(gender-of% :ga s))
finally (return (values good #1=(/ good (length singulars))
(strcat (round #1# 1/100) "%")))))))
(post-irish-plurals)
(define-constant spanish-numbers
(mapplist (key value)
($$$ 1 uno
2 dos
3 tres
4 cuatro
5 cinco
6 seis
7 siete
8 ocho
9 nueve
10 diez
11 once
12 doce
13 trece
14 catorce
15 quince
16 dieciséis
17 diecisiete
18 dieciocho
19 diecinueve
20 veinte
21 veintiuno
22 veintidós
23 veintitrés
24 veinticuatro
25 veinticinco
26 veintiséis
27 veintisiete
28 veintiocho
29 veintinueve
30 treinta
40 cuarenta
50 cincuenta
60 sesenta
70 setenta
80 ochenta
90 noventa
100 cien ;; ciento +
200 doscientos
300 trescientos
400 cuatrocientos
500 quinientos
600 seiscientos
700 setecientos
800 ochocientos
900 novecientos
1000 mil)
(list (parse-integer key) value))
:test 'equal)
(defun-lang counting (count string)
(:en (cond
((zerop count) (a/an/some% :en 0 string))
((< count 21) (funcall (letter-case string)
(format nil "~R ~A" count
(plural% :en count string))))
(t (format nil "~:D ~A" count (plural% :en count string)))))
(:es (cond
((zerop count) (a/an/some 0 string))
((= 1 count) (funcall (letter-case string)
(strcat (ecase (gender-of% :es string)
(:m "un ")
(:f "una "))
string)))
((< count 31) (funcall (letter-case string)
(strcat (getf spanish-numbers count)
" "
(plural% :es count string))))
(t (format nil "~,,'.:D ~A" count (plural% :es count string)))))
(:la (cond
((zerop count) (a/an/some 0 string))
((= 1 count) (funcall (letter-case string)
(strcat (ecase (gender-of% :la string)
(:m "unus ")
(:f "una ")
(:n "unum "))
string)))
((< count 11) (funcall (letter-case string)
(strcat (getf '(1 nil
2 "duō"
3 "trēs"
4 "quatuor"
5 "quinque"
6 "sex"
7 "septem"
8 "octem"
9 "novem"
10 "decem"
) count)
" "
(plural% :la count string))))
((< count 5000) (presentation-roman-numeral (format nil "~:@r ~A" count (plural% :es count string))))
(t (format nil "~,,'.:D ~A" count (plural% :es count string))))))
(assert (equal (counting% :es 2 "gato") "dos gatos"))
(assert (equal (counting% :es 1492 "gato") "1.492 gatos"))
(assert (equal (counting% :es 1 "gato") "un gato"))
(assert (equal (counting% :es 1 "casa") "una casa"))
(defun-lang a/an (string)
(:la string)
(:en (let ((letter (elt string 0)))
(case letter
((#\a #\e #\i #\o #\u #\h)
(concatenate 'string "an " string))
((#\A #\E #\I #\O #\U #\H)
(concatenate 'string (funcall (letter-case string) "an ") string))
(otherwise
(concatenate 'string (funcall (letter-case string) "a ") string)))))
(:es (strcat (funcall (letter-case string)
(ecase (gender-of% :es string)
((:m nil) "un ")
(:f "una "))) string))
(:fr (strcat (funcall (letter-case string)
(ecase (gender-of% :fr string)
((:m nil) "un ")
(:f "une "))) string))
(:ga string))
(defun-lang pluralp (string)
(:en (char-equal (last-elt string) #\s))
(:es (char-equal (last-elt string) #\s))
(:fr (char-equal (last-elt string) #\s)))
(defun-lang -the- (string)
(:la string)
(:ru string)
(:en (concatenate 'string (funcall (letter-case string) "the ") string))
(:es (strcat (funcall (letter-case string)
(ecase (pluralp% :es string)
(t (ecase (gender-of% :es string)
((:m nil) "los ")
(:f "las ")))
((nil) (ecase (gender-of% :es string)
((:m nil) "el ")
(:f "la "))))) string))
(:fr (strcat (funcall (letter-case string)
(ecase (pluralp% :es string)
(t "les ")
((nil) (ecase (gender-of% :es string)
((:m nil) (if (vowelp (first-elt string))
"l'"
"le "))
(:f "la "))))) string))
(:ga (concatenate 'string (funcall (letter-case string) "an ")
string)))
(defun-lang a/an/some (count string)
(:en (case count
(0 (concatenate 'string (funcall (letter-case string) "no ")
(plural% :en 0 string)))
(1 (a/an string))
(otherwise (concatenate 'string (funcall (letter-case string) "some ")
(plural% :en count string)))))
(:fr (case count
(0 (concatenate 'string (funcall (letter-case string) "sans ")
(plural% :fr 0 string)))
(1 (a/an string))
(otherwise (concatenate 'string (funcall (letter-case string) "des ")
(plural% :fr count string)))))
(:ga (plural% :ga count string)))
Credit for Irish language test cases to Irish language documents by
Amy de Buitléir , CC - BY 3.0 license , found at
;;; / …
/
;;; Human-friendly formats in and output
(defun range-size (numeric-range-string)
"Count the length of a range of numbers separated by -"
(if (find #\- numeric-range-string)
(destructuring-bind (start end)
(uiop:split-string numeric-range-string
:separator "-")
(1+ (- (parse-integer end) (parse-integer start))))
1))
(defun human-duration (seconds)
(cond
((< seconds 1/1000000000000000)
"instantly")
((< seconds 1/1000000000000)
(format nil "~d femtosecond~:p" (round (* seconds 1000000000000000))))
((< seconds 1/1000000000)
(format nil "~d picosecond~:p" (round (* seconds 1000000000000))))
((< seconds 1/1000000)
(format nil "~d nanosecond~:p" (round (* seconds 1000000000))))
((< seconds 1/1000)
(format nil "~d microsecond~:p" (round (* seconds 1000000))))
((< seconds 1)
(format nil "~d millisecond~:p" (round (* seconds 1000))))
((< seconds 90)
(format nil "~d second~:p" (round seconds)))
((< seconds (* 90 60))
(format nil "~d minutes" (round seconds 60)))
((< seconds (* 3 24 60 60))
(format nil "~d hours" (round seconds (* 60 60))))
((< seconds (* 6 7 24 60 60))
(format nil "~d days" (round seconds (* 24 60 60))))
((< seconds (* 75 7 24 60 60))
(format nil "~d weeks" (round seconds (* 7 24 60 60))))
(t (format nil "~:d years" (round seconds (* 365.2489 24 60 60))))))
(defun weekday-name (day-of-week)
(elt '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday") day-of-week))
(defun month-name (month)
(elt '("January" "February" "March"
"April" "May" "June"
"July" "August" "September"
"October" "November" "December")
month))
(defun human-future-time (universal-time)
(multiple-value-bind (sec min hour day month year day-of-week)
(decode-universal-time universal-time)
(multiple-value-bind (sec-now min-now hour-now
day-now month-now year-now
day-of-week-now)
(decode-universal-time (get-universal-time))
(cond
((and (= hour-now hour)
(= day-now day)
(= month-now month)
(= year-now year))
(format nil "in ~a at ~2,'0d:~2,'0d"
(human-duration (- universal-time (get-universal-time)))
hour min))
((and (= year-now year)
(= month-now month))
(format nil "on ~a the ~:r at ~2,'0d:~2,'0d"
(weekday-name day-of-week) day hour min))
(t (format nil "on ~a, ~:d ~a, ~d at ~2,'0d:~2,'0d"
(weekday-name day-of-week) day (month-name month) year
hour min))))))
| null | https://raw.githubusercontent.com/adventuring/tootsville.net/985c11a91dd1a21b77d7378362d86cf1c031b22c/src/lib/oliphaunt/i18n%2Bl10n.lisp | lisp | Genders of words which cannot be guessed by their declensions
Determine the gender and declension of a word
totally random guess
bad fallback
Presentation and internalized forms.
apostrophe
e.g. as an “bPoblacht.“
or ei; when?
ditto for gaiscíoch→gaiscígh (gaiscigh)
dl retained in writing?
(format *trace-output* "~& Leathnú word ~A vowels ~A"
word vowels)
be, by, so, to, et al.
string declension gender syllables)
some very irregular ones
oliphaunt: probably irregulars?
oliphaunt: there are a few more irregulars to add, too.
observed, oliphaunt
observed, oliphaunt
or -the
or -te?
1 ♀ -ach ; 3/4 *
(and (eq :m gender)
(or (string-ends "adh" string)
rules read:
• add -(a)í
• -(e)adh, -(e)ach → (a)í
• -e → í
-(e)anna??
2 ♀ * , 3 -i[lnr ] , 4 * — 2 syl .
or -eacha
1♂*
XXX probably special-case based on ending?
contentious, but usually right
Naturally, all of these are completely hueristic
and often incomplete, but they appear to cover
most irregular words without affecting too very
many words that they shouldn't.
could have easily been "on" though.
Make sure that we create correct plural forms
ciento +
/ …
Human-friendly formats in and output | (in-package :oliphaunt)
Internationalization and Localization Support
(define-constant +language-names+
'((:en "English" "English" "Language")
(:es "Español" "Spanish" "Idioma")
(:fr "Français" "French" "Langue")
(:ga "Gaeilge" "Irish" "Teanga")
(:ru "Русский" "Russian" "Язык")
(:la "Lingua Latina" "Latin" "Lingua"))
:test 'equalp)
(define-condition language-not-implemented-warning (warning)
((language :initarg :language :reader language-not-implemented)
(fn :initarg :function :reader language-not-implemented-function))
(:report (lambda (c s)
(format s "There is not an implementation of ƒ ~A for language ~A ~@[~{~*(~A/~A)~}~]"
(slot-value c 'fn)
(slot-value c 'language)
(assoc (language-not-implemented c) +language-names+)))))
(defmacro defun-lang (function (&rest lambda-list) &body bodies)
(let ((underlying (intern (concatenate 'string (string function) "%"))))
#+test-i18n
(let ((implemented (mapcar #'car bodies)))
(unless (every (rcurry #'member implemented)
(mapcar #'car +language-names+))
(warn "Defining ƒ ~A with partial language support: ~{~{~% • ~5A: ~20A ~:[ ✗ ~; ✓ ~]~}~}"
function
(mapcar (lambda (language)
(list (car language)
(third language)
(member (car language) implemented)))
+language-names+))))
`(progn
(defgeneric ,underlying (language ,@lambda-list)
,@(mapcar (lambda (body)
(let ((match (car body))
(code (cdr body)))
(unless (assoc match +language-names+)
(warn "Defining a handler for unrecognized language-code ~A in ƒ ~A"
match function))
`(:method ((language (eql ,match)) ,@lambda-list)
,@code)))
bodies)
(:method ((language t) ,@lambda-list)
(warn 'language-not-implemented-warning :language language :function ',function)
(,underlying :en ,@lambda-list)))
(defun ,function (,@lambda-list)
(,underlying (or (get-lang) :en)
,@lambda-list)))))
(defun char-string (char)
(make-string 1 :initial-element char))
(defun irish-broad-vowel-p (char)
(member char '(#\a #\o #\u #\á #\ó #\ú)))
(defun irish-broad-ending-p (word)
(irish-broad-vowel-p (last-elt (remove-if-not #'irish-vowel-p word))))
(defvar irish-gender-dictionary (make-hash-table :test 'equal))
(dolist (word ($$$ adharc baintreach báisteach buíon caor cearc
ciall cloch cos craobh críoch cros dámh
dealbh eangach fadhb fearg ficheall fréamh
gaoth géag gealt girseach grian iall iníon
lámh leac long luch méar mian mias muc
nead pian sceach scian scornach slat
sluasaid srón téad tonn ubh banríon Cáisc
cuid díolaim Eoraip feag feoil muir scread
rogha teanga bearna veain beach))
(setf (gethash word irish-gender-dictionary) :f))
(dolist (word ($$$ am anam áth béas bláth cath cíos cith
crios dath dream droim eas fíon flaith
greim loch lus luach modh rámh rang
rás roth rud sioc taom teas tréad
im sliabh ainm máistir seans club dlí
rince coláiste))
(setf (gethash word irish-gender-dictionary) :m))
(defvar irish-declension-dictionary (make-hash-table :test 'equal))
(dolist (word ($$$ im sliabh
adharc baintreach báisteach buíon caor cearc ciall
cloch cos craobh críoch cros dámh dealbh eangach
fadhb fearg ficheall fréamh gaoth géag gealt
girseach grian iall iníon lámh leac long luch
méar mian mias muc nead pian sceach scian
scornach slat sluasaid srón téad tonn ubh))
(setf (gethash word irish-declension-dictionary) 2))
(dolist (word ($$$ am anam áth béas bláth cath cíos cith crios
dath dream droim eas fíon flaith greim
loch lus luach modh rámh rang rás roth rud
sioc taom teas tréad
banríon Cáisc cuid díolaim Eoraip
feag feoil muir scread))
(setf (gethash word irish-declension-dictionary) 3))
(dolist (word ($$$ rogha teanga bearna ainm máistir seans
club veain dlí rince))
(setf (gethash word irish-declension-dictionary) 4))
(defvar english-gender-dictionary (make-hash-table :test 'equal))
(dolist (word '(car automobile ship plane
airplane boat vessel
cat kitty hen chick peahen
girl woman lady miss mistress mrs ms
chauffeuse masseuse stewardess
madam))
(setf (gethash (string word) english-gender-dictionary) :f))
(dolist (word '(man boy guy bloke fellow dude
dog cock rooster peacock
mister master mr))
(setf (gethash (string word) english-gender-dictionary) :m))
(defun latin-normalize (string)
(regex-replace-pairs '(("i" "j")
("v" "u")
("w" "uu")
("æ" "ae")
("œ" "oe"))
(string-downcase string)))
(defun latin-presentation-form (string)
(funcall (letter-case string)
(regex-replace-pairs '(("ae" "æ")
("oe" "œ")
("u" "v"))
(string-downcase string))))
(defun-lang gender-of (noun)
(:en (if-let ((gender (gethash (string-upcase noun) english-gender-dictionary)))
gender
:n))
(:es (string-ends-with-case noun
("o" :m)
("a" :f)
(otherwise :m)))
(:fr (if (member (last-elt noun) '(#\e #\E))
:f
:m))
(:la (or (gethash (latin-normalize noun) latin-gender-dictionary)
(case (declension-of noun)
(1 :f)
(2 (string-ends-with-case noun
("us" :m)
("um" :n)))
(4 :f)
(5 :f))))
(:ga (or (gethash (string-downcase noun) irish-gender-dictionary)
(string-ends-with-case noun
(("e" "í") :f)
(($$$ a o e u i
á ó é ú í
ín) :m)
(($$$ áil úil ail úint cht irt) :f)
(($$$ éir eoir óir úir) :m)
(("óg" "eog" "lann") :f)
(otherwise
(if (irish-broad-ending-p noun)
:m
:f))))))
(defun-lang declension-of (noun)
(:en nil)
(:la (if-let (genitive (gethash (latin-normalize noun) latin-genitives))
(string-ends-with-case genitive
("ae" 1)
("ēī" 5)
("ī" 2)
("is" 3)
("ūs" 4)))
("a" 1)
could be 4 , but less likely …
("um" 2)
("ēs" 5)
(otherwise 3)))
(:ga (if-let ((overrule (gethash noun irish-declension-dictionary)))
overrule
(cond
((or (eql (last-elt noun) #\e)
(eql (last-elt noun) #\í)
(irish-vowel-p (last-elt noun))
(string-ends "ín" noun)) 4)
((or (member noun '("áil" "úil" "ail" "úint" "cht" "irt"
"éir" "eoir" "óir" "úir")
:test #'string-ending)) 3)
((or (string-ends "eog" noun)
(string-ends "óg" noun)
(string-ends "lann" noun)
(not (irish-broad-ending-p noun))) 2)
((irish-broad-ending-p noun) 1)
(t (warn "Can't guess declension () of “~a”" noun))))))
(defvar latin-genitives (make-hash-table :test #'equal))
(defvar latin-gender-dictionary (make-hash-table :test #'equal))
(let ((array (mapcar (lambda (word)
(let ((parts (split-sequence #\space (substitute #\space #\, word) :remove-empty-subseqs t :count 3)))
(if (char= (elt (elt parts 1) 0) #\-)
(list (elt parts 0) (keyword* (elt parts 1)) (keyword* (elt parts 2)))
(list (elt parts 0) (elt parts 1) (keyword* (elt parts 2))))))
'("accola -ae m"
"advena -ae m"
"agricola, -ae, m"
"agripeta, -ae m"
"alienigena -ae m"
"alipta -ae m"
"aliptes aliptae m"
"amniclola -ae m"
"anagnostes anagnostae m"
"analecta, -ae m"
"anguigena, -ae m"
"anthias, -ae m"
"archipirata, -ae m"
"artopta, -ae m"
"athleta, -ae m"
"auriga, -ae m"
"Abnoba, -ae m"
"Acestes, Acestae m"
"Achates, -ae m"
"Acmonides, -ae m"
"Actorides, -ae m"
"Aeeta, -ae m"
"Aeneas, -ae m"
"Aenides, -ae m"
"Agamemnonides, -ae m"
"Agrippa, -ae m"
"Ahala, -ae m"
"Amisia, -ae m"
"Amphiaraides, -ae m"
"Ampycides, -ae m"
"Amyntas, -ae m"
"Amyntiades, -ae m"
"Anas, Anae m"
"Anaxagoras, -ae m"
"Anchises, -ae m"
"Anchisiades, -ae m"
"Antiphates, -ae m"
"Antisthenes, -ae m"
"Aonides, -ae m"
"Apolloniates, -ae m"
"Appenninicola, -ae c"
"Appenninigena, -ae c"
"Arabarches, -ae m"
"Archias, -ae m"
"Arestorides, -ae m"
"Asopiades, -ae m"
"Astacides, -ae m"
"Athamantiades, -ae m"
"Atlantiades, -ae m"
"Atrida Atridae m"
"Atrides, Atridae m"
"Atta, -ae m"
"Aurigena, -ae m"
"Axona, -ae m"
"brabeuta, -ae m"
"bucaeda, -ae m"
"Bacchiadae, -ārum m"
"Bagoas, -ae m"
"Bagrada, -ae m"
"Baptae, -ārum m"
"Barcas, -ae m"
"Bastarnae -ārum m"
"Basternae, -ārum m"
"Battiades, -ae m"
"Belgae, -ārum m"
"Bellerophontes, -ae m"
"Belides, -ae m"
"Bootes, -ae m"
"Boreas, -ae m"
"cacula, -ae m"
"caecias, -ae m"
"cataphractes, -ae m"
"cerastes, -ae m"
"choraules, -ae m"
"citharista, -ae m"
"clepta, -ae m"
"cometes, -ae m"
"conchita, -ae m"
"conlega, -ae m"
"convenae, -ārum c"
"conviva, -ae m"
"coprea, -ae m"
"Caligula, -ae m"
"Caracalla, -ae m"
"Catilina, -ae m"
"Cecropides, -ae m"
"Celtae, -ārum m"
"Charondas, -ae m"
"Chrysas, -ae m"
"Chryses, -ae m"
"Cinga, -ae m"
"Cinna, -ae m"
"Cinyras, -ae m"
"Clinias, -ae m"
"Cliniades, -ae m"
"Columella, -ae m"
"Cotta, -ae m"
"Crotoniates, -ae m"
"Crotopiades, -ae m"
"danista, -ae m"
"dioecetes, -ae m"
"draconigena, -ae m"
"drapeta, -ae m"
"Dalmatae, -ārum m"
"Dolabella, -ae m"
"etesiae, -ārum m"
"Eleates, -ae m"
"Eumolpidae, -ārum m"
"faeniseca, -ae m"
"fratricida, -ae m"
"geometres, -ae m"
"grammatista, -ae m"
"gumia, -ae m"
"Galatae, -ārum m"
"Galba, -ae m"
"Gangaridae, -ārum m "
"Geta, -ae, m"
"Gorgias, -ae m"
"Graiugena, -ae m"
"Gyas, -ae m"
"Gyges, -ae m"
"halophanta, -ae m"
"heuretes, -ae m"
"hybrida hybridae m"
"hibrida -ae m"
"hippotoxota, -ae m"
"homicida, -ae c"
"Heraclides, -ae m"
"Herma -ae m"
"Hermes Hermae m"
"Hilotae, -ārum m"
"Ilotae Itolārum m"
"Hippias, -ae m"
"Hippomenes, -ae m"
"Hippotades, -ae m"
"ignigena, -ae m"
"incola, -ae m"
"Ianigena, -ae m"
"Iarbas (Iarba), -ae"
"Iliades, -ae m"
"Iuba, -ae m"
"Iugurtha, -ae m"
"Iura, -ae m"
"lanista, -ae m"
"latebricola, -ae m"
"lixa, -ae m"
"Ladas, -ae m"
"Lamia, -ae m"
"Lapithae, -ārum m"
"Leonidas, -ae m"
"nauta, -ae m"
"parricida, -ae m"
"pirata, -ae m"
"poeta, -ae m"
"Proca, -ae m"
"tata, -ae m"
"umbraticola, -ae m"
"xiphias, -ae m"
))))
(flet ((apply-genitive (gen* nom)
(etypecase gen*
(string gen*)
(keyword (ecase gen*
(:-ae (if (char= (last-elt nom) #\a)
(strcat nom "e")
(strcat nom "ae")))
((:-arum :-ārum) (strcat (if (string-ends "ae" nom)
(subseq nom (- (length nom) 2))
nom)
"ārum"))
((:-ī :-i) (strcat (if (or (string-ends "um" nom)
(string-ends "us" nom))
(subseq nom 0 (- (length nom) 2))
nom)
"ī"))
((:-orum :-ōrum) (strcat (if (string-ends "ae" nom)
(subseq nom (- (length nom) 2))
nom)
"ōrum"))
(:-is (strcat nom "is"))
(:-ium (strcat nom "ium"))
((:-us :-ūs) (strcat (if (string-ends "us" nom)
(subseq nom 0 (- (length nom) 2))
nom)
"ūs"))
((:-ei :-ēī) (if (string-ends "ēs" nom)
(strcat (subseq nom 0 (- (length nom) 1)) "ī")
(strcat nom "ēī"))))))))
(dolist (word array)
(destructuring-bind (nom gen* &optional gender) word
(let ((gen (apply-genitive gen* nom)))
(setf (gethash (latin-normalize nom) latin-genitives) (latin-normalize gen))
(when gender
(setf (gethash (latin-normalize nom) latin-gender-dictionary) gender)))))))
(let ((words ($$$ aidiacht aiste anáil bacach bád bádóir
báicéir baincéir bainis béal buidéal caint
cat céad ceadúnas ceann ceart cinnúint
cléreach cliabh cogadh coileach coláiste
comhairle deis dochtúir))
(genders (list :f :f :f :m :m
:m :m :m :f :m :m
:f :m :m :m :m :m
:f :m :m :m :m
:m :f :f :m))
(declensions (list 3 4 3 1 1
3 3 3 2 1
1 2 1 1 1 1
1 3 1 1 1 1
4 4 2 3)))
(loop for word in words
for gender in genders
for declension in declensions
for c-g = (gender-of% :ga word)
for c-decl = (declension-of% :ga word)
do (assert (and (eql gender c-g) (eql declension c-decl))
nil
"~a is ~a, ~:r declension (computed ~:[✗~;✓~]~a ~:[✗~;✓~], ~:r declension)"
word gender declension
(eql gender c-g) (or c-g "could not decide")
(eql declension c-decl) (or c-decl "could not compute"))))
(defun internalize-irish (word)
"Remove presentation forms for Irish"
(substitute-map '(#\ı #\i
#\ɑ #\a
#\⁊ #\&) word))
(defun present-irish (word)
"Create a “read-only” string that looks nicer, including the use of
dotless-i (ı) and the letter “latin alpha,“ (ɑ), the Tironian ampersand,
and fixing up some irregular hyphenation rules.
This is the preferred (although frequently enough, not the observed)
presentation form for Irish."
(let ((word1 (substitute-map '(#\i #\ı
#\a #\ɑ
#\A #\Ɑ
#\⁊ #\&) word)))
(when (or (search "t-" word1)
(search "n-" word1))
(setf word1 (cl-ppcre:regex-replace "\\b([tn])-([AOEUIÁÓÉÚÍ])" word1
"\\1\\2")))
(when (or (search "de " word1)
(search "do " word1)
(search "me " word1)
(search "ba " word1))
(setf word1 (cl-ppcre:register-groups-bind
(prelude preposition fh initial after)
("^(.*)\\b(ba|de|mo|do)\\s+(fh)?([aoeuiAOEUIáóéúíÁÓÉÚÍ])(.*)$"
word1)
(strcat prelude (char-string (elt preposition 0))
fh initial after))))))
(defun irish-eclipsis (word)
"In certian grammatical constructions, the first consonant of an Irish
word may be “eclipsed” to change its sound. "
(strcat (case (elt word 0)
(#\b "m")
(#\c "g")
(#\d "n")
(#\f "bh")
(#\g "n")
(#\p "b")
(#\t "d")
((#\a #\o #\e #\u #\i
#\á #\ó #\é #\ú #\í) "n-")
(otherwise "")) word))
(defun irish-downcase-eclipsed (word)
"In Irish, eclipsis-added characters shouldn't be capitalized with the
It's technically allowed, but discouraged, in ALL CAPS writing."
(cond
((member (subseq word 0 2)
'("MB" "GC" "ND" "NG" "BP" "DT")
:test 'string-equal)
(strcat (string-downcase (subseq word 0 1))
(funcall (letter-case word) (subseq word 1))))
((string-equal (subseq word 0 3) "BHF")
(strcat "bh"
(funcall (letter-case word) (subseq word 2))))
(t word)))
(assert (equal (irish-downcase-eclipsed "Bpoblacht") "bPoblacht"))
(assert (equal (irish-downcase-eclipsed "BHFEAR") "bhFEAR"))
(defmacro with-irish-endings ((word) &body body)
`(block irish-endings
(let* ((last-vowel (or (position-if #'irish-vowel-p ,word :from-end t)
(progn
(warn "No vowels in ,word? ~A" ,word)
(return-from irish-endings ,word))))
(last-vowels-start
(if (and (plusp last-vowel)
(irish-vowel-p (elt ,word (1- last-vowel))))
(if (and (< 1 last-vowel)
(irish-vowel-p (elt ,word (- last-vowel 2))))
(- last-vowel 2)
(1- last-vowel))
last-vowel))
(vowels (subseq ,word last-vowels-start (1+ last-vowel)))
(ending (subseq ,word last-vowels-start)))
(flet ((replace-vowels (replacement)
(strcat (subseq ,word 0 last-vowels-start) replacement
(subseq ,word (1+ last-vowel))))
(replace-ending (replacement)
(strcat (subseq ,word 0 last-vowels-start) replacement))
(add-after-vowels (addition)
(strcat (subseq ,word 0 (1+ last-vowel)) addition
(subseq ,word (1+ last-vowel)))))
,@body))))
(defun caolú (word)
"Caolú is the Irish version of palatalisation."
(with-irish-endings (word)
(cond
((= (length word) last-vowel) word)
((or (string-equal "each" ending)
(string-equal "íoch" ending)) (replace-ending "igh"))
((string-equal "ach" ending) (replace-ending "aigh"))
(t
(string-case vowels
(("éa" "ia") (replace-vowels "éi"))
(("io" "iu") (replace-vowels "i"))
("ío" (replace-vowels "í"))
(otherwise
(add-after-vowels "i")))))))
(assert (equalp (mapcar #'caolú
'("leanbh" "fear" "cliabh" "coileach" "leac"
"ceart" "céad" "líon" "bacach" "pian"
"neart" "léann" "míol" "gaiscíoch"))
'("linbh" "fir" "cléibh" "coiligh" "lic"
"cirt" "céid" "lín" "bacaigh" "péin"
"nirt" "léinn" "míl" "gaiscigh")))
NOTE : is asserted , but I think they meant fear→fir ?
(defun coimriú (word)
"Irish syncopation (shortening a syllable)"
(let* ((last-vowel-pos (position-if #'irish-vowel-p word :from-end t))
(ending-start (loop with index = last-vowel-pos
if (irish-vowel-p (elt word index))
do (setf index (1- index))
else return (1+ index))))
(if (or (= 1 (syllable-count% :ga word))
(= (1- (length word)) last-vowel-pos)
(find (elt word last-vowel-pos) "áóéúí")
( long - vowel - p% : ( subseq word ending - start ) ) ?
(not (find (elt word (1- ending-start)) "lmnr")))
word
(let* ((tail (subseq word (1+ last-vowel-pos)))
(tail (if (member tail '("rr" "ll" "mm") :test 'string-equal)
(subseq tail 0 1)
tail))
(prefix (subseq word (1- ending-start))))
(cl-ppcre:regex-replace
"(dn|nd)"
(cl-ppcre:regex-replace
(strcat prefix tail)
"ll")
"nn")))))
(defun leathnú (word)
"Make a word broad (in Irish)"
(with-irish-endings (word)
(let ((base (string-case vowels
(("ei" "i") (replace-vowels "ea"))
("éi" (replace-vowels "éa"))
("í" (replace-vowels "ío"))
("ui" (replace-vowels "o"))
("aí" (replace-vowels "aío"))
(otherwise
(if (and (< 1 (length vowels))
(char= #\i (last-elt vowels)))
(replace-vowels (subseq vowels 0 (1- (length vowels))))
word)))))
(strcat base
(case (last-elt base)
((#\r #\l #\m #\n) "a")
(otherwise ""))))))
(let ((slender-words '("múinteoir" "bliain" "feoil" "dochtúir" "fuil"
"baincéir" "greim" "móin" "altóir" "muir"))
(broad-words '("múinteora" "bliana" "feola" "dochtúra" "fola"
"baincéara" "greama" "móna" "altóra" "mara")))
(unless (equalp (mapcar #'leathnú slender-words) broad-words)
(#+irish-cerror
cerror
#+irish-cerror
"Continue, and look foolish when speaking Irish"
#-irish-cerror
warn
"The LEATHNÚ function (used in Irish grammar) is being tested
with a set of known-good word-forms, but something has gone awry
and it has failed to properly “broaden” the ending of one or
more of the words in the test set.
Slender forms: ~{~A~^, ~}
Computed broad forms: ~{~A~^, ~}
Correct broad forms: ~{~A~^, ~}"
slender-words (mapcar #'leathnú slender-words) broad-words)))
(defun leathnaítear (word)
"LEATHNAÍTEAR (lenition) is used to change the leading consonant in
certain situations in Irish grammar.
This does NOT enforce the dntls+dts nor m+bp exceptions.
Note that LEATHNÚ applies this to the final consonant, instead."
(flet ((lenite ()
(strcat (subseq word 0 1)
"h"
(subseq word 1))))
(cond
((member (elt word 0) '(#\b #\c #\d #\f #\g #\m #\p #\t))
(lenite))
((and (char= #\s (elt word 0))
(not (member (elt word 1) '(#\c #\p #\t #\m #\f))))
(lenite))
(t word))))
(defun-lang syllable-count (string)
(:en (loop
with counter = 0
with last-vowel-p = nil
for char across (string-downcase string)
for vowelp = (member char '(#\a #\o #\e #\u #\i))
when (or (and vowelp
(not last-vowel-p))
(member char '(#\é #\ö #\ï)))
do (incf counter)
do (setf last-vowel-p vowelp)
finally (return (max 1
(if (and (char= char #\e)
(not last-vowel-p))
(1- counter)
counter)))))
(:es (loop
with counter = 0
with last-i-p = nil
for char across (string-downcase string)
for vowelp = (member char '(#\a #\o #\e #\u #\i))
when (or (and vowelp
(not last-i-p))
(member char '(#\á #\ó #\é #\ú #\í)))
do (incf counter)
do (setf last-i-p (eql char #\i))
finally (return (max 1 counter))))
(:la (loop
with counter = 0
for char across (latin-normalize string)
when (member char '(#\a #\o #\e #\u #\i))
do (incf counter)
when (member char '(#\ā #\ē #\ī #\ō #\ū))
do (incf counter 2)
finally (return (max 1 counter))))
(:ga (loop
with counter = 0
with last-vowel-p = nil
for char across (string-downcase string)
for vowelp = (irish-vowel-p char)
when (and vowelp
(not last-vowel-p))
do (incf counter)
do (setf last-vowel-p vowelp)
finally (return (max 1 counter)))))
(defun-lang diphthongp (letters)
(:en (member (string-downcase letters)
($$$ ow ou ie igh oi oo ea ee ai) :test #'string-beginning))
(:la (member (string-downcase letters)
($$$ ae au ai ou ei) :test #'string-beginning))
(:ga (member (string-downcase letters)
($$$ ae eo ao abh amh agh adh)
:test #'string-beginning)))
(defun vowelp (letter)
(find letter "aoeuiáóéúíýàòèùìỳäöëüïÿāōēūīãõẽũĩỹąęųįøæœåŭαοευιωаоеуийюяэыё"))
(defun-lang long-vowel-p (syllable)
(:la (let* ((first-vowel-pos (position-if #'vowelp syllable))
(first-vowel (elt syllable first-vowel-pos)))
(and first-vowel-pos
(or (find first-vowel "āōēūī" :test #'char=)
(diphthongp% :la (subseq syllable first-vowel-pos))))))
(:ru (some (rcurry #'find "юяиеёь" :test #'char=) syllable))
(:en (if (and (= 2 (length syllable))
(not (vowelp (elt syllable 0)))
(alpha-char-p (elt syllable 0))
(vowelp (elt syllable 1)))
t
(let* ((first-vowel-pos (position-if #'vowelp syllable))
(first-vowel (elt syllable first-vowel-pos)))
(and first-vowel-pos
(or (find first-vowel "āōēūī" :test #'char=)
(and (find first-vowel "aoeui")
(or (and (< (1+ first-vowel-pos) (length syllable))
(find (elt syllable (1+ first-vowel-pos))
"aoeuiy"))
(and (< (+ 2 first-vowel-pos) (length syllable))
(find (elt syllable (+ 2 first-vowel-pos))
"aoeuiy")
(not (eql #\w (elt syllable (1+ first-vowel-pos))))
(not (eql #\x (elt syllable
(1+ first-vowel-pos))))))))))))
(:ga (etypecase syllable
(character
(find syllable "áóéúí"))
(string
(let* ((first-vowel-pos (position-if #'irish-vowel-p syllable))
(first-vowel (elt syllable first-vowel-pos)))
(or (find first-vowel "áóéúí")
(diphthongp% :ga (subseq syllable first-vowel-pos))))))))
(defun irish-plural-form (string)
(let* ((gender (gender-of% :ga string))
(declension (declension-of% :ga string))
(syllables (syllable-count% :ga string))
(multi-syllabic (< 1 syllables))
(len (length string)))
( format t " ~ & ~a = . ~:a , ~r syllable~:p "
(string-case string
("seoid" "seoda")
("bean" "mná")
("grasta" "grásta")
("súil" "súila")
("deoir" "deora")
("cuibreach" "cubraigha")
(otherwise
(flet ((lessen (less)
(subseq string 0 (- len less))))
(cond
4 * -iú
(string-ends "iú" string))
(strcat (lessen 2) "ithe"))
4 * -ú
(eql (last-elt string) #\ú))
(strcat (lessen 1) "uíthe"))
4 ♀ [ rlnm]í
(eq :f gender)
(member (elt string (- len 2))
'(#\r #\l #\n #\m))
(eql (last-elt string) #\í))
(strcat (lessen 1) "ithe"))
4 ♀ [ íe ]
(eq :f gender)
(or (eql (last-elt string) #\í)
(eql (last-elt string) #\e))
(not (eql (elt string (- len 2)) #\t))
(not (eql (elt string (- len 2)) #\l)))
(strcat (lessen 1) "t" (last-elt string)))
4 - a
(eql (last-elt string) #\a))
(strcat string "í"))
1 ♂ , 2 ♀ long+r ( 1 - syl . )
(or (and (eq :m gender)
(= 1 declension))
(and (eq :f gender)
(= 2 declension)))
(char= #\r (last-elt string))
(or (diphthongp% :ga (subseq string
(- len 2)
len))
(long-vowel-p% :ga (elt string (- len 1)))))
)
1 ♂ ,2 ♀ long+[ln ] ( 1 - syl . )
(or (and (eq :m gender)
(= 1 declension))
(and (eq :f gender)
(= 2 declension))
(= 3 declension))
(or (char= #\l (last-elt string))
(char= #\n (last-elt string)))
(or (diphthongp% :ga (subseq string
(1+ (or
(position-if (complement #'irish-vowel-p)
(subseq string 0 (1- len))
:from-end t)
-1))
len))
(long-vowel-p% :ga (elt string (- len 1)))))
)
(eq :f gender)
(or (string-ends "eog" string)
(string-ends "óg" string)
(string-ends "lann" string)
(and multi-syllabic
(string-ends "each" string))
(equal string "binn")
(equal string "deoir")))
(and (= 1 declension)
(eq :f gender)
(string-ends "ach" string))
(= 3 declension)
(= 4 declension))
(leathnú string))
1 ♂ ,2 ♀ -ach , 3 * -éir & c , 4 * -ín,-a,-e ( mult . )
(= 1 declension )
( string - ends " " string ) ) )
(and (eq :f gender)
(= 2 declension)
(or (not (irish-broad-ending-p string))
(string-ends "ach" string)))
(and (= 3 declension)
(member string
'("éir" "eoir" "óir" "úir"
"cht" "áint" "úint" "irt")
:test #'string-ending))
(and (= 4 declension)
(or (string-ends "ín" string)
(string-ends "a" string)
(string-ends "e" string)))))
(strcat string "í")
)
2 ♀
(eq :f gender))
(strcat string
(if (irish-broad-ending-p string)
"a"
"e")))
1 ♂ ,2 ♀ ,3 ♂ ,4 * — ( 1 - syl )
(or (and (eq :m gender)
(= 1 declension)
(not (irish-broad-ending-p string)))
(and (eq :f gender)
(= 2 declension)
(not (irish-broad-ending-p string)))
(and (eq :m gender)
(= 3 declension))
(= 4 declension)))
)
(eq :m gender)
(= 1 declension)
(let ((last (last-elt string)))
(or (char= #\l last)
(char= #\n last)
(char= #\r last))))
(and (= 2 declension)
(eq :f gender))
(and (= 3 declension)
(or (string-ends "il" string)
(string-ends "in" string)
(string-ends "ir" string)))
(= 4 declension))
)
(eq :m gender))
(caolú string)
#+ (or)
((and (= 1 declension)
(eq :m gender))
(strcat (coimriú string) "e")))
3 *
(strcat (coimriú string) "a"))
(t (warn "Unable to figure out the plural form of “~A” (~:R decl. ~A)"
string declension gender)
string)))))))
English exceptional plurals dictionaries .
(defvar english-defective-plurals (make-hash-table :test 'equal)
"Words with no actual plural forms")
(dolist (word ($$$ bison buffalo deer duck fish moose
pike plankton salmon sheep squid swine
trout algae marlin
furniture information
cannon blues iris cactus
meatus status specie
benshi otaku samurai
kiwi kowhai Māori Maori
marae tui waka wikiwiki
Swiss Québécois omnibus
Cherokee Cree Comanche Delaware Hopi
Iroquois Kiowa Navajo Ojibwa Sioux Zuni))
(setf (gethash word english-defective-plurals) word))
(defvar english-irregular-plurals (make-hash-table :test 'equal)
"Words whose plurals cannot be guessed using the heuristics")
(defvar english-irregular-plurals-reverse (make-hash-table :test 'equal)
"Words whose plurals cannot be guessed using the heuristics")
(loop for (s pl) in '(("child" "children") ("ox" "oxen")
("cow" "kine") ("foot" "feet")
("louse" "lice") ("mouse" "mice")
("tooth" "teeth") ("die" "dice") ("person" "people")
("genus" "genera") ("campus" "campuses")
("viscus" "viscera") ("virus" "viruses")
("opus" "opera") ("corpus" "corpera")
("cherub" "cherubim")
("seraph" "seraphim") ("kibbutz" "kibbutzim")
("inuk" "inuit") ("inukshuk" "inukshuit")
("Iqalummiuq" "Iqalummiut")
("Nunavimmiuq" "Nunavimmiut")
("Nunavummiuq" "Nunavummiut")
("aide-de-camp" "aides-de-camp"))
do (setf (gethash s english-irregular-plurals) pl)
do (setf (gethash pl english-irregular-plurals-reverse) s))
(defun make-english-plural (string)
"Attempt to pluralize STRING using some heuristics that should work
well enough for many (most) English words. At least, an improvement upon
~:P …"
(when (search "person" string :test #'char-equal)
(setf string (regex-replace-pairs '(("PERSON" . "PEOPLE")
("person" . "people")) string)))
(funcall (letter-case string)
(let ((s (string-downcase string)))
(flet ((lessen (n)
(subseq s 0 (- (length s) n))))
(or (gethash s english-defective-plurals)
(gethash s english-irregular-plurals)
(string-ends-with-case s
("penny" (strcat (lessen 4) "ence"))
("eau" (strcat s "x"))
(("ies" "ese" "fish") s)
("ife" (strcat (lessen 2) "ves"))
(("eef" "eaf" "oaf") (strcat (lessen 1) "ves"))
("on" (strcat (lessen 2) "a"))
("ma" (strcat s "ta"))
(("ix" "ex") (strcat (lessen 1) "ces"))
("nx" (strcat (lessen 1) "ges"))
(("tum" "dum" "rum") (strcat (lessen 2) "a"))
(("nus" "rpus" "tus" "cus" "bus"
"lus" "eus" "gus" "mus") (strcat (lessen 2) "i"))
(("mna" "ula" "dia") (strcat (lessen 1) "ae"))
("pus" (strcat (lessen 2) "odes"))
("man" (strcat (lessen 2) "en"))
(("s" "x") (strcat s "es"))
("ey" (strcat s "s"))
("y" (let ((penult (elt s (- (length s) 2)))
(antepenult (elt s (- (length s) 3))))
(if (and (or (eql #\r penult) (char= #\l penult))
(vowelp antepenult))
(strcat (lessen 1) (char-string penult) "ies")
(strcat (lessen 1) "ies"))))
(otherwise
(strcat s "s"))))))))
(defun make-english-singular (string)
(when (search "people" string :test #'char-equal)
(setf string (regex-replace-pairs '(("PEOPLE" . "PERSON")
("people" . "person")) string)))
(funcall (letter-case string)
(let ((s (string-downcase string)))
(flet ((lessen (n)
(subseq s 0 (- (length s) n))))
(or (gethash s english-defective-plurals)
(gethash s english-irregular-plurals-reverse)
(string-ends-with-case s
("pence" (strcat (lessen 4) "enny"))
("eaux" (lessen 1))
(("ese" "fish") s)
(("eeves" "eaves" "oaves") (strcat (lessen 3) "f"))
("ives" (strcat (lessen 3) "fe"))
("mata" (lessen 2))
("oices" (lessen 1))
(("eces" "ices") (strcat (lessen 3) "x"))
(("ynges" "anges") (strcat (lessen 3) "x"))
("ae" (lessen 1))
("i" (strcat (lessen 1) "us"))
("podes" (strcat (lessen 4) "us"))
("men" (strcat (lessen 2) "an"))
("im" (lessen 2))
(("ses" "xes") (lessen 2))
("ies" (strcat (lessen 3) "y"))
("s" (lessen 1))
(otherwise s)))))))
(loop for (sing pl) on ($$$
person-in-place people-in-places
country countries
monkey monkeys
penny pence
corpus corpera
octopus octopodes
deer deer
mouse mice
sword swords
address addresses
person-hour people-hours
woman women
child children
loaf loaves
knife knives
car cars
phalanx phalanges
larynx larynges
invoice invoices
) by #'cddr
do (assert (equal (make-english-singular pl) sing))
do (assert (equal (make-english-plural sing) pl)))
(defun-lang plural (count string)
(:en
(if (= 1 count)
string
(funcall
(letter-case string)
(make-english-plural string))))
(:fr (if (= 1 count)
string
FIXME
(t (funcall (letter-case string)
(strcat string "s"))))))
(:es (if (= 1 count)
string
FIXME
(t (funcall (letter-case string)
(strcat string "s"))))))
(:ga
(if (= 1 count)
string
(funcall (letter-case string)
(irish-plural-form string)))))
(defun-lang singular (plural-string)
(:en (make-english-singular plural-string)))
(defun post-irish-plurals ()
(let ((singulars ($$$ bád fear béal íasc síol bacach taoiseach gaiscíoch
deireadh saol
beach bos scornach eaglais aisling
cainteoir gnólacht tincéir am
adhmáil beannacht ban-aba canúint droim
bata ciste cailín runaí rí bus
ordú cruinniú
bearna féile
aidiacht aiste anáil bacach bádóir
báicéir baincéir bainis béal buidéal caint
cat céad ceadúnas ceann ceart cinnúint
cléreach cliabh cogadh coileach coláiste
comhairle deis dochtúir
súil deoir cuibreach))
(plurals ($$$ báid fir béil éisc síl bacaigh taoisigh gaiscigh
deirí saolta
beacha bosa scornacha eaglaisí aislingí
cainteorí gnólachtaí tincéirí amanna
admhálacha beannachtaí ban-abaí canúintí dromanna
bataí cistí cailíní runaithe rithe busanna
orduíthe cruinnithe
bearnaí féilte
aidiachta aiste anála bacaigh bádóra báiceára
baincéara bainise béil buidéil cainte cait céid
ceadúnais cinn cirt cinniúna clérigh
cléibh cogaidh coiligh coláiste
comhairle deise dochtúra
súila deora cubraigha)))
(let ((computed (loop for s in singulars
collecting (plural% :ga 2 s))))
(loop for s in singulars
for pl in plurals
for c-pl in computed
if (equal pl c-pl)
count 1 into good
else do
(warn "Failure in Irish plural: ~A ⇒ ✓ ~A (got ✗“~A”) — ~:r decl. ~A"
s pl c-pl (declension-of% :ga s)(gender-of% :ga s))
finally (return (values good #1=(/ good (length singulars))
(strcat (round #1# 1/100) "%")))))))
(post-irish-plurals)
(define-constant spanish-numbers
(mapplist (key value)
($$$ 1 uno
2 dos
3 tres
4 cuatro
5 cinco
6 seis
7 siete
8 ocho
9 nueve
10 diez
11 once
12 doce
13 trece
14 catorce
15 quince
16 dieciséis
17 diecisiete
18 dieciocho
19 diecinueve
20 veinte
21 veintiuno
22 veintidós
23 veintitrés
24 veinticuatro
25 veinticinco
26 veintiséis
27 veintisiete
28 veintiocho
29 veintinueve
30 treinta
40 cuarenta
50 cincuenta
60 sesenta
70 setenta
80 ochenta
90 noventa
200 doscientos
300 trescientos
400 cuatrocientos
500 quinientos
600 seiscientos
700 setecientos
800 ochocientos
900 novecientos
1000 mil)
(list (parse-integer key) value))
:test 'equal)
(defun-lang counting (count string)
(:en (cond
((zerop count) (a/an/some% :en 0 string))
((< count 21) (funcall (letter-case string)
(format nil "~R ~A" count
(plural% :en count string))))
(t (format nil "~:D ~A" count (plural% :en count string)))))
(:es (cond
((zerop count) (a/an/some 0 string))
((= 1 count) (funcall (letter-case string)
(strcat (ecase (gender-of% :es string)
(:m "un ")
(:f "una "))
string)))
((< count 31) (funcall (letter-case string)
(strcat (getf spanish-numbers count)
" "
(plural% :es count string))))
(t (format nil "~,,'.:D ~A" count (plural% :es count string)))))
(:la (cond
((zerop count) (a/an/some 0 string))
((= 1 count) (funcall (letter-case string)
(strcat (ecase (gender-of% :la string)
(:m "unus ")
(:f "una ")
(:n "unum "))
string)))
((< count 11) (funcall (letter-case string)
(strcat (getf '(1 nil
2 "duō"
3 "trēs"
4 "quatuor"
5 "quinque"
6 "sex"
7 "septem"
8 "octem"
9 "novem"
10 "decem"
) count)
" "
(plural% :la count string))))
((< count 5000) (presentation-roman-numeral (format nil "~:@r ~A" count (plural% :es count string))))
(t (format nil "~,,'.:D ~A" count (plural% :es count string))))))
(assert (equal (counting% :es 2 "gato") "dos gatos"))
(assert (equal (counting% :es 1492 "gato") "1.492 gatos"))
(assert (equal (counting% :es 1 "gato") "un gato"))
(assert (equal (counting% :es 1 "casa") "una casa"))
(defun-lang a/an (string)
(:la string)
(:en (let ((letter (elt string 0)))
(case letter
((#\a #\e #\i #\o #\u #\h)
(concatenate 'string "an " string))
((#\A #\E #\I #\O #\U #\H)
(concatenate 'string (funcall (letter-case string) "an ") string))
(otherwise
(concatenate 'string (funcall (letter-case string) "a ") string)))))
(:es (strcat (funcall (letter-case string)
(ecase (gender-of% :es string)
((:m nil) "un ")
(:f "una "))) string))
(:fr (strcat (funcall (letter-case string)
(ecase (gender-of% :fr string)
((:m nil) "un ")
(:f "une "))) string))
(:ga string))
(defun-lang pluralp (string)
(:en (char-equal (last-elt string) #\s))
(:es (char-equal (last-elt string) #\s))
(:fr (char-equal (last-elt string) #\s)))
(defun-lang -the- (string)
(:la string)
(:ru string)
(:en (concatenate 'string (funcall (letter-case string) "the ") string))
(:es (strcat (funcall (letter-case string)
(ecase (pluralp% :es string)
(t (ecase (gender-of% :es string)
((:m nil) "los ")
(:f "las ")))
((nil) (ecase (gender-of% :es string)
((:m nil) "el ")
(:f "la "))))) string))
(:fr (strcat (funcall (letter-case string)
(ecase (pluralp% :es string)
(t "les ")
((nil) (ecase (gender-of% :es string)
((:m nil) (if (vowelp (first-elt string))
"l'"
"le "))
(:f "la "))))) string))
(:ga (concatenate 'string (funcall (letter-case string) "an ")
string)))
(defun-lang a/an/some (count string)
(:en (case count
(0 (concatenate 'string (funcall (letter-case string) "no ")
(plural% :en 0 string)))
(1 (a/an string))
(otherwise (concatenate 'string (funcall (letter-case string) "some ")
(plural% :en count string)))))
(:fr (case count
(0 (concatenate 'string (funcall (letter-case string) "sans ")
(plural% :fr 0 string)))
(1 (a/an string))
(otherwise (concatenate 'string (funcall (letter-case string) "des ")
(plural% :fr count string)))))
(:ga (plural% :ga count string)))
Credit for Irish language test cases to Irish language documents by
Amy de Buitléir , CC - BY 3.0 license , found at
/
(defun range-size (numeric-range-string)
"Count the length of a range of numbers separated by -"
(if (find #\- numeric-range-string)
(destructuring-bind (start end)
(uiop:split-string numeric-range-string
:separator "-")
(1+ (- (parse-integer end) (parse-integer start))))
1))
(defun human-duration (seconds)
(cond
((< seconds 1/1000000000000000)
"instantly")
((< seconds 1/1000000000000)
(format nil "~d femtosecond~:p" (round (* seconds 1000000000000000))))
((< seconds 1/1000000000)
(format nil "~d picosecond~:p" (round (* seconds 1000000000000))))
((< seconds 1/1000000)
(format nil "~d nanosecond~:p" (round (* seconds 1000000000))))
((< seconds 1/1000)
(format nil "~d microsecond~:p" (round (* seconds 1000000))))
((< seconds 1)
(format nil "~d millisecond~:p" (round (* seconds 1000))))
((< seconds 90)
(format nil "~d second~:p" (round seconds)))
((< seconds (* 90 60))
(format nil "~d minutes" (round seconds 60)))
((< seconds (* 3 24 60 60))
(format nil "~d hours" (round seconds (* 60 60))))
((< seconds (* 6 7 24 60 60))
(format nil "~d days" (round seconds (* 24 60 60))))
((< seconds (* 75 7 24 60 60))
(format nil "~d weeks" (round seconds (* 7 24 60 60))))
(t (format nil "~:d years" (round seconds (* 365.2489 24 60 60))))))
(defun weekday-name (day-of-week)
(elt '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday") day-of-week))
(defun month-name (month)
(elt '("January" "February" "March"
"April" "May" "June"
"July" "August" "September"
"October" "November" "December")
month))
(defun human-future-time (universal-time)
(multiple-value-bind (sec min hour day month year day-of-week)
(decode-universal-time universal-time)
(multiple-value-bind (sec-now min-now hour-now
day-now month-now year-now
day-of-week-now)
(decode-universal-time (get-universal-time))
(cond
((and (= hour-now hour)
(= day-now day)
(= month-now month)
(= year-now year))
(format nil "in ~a at ~2,'0d:~2,'0d"
(human-duration (- universal-time (get-universal-time)))
hour min))
((and (= year-now year)
(= month-now month))
(format nil "on ~a the ~:r at ~2,'0d:~2,'0d"
(weekday-name day-of-week) day hour min))
(t (format nil "on ~a, ~:d ~a, ~d at ~2,'0d:~2,'0d"
(weekday-name day-of-week) day (month-name month) year
hour min))))))
|
d997544485733f2f67cb34b07ca0da291deca083bb1999ce680b0f7627d8a0fa | lojic/LearningRacket | sieve-test.rkt | #lang racket
(require "sieve.rkt")
(module+ test
(require rackunit rackunit/text-ui)
(define suite
(test-suite
"Tests for the sieve exercise"
(for ([(limit primes) #hash((2 . (2))
(3 . (3 2))
(4 . (3 2))
(5 . (5 3 2))
(6 . (5 3 2))
(7 . (7 5 3 2))
(8 . (7 5 3 2))
(9 . (7 5 3 2))
(10 . (7 5 3 2))
(11 . (11 7 5 3 2))
(22 . (19 17 13 11 7 5 3 2))
)])
(check-equal? (primes-to limit) primes))
))
(run-tests suite))
| null | https://raw.githubusercontent.com/lojic/LearningRacket/eb0e75b0e16d3e0a91b8fa6612e2678a9e12e8c7/exercism.io/sieve/sieve-test.rkt | racket | #lang racket
(require "sieve.rkt")
(module+ test
(require rackunit rackunit/text-ui)
(define suite
(test-suite
"Tests for the sieve exercise"
(for ([(limit primes) #hash((2 . (2))
(3 . (3 2))
(4 . (3 2))
(5 . (5 3 2))
(6 . (5 3 2))
(7 . (7 5 3 2))
(8 . (7 5 3 2))
(9 . (7 5 3 2))
(10 . (7 5 3 2))
(11 . (11 7 5 3 2))
(22 . (19 17 13 11 7 5 3 2))
)])
(check-equal? (primes-to limit) primes))
))
(run-tests suite))
|
|
4b7fafdd4abf8d446caccba9f7ce5ecac46ce36e531df7358e554efe88cf1def | freckle/blammo | Terminal.hs | -- | Colorful logging for humans
--
-- Lines are formatted as
--
-- @
-- {timestamp} [{level}] {message} {details}
-- @
--
@level@ is padded to 9 characters and @message@ is padded to 31 . This means
-- things will align as long as values are shorter than that. Longer values will
-- overflow (not be truncated).
--
This format was designed to match Python 's
-- [structlog](/) package in its default
-- configuration.
--
module Blammo.Logging.Terminal
( reformatTerminal
) where
import Prelude
import Blammo.Logging.Colors
import Blammo.Logging.Terminal.LogPiece (LogPiece, logPiece)
import qualified Blammo.Logging.Terminal.LogPiece as LogPiece
import Control.Monad.Logger.Aeson
import Data.Aeson
import Data.Aeson.Compat (KeyMap)
import qualified Data.Aeson.Compat as Key
import qualified Data.Aeson.Compat as KeyMap
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BSL
import Data.List (sortOn)
import Data.Maybe (fromMaybe)
import Data.Text (Text, pack)
import qualified Data.Text as T
import Data.Time (defaultTimeLocale, formatTime)
import qualified Data.Vector as V
reformatTerminal :: Int -> Bool -> LogLevel -> ByteString -> ByteString
reformatTerminal breakpoint useColor logLevel bytes = fromMaybe bytes $ do
LoggedMessage {..} <- decode $ BSL.fromStrict bytes
let
colors@Colors {..} = getColors useColor
logTimestampPiece = logPiece dim $ pack $ formatTime
defaultTimeLocale
"%F %X"
loggedMessageTimestamp
logLevelPiece = case logLevel of
LevelDebug -> logPiece gray $ padTo 9 "debug"
LevelInfo -> logPiece green $ padTo 9 "info"
LevelWarn -> logPiece yellow $ padTo 9 "warn"
LevelError -> logPiece red $ padTo 9 "error"
LevelOther x -> logPiece blue $ padTo 9 x
loggedSourceAsMap =
foldMap (KeyMap.singleton "source" . String) loggedMessageLogSource
logPrefixPiece =
logTimestampPiece <> " [" <> logLevelPiece <> "] "
logMessagePiece = logPiece bold $ padTo 31 loggedMessageText
logAttrsPiece = mconcat
[ colorizeKeyMap " " colors loggedSourceAsMap
, colorizeKeyMap " " colors loggedMessageThreadContext
, colorizeKeyMap " " colors loggedMessageMeta
]
oneLineLogPiece = mconcat [logPrefixPiece, logMessagePiece, logAttrsPiece]
multiLineLogPiece =
let
shift = "\n" <> LogPiece.offset (LogPiece.visibleLength logPrefixPiece)
in
mconcat
[ logPrefixPiece
, logMessagePiece
, colorizeKeyMap shift colors loggedSourceAsMap
, colorizeKeyMap shift colors loggedMessageThreadContext
, colorizeKeyMap shift colors loggedMessageMeta
]
pure
$ LogPiece.bytestring
$ if LogPiece.visibleLength oneLineLogPiece <= breakpoint
then oneLineLogPiece
else multiLineLogPiece
colorizeKeyMap :: LogPiece -> Colors -> KeyMap Value -> LogPiece
colorizeKeyMap sep Colors {..} km
| KeyMap.null km = mempty
| otherwise = foldMap (uncurry fromPair) $ sortOn fst $ KeyMap.toList km
where
fromPair k v =
sep <> logPiece cyan (Key.toText k) <> "=" <> logPiece magenta (fromValue v)
fromValue = \case
Object m -> obj $ map (uncurry renderPairNested) $ KeyMap.toList m
Array a -> list $ map fromValue $ V.toList a
String x -> x
Number n -> sci n
Bool b -> pack $ show b
Null -> "null"
renderPairNested k v = Key.toText k <> ": " <> fromValue v
obj xs = "{" <> T.intercalate ", " xs <> "}"
list xs = "[" <> T.intercalate ", " xs <> "]"
sci = dropSuffix ".0" . pack . show
dropSuffix :: Text -> Text -> Text
dropSuffix suffix t = fromMaybe t $ T.stripSuffix suffix t
padTo :: Int -> Text -> Text
padTo n t = t <> T.replicate pad " " where pad = max 0 $ n - T.length t
| null | https://raw.githubusercontent.com/freckle/blammo/a5b70d0c6d8d3022e78de60984d6f846b06b5086/src/Blammo/Logging/Terminal.hs | haskell | | Colorful logging for humans
Lines are formatted as
@
{timestamp} [{level}] {message} {details}
@
things will align as long as values are shorter than that. Longer values will
overflow (not be truncated).
[structlog](/) package in its default
configuration.
| @level@ is padded to 9 characters and @message@ is padded to 31 . This means
This format was designed to match Python 's
module Blammo.Logging.Terminal
( reformatTerminal
) where
import Prelude
import Blammo.Logging.Colors
import Blammo.Logging.Terminal.LogPiece (LogPiece, logPiece)
import qualified Blammo.Logging.Terminal.LogPiece as LogPiece
import Control.Monad.Logger.Aeson
import Data.Aeson
import Data.Aeson.Compat (KeyMap)
import qualified Data.Aeson.Compat as Key
import qualified Data.Aeson.Compat as KeyMap
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BSL
import Data.List (sortOn)
import Data.Maybe (fromMaybe)
import Data.Text (Text, pack)
import qualified Data.Text as T
import Data.Time (defaultTimeLocale, formatTime)
import qualified Data.Vector as V
reformatTerminal :: Int -> Bool -> LogLevel -> ByteString -> ByteString
reformatTerminal breakpoint useColor logLevel bytes = fromMaybe bytes $ do
LoggedMessage {..} <- decode $ BSL.fromStrict bytes
let
colors@Colors {..} = getColors useColor
logTimestampPiece = logPiece dim $ pack $ formatTime
defaultTimeLocale
"%F %X"
loggedMessageTimestamp
logLevelPiece = case logLevel of
LevelDebug -> logPiece gray $ padTo 9 "debug"
LevelInfo -> logPiece green $ padTo 9 "info"
LevelWarn -> logPiece yellow $ padTo 9 "warn"
LevelError -> logPiece red $ padTo 9 "error"
LevelOther x -> logPiece blue $ padTo 9 x
loggedSourceAsMap =
foldMap (KeyMap.singleton "source" . String) loggedMessageLogSource
logPrefixPiece =
logTimestampPiece <> " [" <> logLevelPiece <> "] "
logMessagePiece = logPiece bold $ padTo 31 loggedMessageText
logAttrsPiece = mconcat
[ colorizeKeyMap " " colors loggedSourceAsMap
, colorizeKeyMap " " colors loggedMessageThreadContext
, colorizeKeyMap " " colors loggedMessageMeta
]
oneLineLogPiece = mconcat [logPrefixPiece, logMessagePiece, logAttrsPiece]
multiLineLogPiece =
let
shift = "\n" <> LogPiece.offset (LogPiece.visibleLength logPrefixPiece)
in
mconcat
[ logPrefixPiece
, logMessagePiece
, colorizeKeyMap shift colors loggedSourceAsMap
, colorizeKeyMap shift colors loggedMessageThreadContext
, colorizeKeyMap shift colors loggedMessageMeta
]
pure
$ LogPiece.bytestring
$ if LogPiece.visibleLength oneLineLogPiece <= breakpoint
then oneLineLogPiece
else multiLineLogPiece
colorizeKeyMap :: LogPiece -> Colors -> KeyMap Value -> LogPiece
colorizeKeyMap sep Colors {..} km
| KeyMap.null km = mempty
| otherwise = foldMap (uncurry fromPair) $ sortOn fst $ KeyMap.toList km
where
fromPair k v =
sep <> logPiece cyan (Key.toText k) <> "=" <> logPiece magenta (fromValue v)
fromValue = \case
Object m -> obj $ map (uncurry renderPairNested) $ KeyMap.toList m
Array a -> list $ map fromValue $ V.toList a
String x -> x
Number n -> sci n
Bool b -> pack $ show b
Null -> "null"
renderPairNested k v = Key.toText k <> ": " <> fromValue v
obj xs = "{" <> T.intercalate ", " xs <> "}"
list xs = "[" <> T.intercalate ", " xs <> "]"
sci = dropSuffix ".0" . pack . show
dropSuffix :: Text -> Text -> Text
dropSuffix suffix t = fromMaybe t $ T.stripSuffix suffix t
padTo :: Int -> Text -> Text
padTo n t = t <> T.replicate pad " " where pad = max 0 $ n - T.length t
|
f0ef880b0b07dbd6444d7504a67c51fad9dd642dc88b7b40b100e3a21b48fb65 | rtoy/ansi-cl-tests | pathnames.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sat Nov 29 04:21:53 2003
;;;; Contains: Various tests on pathnames
(in-package :cl-test)
(deftest pathnames-print-and-read-properly
(with-standard-io-syntax
(loop
for p1 in *pathnames*
for s = (handler-case (write-to-string p1 :readably t)
(print-not-readable () :unreadable-error))
unless (eql s :unreadable-error)
append
(let ((p2 (read-from-string s)))
(unless (equal p1 p2)
(list (list p1 s p2))))))
nil)
| null | https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/pathnames.lsp | lisp | -*- Mode: Lisp -*-
Contains: Various tests on pathnames | Author :
Created : Sat Nov 29 04:21:53 2003
(in-package :cl-test)
(deftest pathnames-print-and-read-properly
(with-standard-io-syntax
(loop
for p1 in *pathnames*
for s = (handler-case (write-to-string p1 :readably t)
(print-not-readable () :unreadable-error))
unless (eql s :unreadable-error)
append
(let ((p2 (read-from-string s)))
(unless (equal p1 p2)
(list (list p1 s p2))))))
nil)
|
d1bd21dc6ddfadc6c85f0d1c3ab6edf9eda436d4e6250adeb00c6be18c04da60 | CarlosMChica/HaskellBook | MakeItBottom.hs | module MakeItBottom where
-- Make it bottom up with bang patterns or seq
x = undefined
y = "blah"
main = do
print (snd (x, y))
main' = do
print (snd (x, x `seq` y))
| null | https://raw.githubusercontent.com/CarlosMChica/HaskellBook/86f82cf36cd00003b1a1aebf264e4b5d606ddfad/chapter27/MakeItBottom.hs | haskell | Make it bottom up with bang patterns or seq | module MakeItBottom where
x = undefined
y = "blah"
main = do
print (snd (x, y))
main' = do
print (snd (x, x `seq` y))
|
03cb11358ad9738f6728a8371cbcc4e8dff446a424ce040c07a059f96f74393d | tweag/asterius | T10104.hs | # LANGUAGE MagicHash #
module Main where
import GHC.Prim
data P = Positives Int# Float# Double# Char# Word# deriving Show
data N = Negatives Int# Float# Double# deriving Show
main = do
print $ Positives 42# 4.23# 4.23## '4'# 4##
print $ Negatives -4# -4.0# -4.0##
| null | https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/deriving/T10104.hs | haskell | # LANGUAGE MagicHash #
module Main where
import GHC.Prim
data P = Positives Int# Float# Double# Char# Word# deriving Show
data N = Negatives Int# Float# Double# deriving Show
main = do
print $ Positives 42# 4.23# 4.23## '4'# 4##
print $ Negatives -4# -4.0# -4.0##
|
|
f0fd42dd5652d2384195a3d6719de64f7ee646596786241e82da2cac023974ed | fpco/inline-c | ParseSpec.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
{-# LANGUAGE OverloadedStrings #-}
module Language.C.Inline.ParseSpec (spec) where
import Control.Exception (evaluate)
import Control.Monad (void)
import Control.Monad.Trans.Class (lift)
import qualified Data.HashSet as HashSet
import Data.Monoid ((<>))
import qualified Test.Hspec as Hspec
import Text.Parser.Char
import Text.Parser.Combinators
import Text.RawString.QQ (r)
import Text.Regex.Posix ((=~))
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<*), (*>))
#endif
import Language.C.Inline.Context
import Language.C.Inline.HaskellIdentifier
import Language.C.Inline.Internal
import qualified Language.C.Types as C
spec :: Hspec.SpecWith ()
spec = do
Hspec.describe "parsing" $ do
Hspec.it "parses simple C expression" $ do
(retType, params, cExp) <- goodParse [r|
int { (int) ceil($(double x) + ((double) $(float y))) }
|]
retType `Hspec.shouldBe` (cty "int")
params `shouldMatchParameters` [(cty "double", Plain "x"), (cty "float", Plain "y")]
cExp `shouldMatchBody` " (int) ceil(x[a-z0-9_]+ \\+ ((double) y[a-z0-9_]+)) "
Hspec.it "accepts anti quotes" $ do
void $ goodParse [r| int { $(int x) } |]
Hspec.it "accepts anti quotes with pointer" $ do
void $ goodParse [r| int* { $(int* x) } |]
Hspec.it "rejects if bad braces (1)" $ do
badParse [r| int x |]
Hspec.it "rejects if bad braces (2)" $ do
badParse [r| int { x |]
Hspec.it "parses function pointers" $ do
void $ goodParse [r| int(int (*add)(int, int)) { add(3, 4) } |]
Hspec.it "parses returning function pointers" $ do
(retType, params, cExp) <-
goodParse [r| double (*)(double) { &cos } |]
retType `Hspec.shouldBe` (cty "double (*)(double)")
params `shouldMatchParameters` []
cExp `shouldMatchBody` " &cos "
Hspec.it "parses Haskell identifier (1)" $ do
(retType, params, cExp) <- goodParse [r| double { $(double x') } |]
retType `Hspec.shouldBe` (cty "double")
params `shouldMatchParameters` [(cty "double", Plain "x'")]
cExp `shouldMatchBody` " x[a-z0-9_]+ "
Hspec.it "parses Haskell identifier (2)" $ do
(retType, params, cExp) <- goodParse [r| double { $(double ä') } |]
retType `Hspec.shouldBe` (cty "double")
params `shouldMatchParameters` [(cty "double", Plain "ä'")]
cExp `shouldMatchBody` " [a-z0-9_]+ "
Hspec.it "parses Haskell identifier (3)" $ do
(retType, params, cExp) <- goodParse [r| int { $(int Foo.bar) } |]
retType `Hspec.shouldBe` (cty "int")
params `shouldMatchParameters` [(cty "int", Plain "Foo.bar")]
cExp `shouldMatchBody` " Foobar[a-z0-9_]+ "
Hspec.it "does not parse Haskell identifier in bad position" $ do
badParse [r| double (*)(double Foo.bar) { 3.0 } |]
where
ctx = baseCtx <> funCtx
assertParse ctxF p s =
case C.runCParser (ctxF HashSet.empty) "spec" s (lift spaces *> p <* lift eof) of
Left err -> error $ "Parse error (assertParse): " ++ show err
Right x -> x
-- We use show + length to fully evaluate the result -- there
might be exceptions hiding . TODO get rid of exceptions .
strictParse
:: String
-> IO (C.Type C.CIdentifier, [(C.CIdentifier, C.Type C.CIdentifier, ParameterType)], String)
strictParse s = do
let ParseTypedC retType pars body =
assertParse (haskellCParserContext True) (parseTypedC True (ctxAntiQuoters ctx)) s
void $ evaluate $ length $ show (retType, pars, body)
return (retType, pars, body)
goodParse = strictParse
badParse s = strictParse s `Hspec.shouldThrow` Hspec.anyException
cty :: String -> C.Type C.CIdentifier
cty s = C.parameterDeclarationType $
assertParse (C.cCParserContext True) C.parseParameterDeclaration s
shouldMatchParameters
:: [(C.CIdentifier, C.Type C.CIdentifier, ParameterType)]
-> [(C.Type C.CIdentifier, ParameterType)]
-> Hspec.Expectation
shouldMatchParameters pars pars' =
[(x, y) | (_, x, y) <- pars] `Hspec.shouldMatchList` pars'
shouldMatchBody :: String -> String -> Hspec.Expectation
shouldMatchBody x y = do
let f ch' = case ch' of
'(' -> "\\("
')' -> "\\)"
ch -> [ch]
(x =~ concatMap f y) `Hspec.shouldBe` True
| null | https://raw.githubusercontent.com/fpco/inline-c/b37b60f1712b12b43c86493cafb9ac324443d22e/inline-c/test/Language/C/Inline/ParseSpec.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE RankNTypes #
# LANGUAGE OverloadedStrings #
We use show + length to fully evaluate the result -- there | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
module Language.C.Inline.ParseSpec (spec) where
import Control.Exception (evaluate)
import Control.Monad (void)
import Control.Monad.Trans.Class (lift)
import qualified Data.HashSet as HashSet
import Data.Monoid ((<>))
import qualified Test.Hspec as Hspec
import Text.Parser.Char
import Text.Parser.Combinators
import Text.RawString.QQ (r)
import Text.Regex.Posix ((=~))
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<*), (*>))
#endif
import Language.C.Inline.Context
import Language.C.Inline.HaskellIdentifier
import Language.C.Inline.Internal
import qualified Language.C.Types as C
spec :: Hspec.SpecWith ()
spec = do
Hspec.describe "parsing" $ do
Hspec.it "parses simple C expression" $ do
(retType, params, cExp) <- goodParse [r|
int { (int) ceil($(double x) + ((double) $(float y))) }
|]
retType `Hspec.shouldBe` (cty "int")
params `shouldMatchParameters` [(cty "double", Plain "x"), (cty "float", Plain "y")]
cExp `shouldMatchBody` " (int) ceil(x[a-z0-9_]+ \\+ ((double) y[a-z0-9_]+)) "
Hspec.it "accepts anti quotes" $ do
void $ goodParse [r| int { $(int x) } |]
Hspec.it "accepts anti quotes with pointer" $ do
void $ goodParse [r| int* { $(int* x) } |]
Hspec.it "rejects if bad braces (1)" $ do
badParse [r| int x |]
Hspec.it "rejects if bad braces (2)" $ do
badParse [r| int { x |]
Hspec.it "parses function pointers" $ do
void $ goodParse [r| int(int (*add)(int, int)) { add(3, 4) } |]
Hspec.it "parses returning function pointers" $ do
(retType, params, cExp) <-
goodParse [r| double (*)(double) { &cos } |]
retType `Hspec.shouldBe` (cty "double (*)(double)")
params `shouldMatchParameters` []
cExp `shouldMatchBody` " &cos "
Hspec.it "parses Haskell identifier (1)" $ do
(retType, params, cExp) <- goodParse [r| double { $(double x') } |]
retType `Hspec.shouldBe` (cty "double")
params `shouldMatchParameters` [(cty "double", Plain "x'")]
cExp `shouldMatchBody` " x[a-z0-9_]+ "
Hspec.it "parses Haskell identifier (2)" $ do
(retType, params, cExp) <- goodParse [r| double { $(double ä') } |]
retType `Hspec.shouldBe` (cty "double")
params `shouldMatchParameters` [(cty "double", Plain "ä'")]
cExp `shouldMatchBody` " [a-z0-9_]+ "
Hspec.it "parses Haskell identifier (3)" $ do
(retType, params, cExp) <- goodParse [r| int { $(int Foo.bar) } |]
retType `Hspec.shouldBe` (cty "int")
params `shouldMatchParameters` [(cty "int", Plain "Foo.bar")]
cExp `shouldMatchBody` " Foobar[a-z0-9_]+ "
Hspec.it "does not parse Haskell identifier in bad position" $ do
badParse [r| double (*)(double Foo.bar) { 3.0 } |]
where
ctx = baseCtx <> funCtx
assertParse ctxF p s =
case C.runCParser (ctxF HashSet.empty) "spec" s (lift spaces *> p <* lift eof) of
Left err -> error $ "Parse error (assertParse): " ++ show err
Right x -> x
might be exceptions hiding . TODO get rid of exceptions .
strictParse
:: String
-> IO (C.Type C.CIdentifier, [(C.CIdentifier, C.Type C.CIdentifier, ParameterType)], String)
strictParse s = do
let ParseTypedC retType pars body =
assertParse (haskellCParserContext True) (parseTypedC True (ctxAntiQuoters ctx)) s
void $ evaluate $ length $ show (retType, pars, body)
return (retType, pars, body)
goodParse = strictParse
badParse s = strictParse s `Hspec.shouldThrow` Hspec.anyException
cty :: String -> C.Type C.CIdentifier
cty s = C.parameterDeclarationType $
assertParse (C.cCParserContext True) C.parseParameterDeclaration s
shouldMatchParameters
:: [(C.CIdentifier, C.Type C.CIdentifier, ParameterType)]
-> [(C.Type C.CIdentifier, ParameterType)]
-> Hspec.Expectation
shouldMatchParameters pars pars' =
[(x, y) | (_, x, y) <- pars] `Hspec.shouldMatchList` pars'
shouldMatchBody :: String -> String -> Hspec.Expectation
shouldMatchBody x y = do
let f ch' = case ch' of
'(' -> "\\("
')' -> "\\)"
ch -> [ch]
(x =~ concatMap f y) `Hspec.shouldBe` True
|
a1883e5412b6bc49eed2d374b910935480ac055ef282969c447c2273c62ba1ce | theodormoroianu/SecondYearCourses | LambdaChurch_20210415171302.hs | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
-- alpha-equivalence
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
-- subst u x t defines [u/x]t, i.e., substituting u for x in t
for example [ 3 / x](x + x ) = = 3 + 3
-- This substitution avoids variable captures so it is safe to be used when
-- reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
subst
:: Term -- ^ substitution term
-> Variable -- ^ variable to be substitutes
-> Term -- ^ term in which the substitution occurs
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
-- Normal order reduction
-- - like call by name
-- - but also reduce under lambda abstractions if no application is possible
-- - guarantees reaching a normal form if it exists
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
-- alpha-beta equivalence (for strongly normalizing terms) is obtained by
-- fully evaluating the terms using beta-reduction, then checking their
-- alpha-equivalence.
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
-- Church Encodings in Lambda
------------
--BOOLEANS--
------------
A boolean is any way to choose between two alternatives ( t - > t - > t )
The boolean constant true always chooses the first alternative
cTrue :: Term
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: Term
cFalse = undefined
--If is not really needed because we can use the booleans themselves, but...
cIf :: Term
cIf = undefined
--The boolean negation switches the alternatives
cNot :: Term
cNot = undefined
--The boolean conjunction can be built as a conditional
cAnd :: Term
cAnd = undefined
--The boolean disjunction can be built as a conditional
cOr :: Term
cOr = undefined
---------
PAIRS--
---------
-- a pair with components of type a and b is a way to compute something based
-- on the values contained within the pair (a -> b -> c) -> c
builds a pair out of two values as an object which , when given
--a function to be applied on the values, it will apply it on them.
cPair :: Term
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: Term
cFst = undefined
second projection
cSnd :: Term
cSnd = undefined
-------------------
--NATURAL NUMBERS--
-------------------
-- A natural number is any way to iterate a function s a number of times
-- over an initial value z ( (t -> t) -> t -> t )
--0 will iterate the function s 0 times over z, producing z
c0 :: Term
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: Term
c1 = undefined
--Successor n either
- applies s one more time in addition to what n does
-- - iterates s n times over (s z)
cS :: Term
cS = undefined
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) -> Term
cNat = undefined
--Addition of m and n can be done by composing n s with m s
cPlus :: Term
cPlus = undefined
--Multiplication of m and n can be done by composing n and m
cMul :: Term
cMul = undefined
--Exponentiation of m and n can be done by applying n to m
cPow :: Term
cPow = undefined
--Testing whether a value is 0 can be done through iteration
-- using a function constantly false and an initial value true
cIs0 :: Term
cIs0 = undefined
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: Term
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
-- of the predeccesor function
cSub :: Term
cSub = undefined
-- m is less than (or equal to) n if when substracting n from m we get 0
cLte :: Term
cLte = undefined
cGte :: Term
cGte = undefined
cLt :: Term
cLt = undefined
cGt :: Term
cGt = undefined
-- equality on naturals can be defined my means of comparisons
cEq :: Term
cEq = undefined
--Fun with arithmetic and pairs
--Define factorial. You can iterate over a pair to contain the current index and so far factorial
cFactorial :: Term
cFactorial = undefined
Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence
cFibonacci :: Term
cFibonacci = undefined
--Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n.
--hint iterate over a pair, initially (0, m),
incrementing the first and substracting n from the second if it is smaller than n
--for at most m times
cDivMod :: Term
cDivMod = undefined
---------
LISTS--
---------
-- a list with elements of type a is a way to aggregate a sequence of elements of type a
-- given an aggregation function and an initial value ( (a -> b -> b) -> b -> b )
-- The empty list is that which when aggregated it will always produce the initial value
cNil :: Term
cNil = undefined
-- Adding an element to a list means that, when aggregating the list, the newly added
-- element will be aggregated with the result obtained by aggregating the remainder of the list
cCons :: Term
cCons = undefined
we can obtain a CList from a regular list of terms by folding the list
cList :: [Term] -> Term
cList = undefined
-- builds a encoded list of encodings of natural numbers corresponding to a list of Integers
cNatList :: [Integer] -> Term
cNatList = undefined
-- sums the elements in the list
cSum :: Term
cSum = undefined
-- checks whether a list is nil (similar to cIs0)
cIsNil :: Term
cIsNil = undefined
-- gets the head of the list (or the default specified value if the list is empty)
cHead :: Term
cHead = undefined
-- gets the tail of the list (empty if the list is empty) --- similar to cPred
cTail :: Term
cTail = undefined
--The Y combinator
fix :: Term
fix = undefined
a recursive definition for divMod , Similar as above , but stops as soon as
-- q becomes less than n (using fix)
cDivMod' :: Term
cDivMod' = undefined
-- a re
cSudan :: Term
cSudan =
cAckermann :: Term
cAckermann = fix $$ lam "A" (lams ["m", "n"]
(cIs0 $$ v "m"
$$ (cS $$ v "n")
$$ (cIs0 $$ v "n"
$$ (v "A" $$ (cPred $$ v "m") $$ c1)
$$ (v "A" $$ (cPred $$ v "m")
$$ (v "A" $$ v "m" $$ (cPred $$ v "n")))
)
))
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415171302.hs | haskell | alpha-equivalence
subst u x t defines [u/x]t, i.e., substituting u for x in t
This substitution avoids variable captures so it is safe to be used when
reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
^ substitution term
^ variable to be substitutes
^ term in which the substitution occurs
Normal order reduction
- like call by name
- but also reduce under lambda abstractions if no application is possible
- guarantees reaching a normal form if it exists
alpha-beta equivalence (for strongly normalizing terms) is obtained by
fully evaluating the terms using beta-reduction, then checking their
alpha-equivalence.
Church Encodings in Lambda
----------
BOOLEANS--
----------
If is not really needed because we can use the booleans themselves, but...
The boolean negation switches the alternatives
The boolean conjunction can be built as a conditional
The boolean disjunction can be built as a conditional
-------
-------
a pair with components of type a and b is a way to compute something based
on the values contained within the pair (a -> b -> c) -> c
a function to be applied on the values, it will apply it on them.
-----------------
NATURAL NUMBERS--
-----------------
A natural number is any way to iterate a function s a number of times
over an initial value z ( (t -> t) -> t -> t )
0 will iterate the function s 0 times over z, producing z
Successor n either
- iterates s n times over (s z)
Addition of m and n can be done by composing n s with m s
Multiplication of m and n can be done by composing n and m
Exponentiation of m and n can be done by applying n to m
Testing whether a value is 0 can be done through iteration
using a function constantly false and an initial value true
of the predeccesor function
m is less than (or equal to) n if when substracting n from m we get 0
equality on naturals can be defined my means of comparisons
Fun with arithmetic and pairs
Define factorial. You can iterate over a pair to contain the current index and so far factorial
Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n.
hint iterate over a pair, initially (0, m),
for at most m times
-------
-------
a list with elements of type a is a way to aggregate a sequence of elements of type a
given an aggregation function and an initial value ( (a -> b -> b) -> b -> b )
The empty list is that which when aggregated it will always produce the initial value
Adding an element to a list means that, when aggregating the list, the newly added
element will be aggregated with the result obtained by aggregating the remainder of the list
builds a encoded list of encodings of natural numbers corresponding to a list of Integers
sums the elements in the list
checks whether a list is nil (similar to cIs0)
gets the head of the list (or the default specified value if the list is empty)
gets the tail of the list (empty if the list is empty) --- similar to cPred
The Y combinator
q becomes less than n (using fix)
a re | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
for example [ 3 / x](x + x ) = = 3 + 3
subst
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
A boolean is any way to choose between two alternatives ( t - > t - > t )
The boolean constant true always chooses the first alternative
cTrue :: Term
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: Term
cFalse = undefined
cIf :: Term
cIf = undefined
cNot :: Term
cNot = undefined
cAnd :: Term
cAnd = undefined
cOr :: Term
cOr = undefined
builds a pair out of two values as an object which , when given
cPair :: Term
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: Term
cFst = undefined
second projection
cSnd :: Term
cSnd = undefined
c0 :: Term
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: Term
c1 = undefined
- applies s one more time in addition to what n does
cS :: Term
cS = undefined
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) -> Term
cNat = undefined
cPlus :: Term
cPlus = undefined
cMul :: Term
cMul = undefined
cPow :: Term
cPow = undefined
cIs0 :: Term
cIs0 = undefined
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: Term
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
cSub :: Term
cSub = undefined
cLte :: Term
cLte = undefined
cGte :: Term
cGte = undefined
cLt :: Term
cLt = undefined
cGt :: Term
cGt = undefined
cEq :: Term
cEq = undefined
cFactorial :: Term
cFactorial = undefined
Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence
cFibonacci :: Term
cFibonacci = undefined
incrementing the first and substracting n from the second if it is smaller than n
cDivMod :: Term
cDivMod = undefined
cNil :: Term
cNil = undefined
cCons :: Term
cCons = undefined
we can obtain a CList from a regular list of terms by folding the list
cList :: [Term] -> Term
cList = undefined
cNatList :: [Integer] -> Term
cNatList = undefined
cSum :: Term
cSum = undefined
cIsNil :: Term
cIsNil = undefined
cHead :: Term
cHead = undefined
cTail :: Term
cTail = undefined
fix :: Term
fix = undefined
a recursive definition for divMod , Similar as above , but stops as soon as
cDivMod' :: Term
cDivMod' = undefined
cSudan :: Term
cSudan =
cAckermann :: Term
cAckermann = fix $$ lam "A" (lams ["m", "n"]
(cIs0 $$ v "m"
$$ (cS $$ v "n")
$$ (cIs0 $$ v "n"
$$ (v "A" $$ (cPred $$ v "m") $$ c1)
$$ (v "A" $$ (cPred $$ v "m")
$$ (v "A" $$ v "m" $$ (cPred $$ v "n")))
)
))
|
cef14b53945937c3a2e44e0b12ec81d137cca842dfa110475a0f58449e87ad6c | disco-lang/disco | Util.hs |
-----------------------------------------------------------------------------
-- |
Module : Disco . . Util
Copyright : ( c ) 2016 disco team ( see LICENSE )
-- License : BSD-style (see LICENSE)
-- Maintainer :
--
-- Definition of type contexts, type errors, and various utilities
-- used during type checking.
--
-----------------------------------------------------------------------------
module Disco.Typecheck.Util where
import Disco.Effects.Fresh
import Polysemy
import Polysemy.Error
import Polysemy.Output
import Polysemy.Reader
import Polysemy.Writer
import Unbound.Generics.LocallyNameless (Name, bind, string2Name)
import qualified Data.Map as M
import Data.Tuple (swap)
import Prelude hiding (lookup)
import Disco.AST.Surface
import Disco.Context
import Disco.Messages
import Disco.Names (ModuleName, QName)
import Disco.Typecheck.Constraints
import Disco.Typecheck.Solve
import Disco.Types
------------------------------------------------------------
-- Contexts
------------------------------------------------------------
-- | A typing context is a mapping from term names to types.
type TyCtx = Ctx Term PolyType
------------------------------------------------------------
-- Errors
------------------------------------------------------------
-- | A typechecking error, wrapped up together with the name of the
-- thing that was being checked when the error occurred.
data LocTCError = LocTCError (Maybe (QName Term)) TCError
deriving Show
| Wrap a @TCError@ into a @LocTCError@ with no explicit provenance
-- information.
noLoc :: TCError -> LocTCError
noLoc = LocTCError Nothing
-- | Potential typechecking errors.
data TCError
= Unbound (Name Term) -- ^ Encountered an unbound variable
| Ambiguous (Name Term) [ModuleName] -- ^ Encountered an ambiguous name.
| NoType (Name Term) -- ^ No type is specified for a definition
| NotCon Con Term Type -- ^ The type of the term should have an
outermost constructor matching Con , but
-- it has type 'Type' instead
| EmptyCase -- ^ Case analyses cannot be empty.
| PatternType Con Pattern Type -- ^ The given pattern should have the type, but it doesn't.
-- instead it has a kind of type given by the Con.
| DuplicateDecls (Name Term) -- ^ Duplicate declarations.
| DuplicateDefns (Name Term) -- ^ Duplicate definitions.
| DuplicateTyDefns String -- ^ Duplicate type definitions.
| CyclicTyDef String -- ^ Cyclic type definition.
| NumPatterns -- ^ # of patterns does not match type in definition
| NonlinearPattern Pattern (Name Term) -- ^ Duplicate variable in a pattern
| NoSearch Type -- ^ Type can't be quantified over.
| Unsolvable SolveError -- ^ The constraint solver couldn't find a solution.
| NotTyDef String -- ^ An undefined type name was used.
| NoTWild -- ^ Wildcards are not allowed in terms.
| NotEnoughArgs Con -- ^ Not enough arguments provided to type constructor.
| TooManyArgs Con -- ^ Too many arguments provided to type constructor.
| UnboundTyVar (Name Type) -- ^ Unbound type variable
| NoPolyRec String [String] [Type] -- ^ Polymorphic recursion is not allowed
| NoError -- ^ Not an error. The identity of the
-- @Monoid TCError@ instance.
deriving Show
instance Semigroup TCError where
_ <> r = r
| ' TCError ' is a monoid where we simply discard the first error .
instance Monoid TCError where
mempty = NoError
mappend = (<>)
------------------------------------------------------------
-- Constraints
------------------------------------------------------------
-- | Emit a constraint.
constraint :: Member (Writer Constraint) r => Constraint -> Sem r ()
constraint = tell
-- | Emit a list of constraints.
constraints :: Member (Writer Constraint) r => [Constraint] -> Sem r ()
constraints = constraint . cAnd
-- | Close over the current constraint with a forall.
forAll :: Member (Writer Constraint) r => [Name Type] -> Sem r a -> Sem r a
forAll nms = censor (CAll . bind nms)
| Run two constraint - generating actions and combine the constraints
-- via disjunction.
cOr :: Members '[Writer Constraint] r => Sem r () -> Sem r () -> Sem r ()
cOr m1 m2 = do
(c1, _) <- censor (const CTrue) (listen m1)
(c2, _) <- censor (const CTrue) (listen m2)
constraint $ COr [c1, c2]
-- | Run a computation that generates constraints, returning the
-- generated 'Constraint' along with the output. Note that this
-- locally dispatches the constraint writer effect.
--
-- This function is somewhat low-level; typically you should use
-- 'solve' instead, which also solves the generated constraints.
withConstraint :: Sem (Writer Constraint ': r) a -> Sem r (a, Constraint)
withConstraint = fmap swap . runWriter
-- | Run a computation and solve its generated constraint, returning
-- the resulting substitution (or failing with an error). Note that
-- this locally dispatches the constraint writer effect.
solve
:: Members '[Reader TyDefCtx, Error TCError, Output Message] r
=> Sem (Writer Constraint ': r) a -> Sem r (a, S)
solve m = do
(a, c) <- withConstraint m
res <- runSolve . inputToReader . solveConstraint $ c
case res of
Left e -> throw (Unsolvable e)
Right s -> return (a, s)
------------------------------------------------------------
-- Contexts
------------------------------------------------------------
| Look up the definition of a named type . Throw a ' NotTyDef ' error
-- if it is not found.
lookupTyDefn ::
Members '[Reader TyDefCtx, Error TCError] r
=> String -> [Type] -> Sem r Type
lookupTyDefn x args = do
d <- ask @TyDefCtx
case M.lookup x d of
Nothing -> throw (NotTyDef x)
Just (TyDefBody _ body) -> return $ body args
-- | Run a subcomputation with an extended type definition context.
withTyDefns :: Member (Reader TyDefCtx) r => TyDefCtx -> Sem r a -> Sem r a
withTyDefns tyDefnCtx = local (M.union tyDefnCtx)
------------------------------------------------------------
-- Fresh name generation
------------------------------------------------------------
-- | Generate a type variable with a fresh name.
freshTy :: Member Fresh r => Sem r Type
freshTy = TyVar <$> fresh (string2Name "a")
-- | Generate a fresh variable as an atom.
freshAtom :: Member Fresh r => Sem r Atom
freshAtom = AVar . U <$> fresh (string2Name "c")
| null | https://raw.githubusercontent.com/disco-lang/disco/a855e854850a00e5cae06a1aa3076e53531d261b/src/Disco/Typecheck/Util.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD-style (see LICENSE)
Maintainer :
Definition of type contexts, type errors, and various utilities
used during type checking.
---------------------------------------------------------------------------
----------------------------------------------------------
Contexts
----------------------------------------------------------
| A typing context is a mapping from term names to types.
----------------------------------------------------------
Errors
----------------------------------------------------------
| A typechecking error, wrapped up together with the name of the
thing that was being checked when the error occurred.
information.
| Potential typechecking errors.
^ Encountered an unbound variable
^ Encountered an ambiguous name.
^ No type is specified for a definition
^ The type of the term should have an
it has type 'Type' instead
^ Case analyses cannot be empty.
^ The given pattern should have the type, but it doesn't.
instead it has a kind of type given by the Con.
^ Duplicate declarations.
^ Duplicate definitions.
^ Duplicate type definitions.
^ Cyclic type definition.
^ # of patterns does not match type in definition
^ Duplicate variable in a pattern
^ Type can't be quantified over.
^ The constraint solver couldn't find a solution.
^ An undefined type name was used.
^ Wildcards are not allowed in terms.
^ Not enough arguments provided to type constructor.
^ Too many arguments provided to type constructor.
^ Unbound type variable
^ Polymorphic recursion is not allowed
^ Not an error. The identity of the
@Monoid TCError@ instance.
----------------------------------------------------------
Constraints
----------------------------------------------------------
| Emit a constraint.
| Emit a list of constraints.
| Close over the current constraint with a forall.
via disjunction.
| Run a computation that generates constraints, returning the
generated 'Constraint' along with the output. Note that this
locally dispatches the constraint writer effect.
This function is somewhat low-level; typically you should use
'solve' instead, which also solves the generated constraints.
| Run a computation and solve its generated constraint, returning
the resulting substitution (or failing with an error). Note that
this locally dispatches the constraint writer effect.
----------------------------------------------------------
Contexts
----------------------------------------------------------
if it is not found.
| Run a subcomputation with an extended type definition context.
----------------------------------------------------------
Fresh name generation
----------------------------------------------------------
| Generate a type variable with a fresh name.
| Generate a fresh variable as an atom. |
Module : Disco . . Util
Copyright : ( c ) 2016 disco team ( see LICENSE )
module Disco.Typecheck.Util where
import Disco.Effects.Fresh
import Polysemy
import Polysemy.Error
import Polysemy.Output
import Polysemy.Reader
import Polysemy.Writer
import Unbound.Generics.LocallyNameless (Name, bind, string2Name)
import qualified Data.Map as M
import Data.Tuple (swap)
import Prelude hiding (lookup)
import Disco.AST.Surface
import Disco.Context
import Disco.Messages
import Disco.Names (ModuleName, QName)
import Disco.Typecheck.Constraints
import Disco.Typecheck.Solve
import Disco.Types
type TyCtx = Ctx Term PolyType
data LocTCError = LocTCError (Maybe (QName Term)) TCError
deriving Show
| Wrap a @TCError@ into a @LocTCError@ with no explicit provenance
noLoc :: TCError -> LocTCError
noLoc = LocTCError Nothing
data TCError
outermost constructor matching Con , but
deriving Show
instance Semigroup TCError where
_ <> r = r
| ' TCError ' is a monoid where we simply discard the first error .
instance Monoid TCError where
mempty = NoError
mappend = (<>)
constraint :: Member (Writer Constraint) r => Constraint -> Sem r ()
constraint = tell
constraints :: Member (Writer Constraint) r => [Constraint] -> Sem r ()
constraints = constraint . cAnd
forAll :: Member (Writer Constraint) r => [Name Type] -> Sem r a -> Sem r a
forAll nms = censor (CAll . bind nms)
| Run two constraint - generating actions and combine the constraints
cOr :: Members '[Writer Constraint] r => Sem r () -> Sem r () -> Sem r ()
cOr m1 m2 = do
(c1, _) <- censor (const CTrue) (listen m1)
(c2, _) <- censor (const CTrue) (listen m2)
constraint $ COr [c1, c2]
withConstraint :: Sem (Writer Constraint ': r) a -> Sem r (a, Constraint)
withConstraint = fmap swap . runWriter
solve
:: Members '[Reader TyDefCtx, Error TCError, Output Message] r
=> Sem (Writer Constraint ': r) a -> Sem r (a, S)
solve m = do
(a, c) <- withConstraint m
res <- runSolve . inputToReader . solveConstraint $ c
case res of
Left e -> throw (Unsolvable e)
Right s -> return (a, s)
| Look up the definition of a named type . Throw a ' NotTyDef ' error
lookupTyDefn ::
Members '[Reader TyDefCtx, Error TCError] r
=> String -> [Type] -> Sem r Type
lookupTyDefn x args = do
d <- ask @TyDefCtx
case M.lookup x d of
Nothing -> throw (NotTyDef x)
Just (TyDefBody _ body) -> return $ body args
withTyDefns :: Member (Reader TyDefCtx) r => TyDefCtx -> Sem r a -> Sem r a
withTyDefns tyDefnCtx = local (M.union tyDefnCtx)
freshTy :: Member Fresh r => Sem r Type
freshTy = TyVar <$> fresh (string2Name "a")
freshAtom :: Member Fresh r => Sem r Atom
freshAtom = AVar . U <$> fresh (string2Name "c")
|
00597de0fe34b5d4a5423ae53bc7414c7904c47acab01ffb3015afa3a853b01c | jumarko/web-development-with-clojure | core.clj | (ns ring-app.core
(:require [ring.adapter.jetty :as jetty]
[ring.middleware.reload :refer [wrap-reload]]
[ring.util.http-response :as r]
[ring.middleware.format :refer [wrap-restful-format]]
[ring.middleware.defaults :refer [wrap-defaults site-defaults]]
[compojure.core :as c]))
(defn- response-handler [request]
(r/ok
(str "<html><body> your IP is: " (:remote-addr request) " </body></html>")))
(c/defroutes handler
(c/GET "/" request response-handler)
;; example from -Syntax
(c/GET "/foo/foo3/:id" [id greeting] (str "<h1>" greeting " user " id " </h1>"))
(c/GET "/:id" [id] (str "<p>the id is: " id " </p>"))
;; notice that output of following is a little bit strange with additional commas in quotes between elements
(c/GET "/foo/foo" request (interpose ", " (keys request)))
(c/POST "/foo/foo2" [x y :as request] (str x y request))
(c/POST "/json" [id] (r/ok {:result id})))
;; compojure also allows us to avoid repetition using context macro
(defn display-profile [id] )
(defn display-settings [id] )
(defn change-password-page [id] )
(c/defroutes user-routes
(c/context "/user/:id" [id]
(c/GET "/profile" [] (display-profile id))
(c/GET "/settings" [] (display-settings id))
(c/GET "/change-password" [] (change-password-page id))))
(defn wrap-nocache
"middleware which wraps response with 'Pragma: no-cache' header"
[handler]
(fn [request]
(-> request
handler
(assoc-in [:headers "Pragma"] "no-cache"))))
(defn wrap-formats
"Add JSON format"
[handler]
(wrap-restful-format
handler
{:formats [:json-kw :transit-json :transit-msgpack]}))
(defn -main []
(jetty/run-jetty
(-> handler
var ;; notice that we need to create var from handler for wrap-reload to work
(wrap-defaults site-defaults)
wrap-nocache
wrap-reload
wrap-formats)
{:port 3000
:join? false}))
| null | https://raw.githubusercontent.com/jumarko/web-development-with-clojure/dfff6e40c76b64e9fcd440d80c7aa29809601b6b/examples/ring-app/src/ring_app/core.clj | clojure | example from -Syntax
notice that output of following is a little bit strange with additional commas in quotes between elements
compojure also allows us to avoid repetition using context macro
notice that we need to create var from handler for wrap-reload to work | (ns ring-app.core
(:require [ring.adapter.jetty :as jetty]
[ring.middleware.reload :refer [wrap-reload]]
[ring.util.http-response :as r]
[ring.middleware.format :refer [wrap-restful-format]]
[ring.middleware.defaults :refer [wrap-defaults site-defaults]]
[compojure.core :as c]))
(defn- response-handler [request]
(r/ok
(str "<html><body> your IP is: " (:remote-addr request) " </body></html>")))
(c/defroutes handler
(c/GET "/" request response-handler)
(c/GET "/foo/foo3/:id" [id greeting] (str "<h1>" greeting " user " id " </h1>"))
(c/GET "/:id" [id] (str "<p>the id is: " id " </p>"))
(c/GET "/foo/foo" request (interpose ", " (keys request)))
(c/POST "/foo/foo2" [x y :as request] (str x y request))
(c/POST "/json" [id] (r/ok {:result id})))
(defn display-profile [id] )
(defn display-settings [id] )
(defn change-password-page [id] )
(c/defroutes user-routes
(c/context "/user/:id" [id]
(c/GET "/profile" [] (display-profile id))
(c/GET "/settings" [] (display-settings id))
(c/GET "/change-password" [] (change-password-page id))))
(defn wrap-nocache
"middleware which wraps response with 'Pragma: no-cache' header"
[handler]
(fn [request]
(-> request
handler
(assoc-in [:headers "Pragma"] "no-cache"))))
(defn wrap-formats
"Add JSON format"
[handler]
(wrap-restful-format
handler
{:formats [:json-kw :transit-json :transit-msgpack]}))
(defn -main []
(jetty/run-jetty
(-> handler
(wrap-defaults site-defaults)
wrap-nocache
wrap-reload
wrap-formats)
{:port 3000
:join? false}))
|
6f31712b50fb974361fee88052e781dcd234bb5a729d594173be58d438c2e511 | ktakashi/sagittarius-scheme | rsa_pss_2048_sha512_256_mgf1_28_test.scm | (test-signature/testvector
"rsa_pss_2048_sha512_256_mgf1_28_test"
:algorithm
"RSASSA-PSS"
:digest
"SHA-512/224"
:public-key
#vu8(48 130 1 34 48 13 6 9 42 134 72 134 247 13 1 1 1 5 0 3 130 1 15 0 48 130 1 10 2 130 1 1 0 163 143 188 243 78 239 24 16 203 42 226 31 239 30 154 30 3 127 125 37 212 62 139 79 5 30 167 76 54 123 221 178 50 122 123 204 197 51 79 230 16 247 169 133 94 43 118 193 233 113 89 112 194 44 39 70 22 253 148 96 215 39 175 233 161 73 194 59 107 151 48 193 60 79 98 19 224 193 18 164 157 178 229 89 147 182 12 82 14 183 48 66 199 160 177 191 228 226 123 17 164 199 57 80 87 35 82 51 253 138 179 137 138 213 106 120 147 7 123 188 68 20 180 8 154 89 76 156 190 197 222 202 9 46 251 77 132 217 119 185 243 127 217 130 52 29 169 99 162 10 246 128 255 74 119 78 200 90 16 74 104 70 72 176 169 11 108 196 247 212 128 141 182 102 235 171 128 138 33 2 15 140 0 92 103 147 241 150 24 120 17 147 85 38 202 241 182 206 228 122 12 20 224 130 63 135 215 170 130 233 245 166 53 202 17 102 134 210 218 113 156 218 38 156 57 216 99 87 28 96 110 92 229 51 66 84 228 150 72 252 252 245 2 161 50 28 192 113 241 0 13 86 39 35 21 111 2 3 1 0 1)
:mgf
"MGF1"
:mgf-digest
"SHA-512/224"
:salt-length
28
:der-encode
#t
:tests
'(#(1
""
#vu8()
#vu8(95 248 66 38 168 12 143 145 84 165 0 131 254 4 172 31 229 122 131 122 21 228 113 185 188 97 250 133 43 46 67 182 243 65 140 162 167 19 0 55 215 73 85 119 142 70 63 36 182 50 213 58 246 221 20 26 45 145 223 171 20 4 155 119 98 235 192 172 251 164 89 205 140 157 221 41 167 176 126 151 208 109 184 29 73 190 185 237 12 201 186 109 192 96 151 136 246 41 30 55 83 144 124 138 193 20 89 184 58 28 10 10 205 62 247 143 154 198 132 152 215 132 9 161 243 181 78 246 80 241 8 214 14 114 103 53 71 135 220 213 255 12 54 72 195 173 58 23 150 222 162 50 189 155 142 129 103 38 16 159 178 229 116 152 53 206 179 115 117 248 195 216 214 35 75 88 40 176 105 107 1 225 71 159 227 137 53 210 125 186 54 84 222 56 209 254 219 191 194 14 102 168 155 64 129 17 180 253 57 235 69 29 171 71 42 102 252 142 59 49 188 72 123 238 62 251 129 197 13 217 48 126 103 78 157 200 164 117 19 173 17 155 225 221 84 23 65 193 252 232 27 99 141 31 63 193)
#t
())
#(2
""
#vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#vu8(120 111 32 220 194 15 27 132 241 93 221 176 60 187 134 29 155 203 180 27 48 63 168 238 152 191 230 201 239 138 245 106 16 71 161 254 32 50 51 43 192 48 156 164 166 145 63 138 202 97 120 36 165 87 41 48 26 13 185 215 4 20 73 92 254 73 78 220 210 122 123 83 56 162 122 43 33 216 182 117 241 188 144 42 115 159 17 41 198 97 146 125 16 83 112 69 182 156 69 4 103 123 115 239 236 85 31 199 105 6 39 181 199 42 113 14 195 206 174 73 18 79 149 242 141 128 45 164 193 188 137 77 239 143 246 74 61 149 171 86 220 181 76 26 160 97 192 213 240 92 165 237 138 120 140 206 171 225 165 66 174 125 65 75 154 169 122 178 18 158 136 67 140 228 143 165 199 7 220 248 40 9 170 85 56 187 123 217 114 12 37 29 193 123 1 216 113 166 82 123 195 116 79 112 220 157 19 15 90 206 183 178 172 215 12 237 181 1 203 214 123 120 65 113 59 147 167 9 75 182 15 50 38 145 242 86 65 194 178 43 72 128 92 17 176 118 102 246 38 114 199 38 174 168 211 37)
#t
())
#(3
""
#vu8(84 101 115 116)
#vu8(107 111 140 172 206 14 80 66 158 94 96 235 21 173 71 70 236 173 65 211 187 185 115 165 108 236 31 120 48 35 224 240 4 165 194 109 223 73 76 255 202 41 213 208 237 209 169 197 47 24 29 105 191 115 69 12 97 234 158 160 16 43 180 18 36 77 91 79 246 226 194 22 190 118 244 82 56 23 8 180 95 14 128 174 182 57 26 74 213 211 137 21 95 181 229 203 56 230 162 227 3 224 188 99 245 45 39 131 11 253 30 56 7 190 237 197 217 73 91 125 92 253 17 61 192 198 225 188 23 8 93 234 151 187 202 95 13 70 43 99 190 197 166 100 235 92 31 245 135 69 144 56 245 190 124 220 76 220 179 32 215 104 106 11 151 255 253 35 65 234 242 134 233 0 23 111 133 20 23 16 102 108 107 207 58 121 127 158 130 130 167 145 8 37 215 191 77 41 48 220 32 138 172 54 102 112 112 27 88 59 132 129 126 99 105 162 24 48 84 184 148 229 5 220 236 245 64 91 33 16 249 107 107 139 36 69 66 164 102 191 15 15 113 65 205 222 238 127 6 19 55 144 40 209 165 188)
#t
())
#(4
""
#vu8(49 50 51 52 48 48)
#vu8(105 248 249 9 198 244 207 78 217 153 80 204 194 133 21 88 138 154 120 28 37 89 222 142 44 232 176 167 63 244 35 190 71 91 88 217 29 110 181 122 112 144 38 4 97 95 217 250 178 230 188 166 181 253 48 46 176 44 95 75 110 53 167 205 17 50 5 134 246 41 88 52 181 93 76 79 9 196 169 123 158 242 45 35 33 168 244 238 241 163 144 74 33 101 124 52 103 63 251 114 216 60 160 68 228 45 114 134 194 104 19 47 172 78 60 51 118 212 178 112 179 221 162 191 224 226 190 186 45 134 112 167 194 36 187 123 192 39 19 239 190 239 118 125 80 14 234 78 62 255 76 145 88 8 156 95 29 150 245 193 10 22 84 131 125 16 232 77 35 188 132 22 107 20 200 82 169 175 12 226 15 76 248 166 59 123 90 219 119 90 174 13 210 250 151 205 187 88 141 54 231 15 171 169 73 228 85 65 168 59 180 233 234 53 117 38 79 143 29 130 25 83 208 175 1 219 42 22 172 64 18 238 151 185 241 202 235 174 206 90 177 201 68 85 155 12 148 65 74 236 173 214 102 107 25 164)
#t
())
#(5
""
#vu8(77 101 115 115 97 103 101)
#vu8(117 127 78 235 219 3 104 55 132 68 5 131 25 244 124 116 214 165 77 65 113 16 55 15 218 208 50 173 43 154 198 23 65 61 67 177 34 114 223 210 0 245 246 153 68 169 204 175 246 80 170 197 236 85 60 117 119 249 171 75 43 37 164 191 134 151 141 0 191 18 94 153 218 140 3 241 239 142 162 35 207 28 75 222 90 102 7 239 98 37 58 21 81 72 52 185 2 151 1 92 194 72 175 39 40 68 56 235 195 203 65 102 39 178 80 84 207 113 154 159 213 159 21 114 187 240 13 199 179 109 48 61 218 108 227 150 249 252 141 199 129 18 133 77 26 104 195 156 251 50 183 197 111 12 67 170 91 134 219 225 150 55 164 243 171 86 132 75 154 228 66 10 85 175 180 84 147 31 141 92 186 88 88 161 252 235 239 248 223 33 162 123 51 73 103 94 0 144 233 186 185 191 215 86 42 180 189 86 151 116 250 218 69 236 195 143 194 206 192 24 155 202 222 137 139 141 232 108 243 144 129 189 217 95 56 217 80 47 32 177 41 180 217 212 101 193 20 58 134 157 31 172 88 216 39 199)
#t
())
#(6
""
#vu8(97)
#vu8(55 190 58 193 227 250 27 240 88 0 226 238 150 138 101 214 88 14 101 60 220 104 117 239 189 105 8 129 83 54 119 122 29 143 179 163 39 58 21 210 190 152 139 177 22 23 153 100 23 4 246 18 28 48 61 98 169 87 104 155 185 2 62 166 101 86 31 95 43 1 51 46 247 20 41 213 101 152 123 162 217 190 130 111 1 225 211 220 66 125 135 245 20 236 167 74 146 151 116 19 70 115 195 174 171 36 230 141 36 102 27 11 128 87 125 163 32 3 13 98 211 199 199 225 163 83 0 189 117 205 18 13 189 172 29 42 169 123 249 4 255 158 247 74 245 50 55 195 218 20 189 213 112 34 246 169 184 252 147 171 72 34 123 115 84 104 189 132 96 197 9 205 217 39 121 170 13 198 242 115 203 228 91 188 215 60 166 211 41 102 203 51 200 174 97 116 63 24 21 125 49 198 59 144 90 200 106 20 165 232 34 205 206 201 43 125 66 103 198 248 201 18 227 96 221 152 254 114 73 72 179 154 181 70 178 64 61 175 116 11 120 233 85 226 13 55 254 228 80 65 41 254 77 74 125 196)
#t
())
#(7
""
#vu8(224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255)
#vu8(56 42 106 0 192 44 147 153 31 78 117 202 234 241 153 233 230 6 158 65 76 182 23 145 98 191 71 203 210 236 15 89 242 20 255 17 32 121 69 181 98 30 41 189 29 157 11 110 229 117 59 164 125 237 123 37 177 204 240 221 11 110 243 147 2 177 112 86 92 85 243 126 99 254 252 126 215 153 171 199 60 231 90 176 86 173 31 28 248 209 193 176 66 5 206 80 32 186 156 47 189 251 166 18 134 125 213 237 132 72 237 121 51 31 243 31 25 234 123 42 78 249 201 27 234 158 56 105 121 96 54 58 176 85 22 94 75 104 221 47 85 28 65 2 228 131 174 68 138 124 115 32 129 12 40 73 161 87 242 249 20 24 180 242 130 213 150 179 81 248 237 122 93 77 176 112 25 102 142 210 123 112 208 224 46 215 14 150 37 151 196 249 94 46 11 200 161 41 78 32 166 155 107 115 155 185 112 75 133 87 190 42 167 181 48 215 9 86 60 209 207 150 107 232 240 108 131 18 18 73 211 73 152 193 236 184 111 115 245 179 122 196 147 21 244 223 219 214 158 78 11 29 195 42 167 149)
#t
())
#(8
"first byte of m_hash modified"
#vu8(49 50 51 52 48 48)
#vu8(1 173 5 50 240 177 17 231 235 182 170 142 14 42 125 40 119 0 128 98 26 7 57 203 194 107 236 30 14 108 214 212 116 176 247 74 29 200 45 50 3 29 80 59 218 98 235 210 220 166 205 42 40 130 28 60 37 121 199 32 169 217 175 29 162 81 43 31 187 113 250 116 182 82 98 219 235 28 111 9 96 19 136 167 33 80 21 50 242 179 127 68 25 135 12 149 176 89 80 7 242 232 248 220 113 130 183 199 27 39 247 230 235 184 78 115 108 16 126 192 81 64 178 87 211 23 194 98 173 4 66 36 32 137 96 198 243 29 113 82 101 209 148 7 100 151 212 82 25 86 247 164 140 252 9 66 139 189 203 79 197 58 216 190 17 83 105 136 115 243 96 237 9 201 254 16 211 185 213 235 45 250 15 234 199 74 118 75 224 68 177 204 93 94 123 103 68 69 95 163 136 156 98 89 8 10 158 198 114 160 23 201 229 179 122 232 124 174 133 211 219 113 248 23 133 227 68 224 18 85 172 236 141 121 190 48 141 172 174 156 49 170 144 8 48 139 67 18 111 114 54 241 4 245 67 194)
#f
())
#(9
"first byte of m_hash modified"
#vu8(49 50 51 52 48 48)
#vu8(13 110 126 116 138 165 55 163 9 220 59 56 156 250 176 176 180 145 198 243 225 172 177 177 148 81 65 54 128 232 15 195 217 138 28 51 170 177 1 133 224 202 163 95 183 135 7 247 181 223 83 218 83 78 168 140 6 67 235 45 140 169 212 32 66 60 223 17 72 161 117 121 204 107 36 252 249 255 145 7 174 232 197 196 33 157 16 105 180 39 48 228 112 22 93 112 119 91 113 96 223 34 57 188 31 27 174 28 247 232 140 134 169 107 68 171 164 152 131 72 58 56 181 72 20 213 186 144 84 11 193 103 199 114 242 254 127 197 136 220 120 152 209 191 157 232 99 194 145 143 36 104 81 79 8 57 54 151 192 29 246 180 201 195 68 129 83 241 162 34 147 106 255 18 61 214 76 24 166 2 31 187 142 227 50 39 82 159 193 148 40 41 37 226 164 97 86 142 116 241 77 7 43 253 17 73 177 9 178 169 175 145 231 203 244 61 255 187 186 94 21 130 24 0 95 132 46 17 134 4 179 141 210 58 10 181 231 163 236 69 36 250 236 20 175 241 157 136 99 56 210 217 75 25 239 242)
#f
())
#(10
"last byte of m_hash modified"
#vu8(49 50 51 52 48 48)
#vu8(158 242 44 46 173 169 53 9 200 168 200 214 146 213 249 188 195 253 76 138 17 74 162 242 96 165 69 160 158 117 81 35 33 211 215 126 83 97 77 146 139 113 61 150 47 38 23 161 50 5 4 20 81 212 121 208 227 159 233 18 224 152 192 149 56 106 237 33 166 6 220 130 240 5 61 52 89 94 81 184 35 38 40 203 54 113 51 239 15 169 143 79 173 228 180 32 166 56 60 124 10 131 33 184 86 10 192 235 93 57 123 238 223 227 11 76 74 171 88 254 35 16 161 142 242 144 90 157 90 101 189 95 129 158 57 43 218 193 103 166 212 51 35 227 97 30 215 171 246 68 92 240 136 171 17 243 199 57 120 30 47 122 3 31 215 128 178 2 118 126 51 192 233 145 177 26 10 238 132 3 151 251 140 229 120 182 81 59 243 9 23 145 46 178 160 106 193 48 9 8 115 79 248 2 186 14 54 70 89 63 244 249 42 97 205 46 25 50 31 240 103 46 42 253 144 45 238 19 190 246 123 25 125 254 26 196 228 140 225 120 5 234 103 165 207 60 58 28 7 236 173 254 113 10 150 52)
#f
())
#(11
"last byte of m_hash modified"
#vu8(49 50 51 52 48 48)
#vu8(136 254 107 5 191 29 184 41 7 83 226 26 112 38 102 91 18 34 27 167 151 98 198 105 161 145 16 192 34 33 233 1 56 173 189 208 20 126 82 230 159 196 129 121 32 131 76 158 79 50 215 147 45 117 151 114 125 139 30 139 168 141 87 146 204 12 122 74 153 38 28 139 244 71 229 105 253 29 17 242 123 84 65 185 133 252 91 85 19 74 63 63 16 229 119 74 198 196 38 197 90 8 25 71 184 155 83 126 238 12 125 42 226 243 234 104 186 79 29 136 132 83 158 45 106 38 198 219 19 37 4 57 231 137 101 187 241 48 238 79 242 161 139 66 63 233 101 149 234 255 81 14 127 140 32 144 180 205 65 139 183 42 224 219 252 200 204 174 45 150 128 10 109 163 7 130 179 57 224 229 223 241 141 240 204 1 203 94 207 120 167 227 43 216 17 186 221 171 216 41 121 184 249 235 187 194 184 183 50 34 102 15 48 181 202 18 66 49 199 151 246 35 159 181 207 60 94 62 106 233 235 77 158 102 179 76 91 127 127 172 56 81 6 15 192 157 91 13 234 115 32 171 243 246 112 117)
#f
())
#(12
"all bits in m_hash flipped"
#vu8(49 50 51 52 48 48)
#vu8(77 29 15 245 228 77 42 10 121 78 249 228 248 225 56 64 72 36 215 218 51 186 41 28 105 84 160 97 188 208 130 125 208 36 52 68 47 109 56 221 157 162 234 130 104 195 175 17 187 241 188 25 24 55 182 76 219 239 11 196 219 54 1 229 190 193 207 183 51 33 71 74 33 236 136 228 62 18 166 221 113 31 31 44 202 68 1 60 3 38 23 57 53 113 174 28 30 30 26 89 92 221 217 34 20 207 140 232 211 57 35 151 186 104 77 176 227 27 208 154 200 229 137 181 242 179 235 246 162 211 64 58 232 215 239 123 45 14 28 53 253 73 178 238 252 137 110 250 51 109 248 218 66 16 83 5 235 211 152 202 139 194 206 7 115 50 96 229 8 113 255 214 204 176 58 161 159 165 253 135 228 154 152 50 106 183 138 199 174 153 241 41 22 102 152 33 55 166 63 229 70 195 243 77 85 12 253 207 77 250 116 174 80 231 130 47 185 206 197 20 77 138 250 190 212 74 237 97 195 169 142 132 163 218 125 59 118 121 158 30 192 201 54 174 193 120 212 113 225 161 99 135 174 66 200 121)
#f
())
#(13
"s_len changed to 0"
#vu8(49 50 51 52 48 48)
#vu8(49 158 118 253 64 248 249 113 192 97 133 135 77 97 81 44 40 20 1 158 47 92 104 248 170 99 122 174 189 25 232 223 56 250 243 53 83 52 136 112 194 232 181 72 48 174 61 252 183 19 86 167 62 54 159 230 45 91 185 223 128 205 151 96 164 27 178 154 100 184 110 95 92 12 186 113 240 29 218 53 148 3 102 168 244 149 53 205 248 244 150 202 243 72 228 1 9 101 207 152 228 206 237 147 147 251 97 210 37 46 209 113 102 130 183 144 84 162 221 214 195 21 212 120 197 34 167 206 2 181 76 90 146 23 31 11 126 43 189 243 87 20 95 131 10 198 242 58 166 32 193 196 48 152 232 48 19 76 12 28 170 126 66 180 151 208 75 199 44 73 19 138 205 107 80 229 216 47 113 227 112 250 220 246 4 179 218 24 178 166 133 221 153 236 216 224 14 229 141 93 238 229 36 91 158 36 125 10 200 11 59 202 136 72 96 209 195 26 103 125 72 26 0 188 5 249 214 206 61 23 233 8 186 199 71 137 81 38 230 140 141 89 168 44 195 223 153 86 162 75 119 190 110 42 211 155)
#f
())
#(14
"s_len changed to 20"
#vu8(49 50 51 52 48 48)
#vu8(113 36 44 73 12 201 119 52 209 130 65 253 196 38 33 123 140 125 224 137 193 128 116 157 100 209 103 227 250 150 201 54 5 65 211 214 201 246 52 134 211 151 83 157 142 129 255 128 99 207 21 225 56 38 251 148 97 140 99 134 32 247 143 168 27 33 166 60 26 162 32 208 174 26 35 92 227 52 89 42 13 139 237 110 52 104 39 12 195 251 40 158 87 255 243 183 70 53 29 78 157 65 227 52 87 141 26 115 48 250 156 235 71 41 143 86 56 167 134 249 15 127 247 121 247 164 98 105 19 136 182 10 82 206 207 8 183 161 3 143 21 77 143 117 180 214 102 105 11 125 11 143 142 206 238 12 93 139 96 123 183 192 185 98 112 219 160 196 181 229 25 153 253 237 94 109 229 9 90 114 212 91 32 148 92 71 174 190 113 126 141 153 86 132 88 43 9 152 131 67 31 78 215 59 115 84 157 65 81 142 97 214 220 118 217 87 205 13 137 138 124 181 81 251 210 166 91 101 11 182 51 231 67 245 169 113 182 195 181 99 127 235 160 117 184 152 133 179 98 167 224 240 218 59 158 227)
#f
())
#(15
"s_len changed to 32"
#vu8(49 50 51 52 48 48)
#vu8(146 88 227 227 222 255 239 192 250 64 109 252 28 98 197 129 168 39 60 172 185 52 35 102 219 156 156 41 132 198 208 8 71 49 49 213 166 167 142 192 217 28 253 32 211 1 24 26 134 195 52 170 82 205 243 101 56 68 67 150 56 68 239 8 90 86 32 187 33 129 89 120 2 181 223 250 113 179 64 132 96 122 39 252 221 127 117 16 238 193 57 89 209 57 255 20 18 194 138 201 253 220 51 174 55 115 60 118 125 113 190 110 194 3 79 162 205 40 164 24 220 64 202 179 208 47 36 35 185 209 55 241 29 103 7 182 127 17 211 9 81 225 16 199 197 197 79 172 176 208 105 240 157 84 69 109 189 255 42 215 170 197 188 88 77 73 132 38 182 136 141 69 169 228 207 30 122 32 172 18 175 59 49 157 73 226 113 255 232 26 239 185 160 234 25 55 221 126 89 193 204 182 193 137 161 52 136 37 101 92 113 118 238 238 250 243 95 157 224 227 57 24 124 217 156 231 224 133 76 144 7 94 91 159 194 167 196 112 23 198 221 76 73 192 212 226 71 79 236 150 227 195 170 138 2 63)
#f
())
#(16
"salt is all 0"
#vu8(49 50 51 52 48 48)
#vu8(74 159 184 209 160 79 253 54 163 78 250 69 5 249 149 0 219 119 101 115 112 181 187 133 71 166 66 132 119 184 9 149 52 234 202 97 29 231 87 183 3 178 80 109 70 63 82 194 107 189 159 246 187 127 250 252 62 163 142 134 254 253 147 98 136 133 73 116 205 77 184 79 216 163 188 49 193 39 101 205 165 94 118 238 56 78 222 130 49 124 205 120 2 134 181 108 31 145 110 84 95 115 94 67 39 250 240 91 158 196 213 9 80 148 173 177 158 85 250 103 3 185 34 119 83 63 233 188 185 58 0 82 213 223 237 73 48 21 23 178 56 216 225 37 226 222 228 131 228 210 131 155 138 127 168 141 15 222 224 22 76 8 174 134 107 137 204 127 227 189 73 74 45 42 60 46 55 7 175 37 124 199 186 229 60 217 59 134 161 157 204 115 152 80 128 192 53 179 68 174 79 232 146 71 165 22 92 231 189 193 177 81 61 197 188 105 60 73 122 3 255 118 31 137 145 229 36 221 119 155 223 47 121 108 124 67 164 230 244 83 117 46 172 16 151 220 60 10 146 131 14 1 188 165 98 88)
#t
())
#(17
"salt is all 1"
#vu8(49 50 51 52 48 48)
#vu8(71 69 147 234 71 1 62 98 183 21 102 4 194 97 148 59 59 110 186 37 233 14 51 156 166 101 154 5 75 205 10 6 193 0 84 81 32 240 163 45 97 76 66 141 226 138 240 5 248 103 218 116 228 76 45 254 208 231 145 214 253 201 180 43 92 197 47 169 134 144 240 83 247 236 20 12 98 134 216 8 226 203 222 176 199 217 16 33 27 254 242 252 15 144 29 244 149 141 246 21 50 148 240 221 215 112 159 190 201 42 220 60 194 163 217 79 62 139 152 60 34 219 25 197 25 50 239 71 252 46 8 146 228 159 67 244 43 221 173 232 134 163 214 92 48 73 211 145 113 132 57 218 71 209 251 180 212 226 60 108 2 92 209 20 59 249 248 235 254 211 114 60 150 221 161 38 175 10 35 94 58 32 247 22 221 242 125 116 247 241 210 176 226 53 77 22 198 238 250 32 87 57 166 119 82 151 233 5 167 98 210 180 61 86 49 156 93 101 32 242 201 67 199 242 244 169 24 131 107 142 193 188 182 171 67 124 178 70 144 116 110 158 184 225 62 243 12 143 139 219 68 166 216 44 91 103)
#t
())
#(18
"byte 0 in zero padding modified"
#vu8(49 50 51 52 48 48)
#vu8(137 232 73 239 194 104 3 227 161 82 118 95 197 59 16 213 69 213 190 87 79 50 151 98 59 202 239 253 26 180 45 214 113 144 42 191 154 153 208 177 105 204 62 173 112 10 33 118 48 77 3 51 239 49 47 38 172 38 61 89 75 174 57 210 64 79 213 230 150 90 231 135 149 245 48 128 134 179 251 230 136 16 113 41 126 196 183 76 162 64 24 36 73 7 173 206 151 166 205 9 172 160 233 114 22 157 249 29 71 68 228 194 65 238 218 88 219 206 0 194 200 108 187 157 11 27 77 29 169 32 26 17 233 96 21 207 93 155 214 204 251 216 63 18 188 134 39 105 122 27 158 16 44 130 47 242 3 235 43 134 182 104 177 81 24 233 115 114 149 120 3 134 188 5 5 219 72 228 110 202 29 117 38 103 55 64 101 205 8 78 53 121 5 240 69 37 183 26 98 70 84 202 151 212 170 46 106 86 98 40 254 172 161 15 178 250 122 189 123 47 203 103 156 137 199 48 232 11 44 30 89 78 231 133 133 91 221 75 203 121 169 248 85 163 193 126 60 227 35 173 4 175 237 216 145 12)
#f
())
#(19
"byte 7 in zero padding modified"
#vu8(49 50 51 52 48 48)
#vu8(63 231 202 71 156 41 203 99 146 77 18 244 120 29 177 223 252 67 185 42 160 182 2 218 226 144 207 59 207 10 112 84 80 176 207 99 153 231 177 44 250 79 84 63 51 76 129 157 218 92 21 173 45 211 67 207 151 171 5 141 40 120 14 218 225 132 218 13 162 21 197 28 112 84 195 106 199 18 68 103 234 219 37 26 175 94 218 148 119 109 229 125 239 32 66 10 200 241 84 228 65 86 32 47 78 71 159 82 97 76 193 27 236 105 71 217 107 235 41 28 79 66 200 113 183 1 206 142 116 70 70 177 46 150 117 87 187 144 51 71 86 148 233 138 46 162 214 248 109 51 157 55 122 199 234 141 254 64 87 233 2 152 25 49 9 91 158 0 76 81 9 227 45 202 197 96 215 240 210 99 1 123 50 24 195 57 251 46 43 209 48 39 227 12 209 148 170 147 78 21 170 252 193 51 220 20 124 20 84 253 97 214 161 128 59 62 156 33 214 233 21 143 204 26 144 182 119 158 158 13 140 129 80 241 100 116 190 155 22 78 111 155 217 137 39 176 105 100 28 237 191 216 60 100 51 75)
#f
())
#(20
"all bytes in zero padding modified"
#vu8(49 50 51 52 48 48)
#vu8(92 132 100 145 48 176 189 19 229 85 42 66 117 192 2 210 24 206 119 53 56 42 123 87 113 167 211 52 166 88 85 12 162 238 69 160 209 165 107 76 12 45 109 17 52 215 204 165 219 100 66 173 175 238 4 77 185 44 48 61 86 197 81 32 80 210 216 29 189 2 181 8 234 215 220 170 1 255 8 29 104 237 138 179 50 67 215 254 244 51 201 243 175 211 177 131 151 37 214 254 121 54 182 104 167 92 164 116 50 249 46 125 197 37 152 76 1 177 120 45 131 56 48 187 158 110 228 82 116 107 47 74 89 210 113 42 31 169 64 248 22 136 152 10 172 220 188 157 179 166 85 22 243 0 178 217 16 76 253 206 61 112 2 116 32 97 247 21 0 112 233 225 116 168 61 119 152 88 188 242 70 218 171 93 41 182 129 238 82 223 174 179 66 128 110 245 106 144 147 28 210 27 149 222 175 16 92 1 184 199 175 116 140 15 156 236 173 135 2 133 253 198 164 63 149 248 124 5 47 195 95 26 49 83 184 208 155 34 24 207 190 114 116 180 140 143 111 233 93 154 136 219 99 77 21 91)
#f
())
#(21
"first byte of hash h modified"
#vu8(49 50 51 52 48 48)
#vu8(111 48 183 207 46 94 53 135 37 244 38 183 57 144 23 30 141 89 249 236 107 224 204 210 18 73 74 63 236 165 126 43 9 73 1 29 252 237 147 146 63 147 203 136 163 157 44 3 185 220 193 6 232 215 2 207 53 255 51 130 236 80 134 99 70 120 31 190 241 155 215 121 42 252 30 130 221 158 21 246 4 250 232 121 156 219 220 128 70 144 152 255 161 169 171 80 115 163 66 204 209 255 127 70 20 234 6 204 69 229 155 35 125 243 138 34 241 93 27 247 86 96 40 236 75 225 122 193 149 122 100 137 12 125 204 96 19 67 204 254 176 120 135 13 217 9 132 31 124 82 12 159 43 46 223 122 136 7 72 116 196 114 195 220 66 65 152 18 22 229 156 236 204 190 118 94 128 153 38 5 123 134 82 84 115 139 196 247 202 17 234 239 4 86 21 239 155 78 34 65 83 179 46 42 212 237 222 171 94 42 129 8 16 69 184 171 103 159 95 179 63 83 12 234 69 230 235 239 240 172 73 65 218 247 41 83 184 73 114 4 203 233 142 211 129 113 64 183 187 157 112 173 232 164 148 115)
#f
())
#(22
"first byte of hash h modified"
#vu8(49 50 51 52 48 48)
#vu8(126 208 235 36 3 155 228 105 93 222 81 125 148 209 183 190 127 42 229 159 59 163 167 226 32 80 247 254 137 158 67 48 185 96 80 130 143 80 55 14 203 80 195 87 175 71 75 216 102 236 235 147 176 116 155 243 138 151 172 188 249 191 168 255 83 163 4 144 174 195 204 95 107 57 200 182 193 148 137 30 121 114 166 158 61 194 208 87 151 82 66 0 204 2 175 8 51 206 162 132 5 59 159 149 60 34 48 49 105 11 30 31 184 167 178 96 158 107 185 79 60 112 28 218 72 77 79 125 132 144 43 98 252 145 224 240 236 105 56 125 93 244 151 227 24 182 112 106 16 164 88 30 63 7 60 117 5 10 148 102 60 200 51 53 213 15 5 31 245 208 5 151 79 54 164 84 31 101 165 96 229 135 240 156 146 79 82 167 129 83 116 89 242 5 38 248 148 89 118 91 75 173 243 160 64 195 57 34 116 64 225 98 80 123 192 249 250 145 225 106 78 77 88 198 200 31 239 199 110 109 184 34 14 180 159 109 18 118 205 220 20 111 13 150 74 175 190 244 156 147 95 83 184 162 178 21)
#f
())
#(23
"last byte of hash h modified"
#vu8(49 50 51 52 48 48)
#vu8(99 40 66 230 205 25 11 10 160 49 5 73 146 64 160 77 251 61 97 33 118 100 45 223 104 238 254 143 246 125 225 140 211 135 22 91 245 243 78 120 5 46 241 209 171 136 140 97 104 170 33 249 119 217 54 133 110 174 197 202 0 52 172 236 33 99 16 52 48 76 71 16 245 102 90 130 23 243 20 209 191 151 5 135 217 158 6 239 56 110 156 11 225 165 251 198 69 197 243 243 110 73 126 69 87 226 172 131 3 55 24 35 9 100 25 154 223 133 122 217 113 236 105 212 33 106 172 208 237 37 126 222 199 60 138 100 74 162 94 23 82 151 244 20 184 201 17 233 220 91 182 134 109 193 185 199 229 45 94 101 109 89 140 122 112 7 167 200 66 130 142 147 74 80 142 124 14 64 3 38 62 101 126 132 191 45 16 160 204 187 71 98 11 236 190 15 82 195 240 149 177 126 61 212 233 6 251 173 127 69 235 219 232 153 90 97 203 248 43 110 213 138 50 241 46 51 179 144 15 186 7 216 20 150 147 164 60 52 100 156 189 52 170 122 107 147 3 212 15 24 123 188 246 26 19 206)
#f
())
#(24
"last byte of hash h modified"
#vu8(49 50 51 52 48 48)
#vu8(84 94 205 58 27 135 153 183 73 227 123 196 95 168 185 151 209 95 18 209 18 58 187 7 118 97 48 231 68 41 162 190 207 150 132 235 237 160 133 93 240 117 226 177 138 199 202 145 231 125 142 104 46 23 19 25 247 66 235 109 131 60 19 131 255 35 52 17 221 127 163 102 57 239 98 143 191 111 165 58 176 115 131 193 102 54 65 255 228 205 3 13 32 254 75 53 117 151 213 27 203 226 114 92 6 186 0 5 36 26 121 88 185 97 169 107 180 69 191 25 185 5 111 215 21 69 19 207 125 34 96 42 14 39 29 233 39 50 4 149 91 217 68 152 78 216 41 44 18 82 33 5 156 38 185 211 206 220 121 240 117 14 67 14 136 98 118 42 57 122 10 135 55 254 86 35 230 104 188 36 165 236 139 97 158 5 6 208 151 32 190 174 207 2 200 67 33 83 212 201 24 164 97 199 211 37 93 177 155 177 44 140 95 254 4 111 208 103 107 230 133 138 232 131 161 62 113 230 156 53 238 47 9 55 95 1 161 253 94 23 230 96 97 79 31 41 61 176 167 103 1 204 162 123 150 153)
#f
())
#(25
"all bytes of h replaced by 0"
#vu8(49 50 51 52 48 48)
#vu8(158 1 88 200 203 52 111 227 135 225 29 117 20 31 36 51 54 175 11 149 96 96 126 42 249 241 108 96 242 113 182 97 74 136 66 163 71 161 122 39 187 73 241 63 137 76 210 228 148 193 136 131 101 180 51 195 196 204 107 176 223 210 219 223 83 7 49 73 106 253 243 154 112 202 242 146 113 172 197 138 116 212 25 107 133 187 143 55 111 172 223 134 35 43 157 0 249 245 202 191 10 55 195 47 113 230 176 215 203 120 162 233 50 102 59 243 60 104 52 42 23 87 120 38 162 48 185 7 46 111 151 169 155 207 103 155 112 150 88 194 158 224 126 243 128 146 57 233 83 188 121 147 62 75 228 131 99 12 177 250 223 149 20 60 96 234 43 67 84 68 233 114 180 130 72 179 153 205 146 38 28 11 201 249 73 255 108 220 82 225 255 105 51 71 231 94 101 250 170 106 254 60 165 82 205 54 134 214 99 214 49 169 97 4 107 123 170 10 174 14 98 120 60 223 23 92 23 140 145 246 18 72 34 157 85 132 224 7 15 34 24 196 129 173 115 222 124 218 190 97 233 51 230 47 63 83)
#f
())
#(26
"all bits of h replaced by 1s"
#vu8(49 50 51 52 48 48)
#vu8(30 201 149 96 239 112 240 44 82 60 57 203 210 26 234 13 14 106 101 147 178 2 158 201 233 244 153 248 221 189 134 74 10 133 188 220 216 172 234 134 112 144 197 17 235 214 51 16 91 131 3 81 85 7 72 12 203 88 219 244 223 160 59 185 2 217 50 115 135 48 41 248 225 10 2 188 20 9 19 213 173 28 30 109 135 169 123 66 117 86 145 84 29 254 125 52 75 176 204 32 157 210 188 138 44 54 179 202 248 41 90 17 189 208 96 222 52 125 78 145 178 56 42 83 188 174 250 41 223 0 151 141 73 64 111 192 93 84 12 239 106 221 89 57 202 9 21 208 215 217 143 8 131 231 207 80 4 211 218 144 160 251 61 11 156 230 184 86 127 208 63 241 207 68 200 216 10 63 249 241 179 22 194 40 64 18 73 2 202 215 191 43 212 78 147 212 195 68 198 169 87 164 157 91 132 123 121 174 210 249 151 87 225 207 204 24 202 154 190 46 123 44 26 250 162 156 1 101 239 197 235 172 28 128 168 94 193 113 99 114 104 190 237 83 110 89 29 55 236 109 166 158 226 229 58 168)
#f
())
#(27
"all bits in hash h flipped"
#vu8(49 50 51 52 48 48)
#vu8(43 79 240 127 119 136 175 160 207 99 162 133 162 184 136 96 249 167 95 126 215 104 161 70 128 171 61 16 93 112 166 18 250 201 138 30 135 132 121 15 246 193 202 3 220 206 90 30 216 74 134 196 80 38 15 154 136 204 83 43 252 48 230 183 255 2 48 160 220 86 6 119 159 21 83 68 114 148 179 105 46 137 203 145 134 79 58 149 197 145 233 206 132 162 243 133 21 130 109 197 99 60 7 92 189 173 3 239 240 106 132 102 214 236 153 195 39 117 12 110 120 200 215 126 51 87 59 229 25 8 85 213 144 176 126 121 187 61 96 153 104 140 95 57 193 146 196 215 191 143 191 32 93 38 120 155 140 199 178 144 216 64 112 107 163 49 144 19 108 186 58 166 189 22 238 20 229 65 43 200 217 157 125 36 87 88 9 58 34 54 165 60 245 88 37 213 114 230 145 8 176 43 25 24 139 250 0 69 87 63 99 158 22 148 247 175 30 214 41 158 16 242 138 26 149 60 167 41 74 14 250 70 47 159 209 135 109 111 175 46 124 64 229 85 79 255 128 200 239 37 110 66 79 2 227 244)
#f
())
#(28
"hash of salt missing"
#vu8(49 50 51 52 48 48)
#vu8(109 236 65 10 78 53 102 165 33 91 108 157 15 229 250 11 95 92 101 223 12 79 149 45 203 124 72 215 206 245 123 22 218 163 21 215 209 224 92 89 40 188 6 21 221 14 81 189 83 60 82 117 60 107 84 181 36 165 76 120 122 169 86 189 58 248 174 126 172 31 205 180 173 236 187 189 17 74 154 225 155 103 103 201 231 71 78 250 84 232 248 97 186 185 62 12 148 248 176 201 54 25 83 201 65 30 18 243 75 95 158 132 250 95 138 234 41 227 22 235 152 59 136 50 40 87 69 101 230 213 61 130 196 117 69 170 199 13 61 59 36 238 62 43 58 205 89 126 227 36 100 23 109 169 14 150 35 236 44 208 40 49 222 64 225 253 92 98 123 66 25 65 101 23 27 200 135 112 67 254 143 89 117 227 134 49 165 87 1 216 78 137 95 166 157 214 119 141 218 132 152 117 100 82 209 113 199 25 88 152 239 233 203 131 123 42 189 154 34 165 140 18 48 251 127 171 44 107 149 91 92 210 78 185 124 246 127 234 1 140 47 40 50 52 165 189 138 190 6 149 178 82 176 71 220 240)
#f
())
#(29
"first byte of ps modified"
#vu8(49 50 51 52 48 48)
#vu8(97 70 66 65 153 82 138 73 143 109 254 242 42 153 208 166 135 31 43 110 39 224 29 173 223 201 133 220 86 84 66 148 24 23 160 165 223 202 236 62 229 186 164 142 14 12 144 43 43 169 182 47 4 125 128 33 11 97 76 165 206 243 92 204 214 1 17 25 139 177 41 229 156 167 182 219 46 13 236 143 162 118 41 7 208 214 237 0 194 153 92 7 58 204 190 203 202 131 107 226 206 177 187 183 193 77 242 31 159 219 64 158 120 191 157 64 154 56 152 195 78 228 72 187 184 143 146 172 213 41 111 80 116 43 248 49 224 18 63 78 184 104 176 114 23 199 112 126 3 44 245 221 130 30 56 163 248 150 113 122 238 125 67 221 62 214 203 185 23 37 151 206 132 15 18 110 199 138 130 148 242 2 86 148 252 93 97 140 255 160 173 189 197 113 124 67 192 80 109 16 188 3 51 4 167 31 90 225 3 1 105 218 103 161 175 237 206 133 164 27 127 150 78 15 181 64 4 216 207 4 234 147 36 179 176 201 52 232 40 87 222 211 175 109 249 144 62 232 111 161 251 36 88 172 157 18)
#f
())
#(30
"last byte of ps modified"
#vu8(49 50 51 52 48 48)
#vu8(43 55 57 56 37 209 250 248 156 234 98 177 38 35 123 13 104 7 187 79 181 117 107 154 158 32 207 73 186 109 238 70 2 237 171 205 116 211 183 48 174 197 144 236 81 132 205 56 24 73 47 76 138 255 222 8 36 255 66 81 86 75 21 65 14 173 154 90 39 230 143 71 173 252 175 232 181 151 49 17 240 0 188 102 49 232 28 69 74 79 238 111 250 34 221 47 1 242 134 128 239 116 250 208 195 8 11 191 121 88 203 110 72 134 240 26 66 33 15 26 159 75 193 250 110 138 113 171 227 154 65 241 241 192 158 252 190 166 161 10 187 12 30 34 117 77 32 161 42 56 165 178 104 150 226 186 159 248 133 177 122 223 101 202 104 17 80 112 251 209 201 12 5 145 120 224 68 196 94 36 40 230 112 131 235 101 229 72 16 84 249 203 76 35 179 15 180 55 19 57 106 64 159 44 152 220 113 131 73 135 136 101 239 32 15 159 245 220 45 154 4 119 161 46 195 18 205 197 101 181 231 91 159 223 29 229 63 230 248 177 118 52 129 122 58 202 131 224 42 2 94 220 3 83 36 115)
#f
())
#(31
"all bytes of ps changed to 0xff"
#vu8(49 50 51 52 48 48)
#vu8(151 94 132 177 21 108 236 63 54 205 169 151 85 80 109 208 187 205 66 161 17 110 155 134 50 116 96 13 245 27 230 113 3 176 196 75 106 90 136 100 19 106 74 37 164 125 142 246 26 217 29 97 13 105 110 1 88 65 56 80 103 151 98 5 21 20 80 4 106 191 164 249 81 79 116 135 242 25 26 28 185 57 222 88 33 143 69 112 182 26 107 166 246 214 234 75 42 192 157 183 156 65 107 247 115 111 230 113 253 17 198 100 115 50 206 74 110 38 159 183 174 50 9 128 248 245 24 99 86 38 0 244 187 84 58 209 41 82 237 169 34 113 193 76 181 86 21 15 234 188 65 72 230 210 138 44 133 141 154 78 132 171 152 95 164 22 254 97 25 252 36 22 89 19 154 151 131 240 28 196 104 52 239 53 172 92 33 91 179 116 188 55 32 174 225 154 191 36 149 91 122 11 162 212 134 134 26 152 113 187 170 103 2 221 40 9 249 157 190 162 158 41 33 40 107 93 95 127 213 253 197 148 194 149 47 154 57 0 63 227 188 14 35 191 112 38 173 169 25 142 174 201 199 221 38 122)
#f
())
#(32
"all bytes of ps changed to 0x80"
#vu8(49 50 51 52 48 48)
#vu8(110 35 97 202 229 245 215 227 236 182 180 96 15 26 39 219 16 178 185 181 154 29 98 13 199 49 75 204 206 241 11 197 42 13 208 171 127 220 38 186 182 30 207 117 217 43 222 18 172 145 88 247 233 172 110 140 7 49 164 113 75 187 171 50 53 247 82 65 55 177 111 39 38 168 126 54 11 130 249 216 36 81 18 189 50 48 135 195 78 148 160 155 215 94 164 90 43 144 76 53 68 162 9 143 83 103 222 198 87 247 231 24 69 87 237 78 178 227 189 176 31 220 201 216 232 235 32 148 133 212 99 66 242 32 130 118 188 166 49 167 84 100 236 27 143 58 211 77 238 221 11 141 151 166 2 147 12 134 63 117 119 127 38 184 50 78 13 103 252 177 218 178 234 85 104 70 249 56 179 26 123 177 216 96 196 215 55 255 69 214 181 149 97 150 58 3 104 242 166 72 191 223 129 193 71 190 29 107 191 1 20 55 233 139 104 85 116 119 176 49 20 245 3 39 87 143 17 25 108 208 23 183 254 234 34 235 148 126 187 213 198 8 4 53 181 233 160 26 81 96 6 127 88 113 29 143)
#f
())
#(33
"ps followed by 0"
#vu8(49 50 51 52 48 48)
#vu8(10 47 110 234 163 51 173 5 218 17 63 160 12 220 211 136 143 173 115 150 5 196 217 179 69 0 13 106 227 216 10 119 34 80 16 159 164 36 239 133 21 57 31 62 164 196 20 156 62 112 115 242 10 79 45 133 164 182 246 50 236 114 92 196 165 199 150 174 29 214 76 74 219 174 73 79 105 51 233 203 28 64 69 231 125 153 26 218 50 46 130 163 49 81 15 123 72 192 158 98 225 242 133 0 90 21 170 180 185 100 93 95 118 67 86 227 38 106 165 65 4 118 239 206 68 123 15 140 248 241 30 245 143 82 8 156 243 69 228 112 83 83 42 18 217 254 17 251 252 73 218 159 61 220 205 93 91 51 131 23 213 167 9 136 59 127 79 130 48 111 90 236 92 130 39 35 140 253 246 203 158 143 235 231 47 146 63 226 226 67 156 189 218 91 246 51 24 39 162 24 150 19 2 58 73 64 28 22 200 91 177 99 198 83 4 228 194 199 73 234 39 168 176 112 129 77 102 248 233 254 89 114 91 150 207 215 109 12 76 97 45 90 73 166 26 115 228 124 75 231 114 149 147 241 215 91)
#f
())
#(34
"ps followed by 0xff"
#vu8(49 50 51 52 48 48)
#vu8(116 27 92 111 232 221 43 175 165 3 31 11 174 5 123 124 107 91 192 210 196 242 96 223 36 73 194 187 217 71 178 204 6 255 70 174 103 175 115 121 93 208 93 118 190 225 95 75 38 114 144 207 165 141 187 249 178 159 153 195 101 228 132 18 65 178 46 19 93 171 212 7 0 214 169 44 241 70 190 117 29 190 143 126 133 190 250 234 156 51 113 44 246 43 224 195 215 111 106 81 79 239 19 161 186 111 206 108 103 136 136 16 2 47 76 22 139 37 23 163 1 45 231 98 255 16 32 85 4 237 39 184 14 191 173 237 18 189 26 187 37 119 251 98 11 215 12 241 174 136 106 184 16 20 104 150 215 66 142 132 244 139 160 181 247 230 126 22 148 17 191 32 125 203 67 192 225 133 239 130 241 187 220 67 26 112 209 3 87 119 120 189 202 180 36 239 63 97 159 61 228 170 73 236 46 72 252 64 221 68 249 15 214 252 165 13 2 241 162 115 82 96 84 138 1 165 104 199 54 157 98 153 157 48 93 195 205 21 220 236 242 166 65 124 213 180 194 106 197 21 94 190 232 229 119 247)
#f
())
#(35
"shifted salt"
#vu8(49 50 51 52 48 48)
#vu8(127 238 30 158 95 119 125 95 80 116 58 30 197 53 57 213 240 130 68 50 191 220 155 126 243 29 43 24 82 128 71 115 150 151 150 213 3 253 178 180 139 8 205 141 189 217 10 255 198 160 199 244 99 159 217 49 21 93 220 61 82 82 153 62 206 245 179 223 135 38 9 228 137 10 228 120 248 9 237 255 213 226 114 95 46 41 179 202 64 42 244 133 62 207 164 169 174 113 182 140 59 17 68 206 212 122 39 163 14 39 45 205 251 153 219 206 15 253 59 191 206 18 165 147 60 46 182 142 176 59 157 41 180 192 177 110 102 156 218 192 244 45 0 206 66 24 100 65 139 113 195 84 186 17 198 90 250 236 169 25 244 220 179 240 155 200 190 146 0 27 66 152 18 142 131 45 101 89 206 157 252 66 227 234 42 226 37 155 25 21 50 174 178 65 154 143 33 215 67 69 121 178 201 3 67 5 195 69 140 235 102 224 72 185 3 210 45 227 9 165 9 91 68 114 226 165 133 14 224 119 127 14 230 36 100 99 159 118 110 237 213 211 80 212 16 154 243 176 165 46 220 115 115 248 249 58)
#f
())
#(36
"including garbage"
#vu8(49 50 51 52 48 48)
#vu8(23 149 172 64 200 0 58 149 61 13 13 224 142 227 86 19 239 58 201 82 66 82 25 227 123 86 153 206 0 42 108 87 70 85 229 39 207 140 67 61 123 115 179 19 99 139 43 157 240 233 163 109 181 118 183 40 247 200 231 82 19 146 165 250 81 252 15 197 136 233 37 81 89 75 167 155 70 182 115 103 70 93 21 117 241 46 60 244 34 127 234 80 129 100 35 44 65 211 195 207 146 208 90 203 78 251 220 90 59 102 160 147 167 147 130 20 62 15 192 248 246 171 201 13 92 152 98 234 186 141 186 137 100 173 77 253 23 162 20 172 203 76 75 84 138 87 87 19 90 246 141 72 142 254 104 231 230 106 114 121 242 238 190 170 250 102 200 124 104 24 239 201 217 250 218 22 69 85 41 166 22 134 22 94 13 139 148 236 255 211 70 244 108 212 66 20 233 199 31 244 87 120 187 221 61 243 165 142 245 216 192 46 4 105 167 112 119 133 104 164 49 106 185 83 26 119 203 124 229 93 224 97 248 162 39 237 44 93 236 94 99 197 186 204 42 71 77 157 107 119 240 97 59 90 111 163)
#f
())
#(37
"bit 7 of masked_db not cleared"
#vu8(49 50 51 52 48 48)
#vu8(92 110 80 84 244 17 203 67 241 94 228 96 34 24 125 164 92 130 20 160 245 246 229 44 77 234 245 122 164 64 64 192 135 184 40 209 195 213 162 225 195 120 7 124 81 249 188 73 89 154 252 254 157 176 53 16 55 99 146 1 97 73 173 97 190 193 32 59 244 253 5 103 35 65 246 44 179 46 154 77 127 142 145 210 149 60 229 232 51 112 191 74 94 209 195 19 41 197 98 42 125 85 168 46 138 25 236 194 89 132 236 217 159 56 25 135 150 254 49 195 222 241 6 198 232 25 70 34 74 124 26 13 147 88 105 254 142 246 187 137 47 182 223 128 108 245 45 224 159 74 200 106 190 81 241 177 72 246 179 45 187 151 203 248 124 221 37 154 197 118 102 222 221 10 252 182 221 124 171 82 125 140 184 71 207 26 24 240 27 10 20 240 241 243 181 15 203 154 244 105 42 188 166 11 18 51 21 16 193 236 207 219 170 18 139 219 159 2 93 117 254 138 73 218 44 239 4 48 121 18 162 210 144 126 190 106 119 221 68 219 204 93 131 117 48 150 235 14 186 134 190 212 47 216 79 36)
#f
())
#(38
"first byte of masked_db changed to 0"
#vu8(49 50 51 52 48 48)
#vu8(121 40 197 135 125 187 22 199 97 209 94 89 151 81 33 89 186 178 148 252 29 28 199 58 88 101 248 72 64 243 105 214 188 71 80 75 186 132 50 0 58 79 28 188 252 233 125 238 19 118 96 233 115 229 24 31 126 129 248 151 250 96 121 65 161 29 149 171 35 12 140 42 254 171 37 38 197 217 6 89 117 147 148 139 126 150 119 130 61 177 60 18 6 44 86 208 184 244 188 162 131 220 144 163 150 44 252 152 8 158 9 205 199 145 229 202 96 118 202 142 110 11 115 29 133 237 95 75 227 142 215 152 231 11 67 127 30 236 75 181 183 10 143 191 53 243 192 95 15 147 243 65 103 236 102 103 131 160 128 98 194 35 13 18 249 210 145 236 180 229 35 189 126 144 211 248 210 149 213 114 63 193 189 53 137 34 7 66 63 32 225 201 37 194 112 241 232 182 229 118 184 114 223 71 93 86 27 93 199 117 112 91 205 171 162 21 243 196 238 156 37 113 228 27 154 65 255 35 246 1 60 2 32 39 85 182 5 187 162 29 43 198 252 172 108 254 228 81 130 193 31 72 83 219 38 181)
#f
())
#(39
"last byte in em modified"
#vu8(49 50 51 52 48 48)
#vu8(9 252 98 137 11 38 212 89 86 175 170 165 125 99 213 78 32 92 31 91 98 4 136 155 248 62 90 216 137 95 237 173 234 30 184 94 78 73 102 61 36 96 93 76 74 47 127 198 133 14 128 103 144 78 112 1 85 92 11 171 89 93 59 195 109 182 47 54 150 41 201 83 68 103 64 110 234 224 79 214 59 241 100 199 125 119 206 123 91 192 31 30 207 164 229 208 0 201 74 79 55 196 248 241 111 208 197 170 68 209 226 246 167 54 27 73 123 206 195 29 108 251 235 92 128 93 92 181 50 26 13 232 242 200 224 251 158 14 25 183 66 30 177 164 50 179 22 208 235 46 114 213 201 56 2 143 233 143 88 71 185 12 135 189 34 187 165 222 129 255 160 201 177 122 232 106 50 188 166 67 48 7 171 68 86 81 184 217 65 88 178 251 169 33 74 98 160 246 146 252 18 211 254 248 247 134 121 96 19 148 148 59 191 72 19 174 86 17 12 236 161 146 155 254 34 90 84 57 214 162 229 175 173 80 51 47 173 223 67 69 89 160 48 58 45 223 174 239 71 26 151 78 56 243 158 196)
#f
())
#(40
"last byte in em modified"
#vu8(49 50 51 52 48 48)
#vu8(10 24 200 191 190 210 176 253 116 224 110 45 223 181 236 133 25 141 206 217 84 111 139 198 248 12 159 140 165 42 13 21 58 96 156 219 61 100 93 125 124 185 205 118 14 159 231 102 18 126 181 194 206 5 204 103 141 116 157 5 250 55 223 6 170 236 21 199 119 217 49 136 239 86 200 73 156 80 181 218 189 84 59 20 170 201 253 140 9 221 201 111 128 192 226 116 131 52 161 140 75 16 213 189 26 67 194 19 157 71 117 28 51 201 70 163 117 62 19 96 168 29 31 103 113 178 65 25 85 90 51 143 46 130 64 105 233 70 73 125 155 144 134 46 243 179 156 5 186 103 77 234 169 93 211 41 26 224 92 190 212 244 184 104 175 237 46 101 92 223 204 54 192 167 3 165 86 26 132 109 230 106 122 230 118 52 164 91 198 14 150 108 129 182 52 62 203 218 70 204 117 146 104 126 116 160 62 88 99 223 14 183 251 77 162 238 195 137 82 88 31 162 234 72 198 36 71 137 49 145 181 98 177 144 92 166 13 249 135 10 7 74 58 97 1 145 26 49 200 249 60 59 231 167 226 29)
#f
())
#(41
"last byte in em modified"
#vu8(49 50 51 52 48 48)
#vu8(99 192 3 185 187 228 38 123 216 62 249 240 28 11 222 9 67 180 38 134 253 246 209 220 111 243 238 233 106 208 235 186 33 226 194 17 157 60 232 113 10 211 105 115 92 169 242 196 254 254 255 219 216 147 55 54 104 41 113 180 171 98 11 119 83 251 123 134 103 5 203 9 238 34 75 197 178 215 120 213 136 54 173 49 211 195 236 252 99 177 222 160 206 71 32 52 229 8 240 87 250 208 60 81 94 235 11 98 121 3 135 242 234 216 239 197 66 26 153 46 61 113 165 61 180 137 128 218 222 207 182 216 55 197 1 176 140 121 30 36 70 94 44 180 41 114 211 69 11 230 209 86 31 177 196 22 243 6 130 12 181 21 108 234 68 201 101 202 100 226 148 24 83 113 137 116 200 176 231 109 197 246 224 245 128 207 82 167 225 102 237 182 212 29 121 166 145 184 246 128 122 137 117 46 133 46 212 226 7 176 120 243 200 189 253 241 106 105 20 185 112 250 121 137 248 26 87 63 177 241 165 39 51 199 33 34 66 221 103 63 244 133 113 165 104 113 58 172 9 73 73 161 44 154 117 94)
#f
())
#(42
"signature is 0"
#vu8(49 50 51 52 48 48)
#vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#f
())
#(43
"signature is 1"
#vu8(49 50 51 52 48 48)
#vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1)
#f
())
#(44
"signature is n-1"
#vu8(49 50 51 52 48 48)
#vu8(163 143 188 243 78 239 24 16 203 42 226 31 239 30 154 30 3 127 125 37 212 62 139 79 5 30 167 76 54 123 221 178 50 122 123 204 197 51 79 230 16 247 169 133 94 43 118 193 233 113 89 112 194 44 39 70 22 253 148 96 215 39 175 233 161 73 194 59 107 151 48 193 60 79 98 19 224 193 18 164 157 178 229 89 147 182 12 82 14 183 48 66 199 160 177 191 228 226 123 17 164 199 57 80 87 35 82 51 253 138 179 137 138 213 106 120 147 7 123 188 68 20 180 8 154 89 76 156 190 197 222 202 9 46 251 77 132 217 119 185 243 127 217 130 52 29 169 99 162 10 246 128 255 74 119 78 200 90 16 74 104 70 72 176 169 11 108 196 247 212 128 141 182 102 235 171 128 138 33 2 15 140 0 92 103 147 241 150 24 120 17 147 85 38 202 241 182 206 228 122 12 20 224 130 63 135 215 170 130 233 245 166 53 202 17 102 134 210 218 113 156 218 38 156 57 216 99 87 28 96 110 92 229 51 66 84 228 150 72 252 252 245 2 161 50 28 192 113 241 0 13 86 39 35 21 110)
#f
())
#(45
"signature is n"
#vu8(49 50 51 52 48 48)
#vu8(163 143 188 243 78 239 24 16 203 42 226 31 239 30 154 30 3 127 125 37 212 62 139 79 5 30 167 76 54 123 221 178 50 122 123 204 197 51 79 230 16 247 169 133 94 43 118 193 233 113 89 112 194 44 39 70 22 253 148 96 215 39 175 233 161 73 194 59 107 151 48 193 60 79 98 19 224 193 18 164 157 178 229 89 147 182 12 82 14 183 48 66 199 160 177 191 228 226 123 17 164 199 57 80 87 35 82 51 253 138 179 137 138 213 106 120 147 7 123 188 68 20 180 8 154 89 76 156 190 197 222 202 9 46 251 77 132 217 119 185 243 127 217 130 52 29 169 99 162 10 246 128 255 74 119 78 200 90 16 74 104 70 72 176 169 11 108 196 247 212 128 141 182 102 235 171 128 138 33 2 15 140 0 92 103 147 241 150 24 120 17 147 85 38 202 241 182 206 228 122 12 20 224 130 63 135 215 170 130 233 245 166 53 202 17 102 134 210 218 113 156 218 38 156 57 216 99 87 28 96 110 92 229 51 66 84 228 150 72 252 252 245 2 161 50 28 192 113 241 0 13 86 39 35 21 111)
#f
())
#(46
"prepending 0's to signature"
#vu8(49 50 51 52 48 48)
#vu8(0 0 105 248 249 9 198 244 207 78 217 153 80 204 194 133 21 88 138 154 120 28 37 89 222 142 44 232 176 167 63 244 35 190 71 91 88 217 29 110 181 122 112 144 38 4 97 95 217 250 178 230 188 166 181 253 48 46 176 44 95 75 110 53 167 205 17 50 5 134 246 41 88 52 181 93 76 79 9 196 169 123 158 242 45 35 33 168 244 238 241 163 144 74 33 101 124 52 103 63 251 114 216 60 160 68 228 45 114 134 194 104 19 47 172 78 60 51 118 212 178 112 179 221 162 191 224 226 190 186 45 134 112 167 194 36 187 123 192 39 19 239 190 239 118 125 80 14 234 78 62 255 76 145 88 8 156 95 29 150 245 193 10 22 84 131 125 16 232 77 35 188 132 22 107 20 200 82 169 175 12 226 15 76 248 166 59 123 90 219 119 90 174 13 210 250 151 205 187 88 141 54 231 15 171 169 73 228 85 65 168 59 180 233 234 53 117 38 79 143 29 130 25 83 208 175 1 219 42 22 172 64 18 238 151 185 241 202 235 174 206 90 177 201 68 85 155 12 148 65 74 236 173 214 102 107 25 164)
#f
())
#(47
"appending 0's to signature"
#vu8(49 50 51 52 48 48)
#vu8(105 248 249 9 198 244 207 78 217 153 80 204 194 133 21 88 138 154 120 28 37 89 222 142 44 232 176 167 63 244 35 190 71 91 88 217 29 110 181 122 112 144 38 4 97 95 217 250 178 230 188 166 181 253 48 46 176 44 95 75 110 53 167 205 17 50 5 134 246 41 88 52 181 93 76 79 9 196 169 123 158 242 45 35 33 168 244 238 241 163 144 74 33 101 124 52 103 63 251 114 216 60 160 68 228 45 114 134 194 104 19 47 172 78 60 51 118 212 178 112 179 221 162 191 224 226 190 186 45 134 112 167 194 36 187 123 192 39 19 239 190 239 118 125 80 14 234 78 62 255 76 145 88 8 156 95 29 150 245 193 10 22 84 131 125 16 232 77 35 188 132 22 107 20 200 82 169 175 12 226 15 76 248 166 59 123 90 219 119 90 174 13 210 250 151 205 187 88 141 54 231 15 171 169 73 228 85 65 168 59 180 233 234 53 117 38 79 143 29 130 25 83 208 175 1 219 42 22 172 64 18 238 151 185 241 202 235 174 206 90 177 201 68 85 155 12 148 65 74 236 173 214 102 107 25 164 0 0)
#f
())
#(48
"truncated signature"
#vu8(49 50 51 52 48 48)
#vu8(105 248 249 9 198 244 207 78 217 153 80 204 194 133 21 88 138 154 120 28 37 89 222 142 44 232 176 167 63 244 35 190 71 91 88 217 29 110 181 122 112 144 38 4 97 95 217 250 178 230 188 166 181 253 48 46 176 44 95 75 110 53 167 205 17 50 5 134 246 41 88 52 181 93 76 79 9 196 169 123 158 242 45 35 33 168 244 238 241 163 144 74 33 101 124 52 103 63 251 114 216 60 160 68 228 45 114 134 194 104 19 47 172 78 60 51 118 212 178 112 179 221 162 191 224 226 190 186 45 134 112 167 194 36 187 123 192 39 19 239 190 239 118 125 80 14 234 78 62 255 76 145 88 8 156 95 29 150 245 193 10 22 84 131 125 16 232 77 35 188 132 22 107 20 200 82 169 175 12 226 15 76 248 166 59 123 90 219 119 90 174 13 210 250 151 205 187 88 141 54 231 15 171 169 73 228 85 65 168 59 180 233 234 53 117 38 79 143 29 130 25 83 208 175 1 219 42 22 172 64 18 238 151 185 241 202 235 174 206 90 177 201 68 85 155 12 148 65 74 236 173 214 102 107)
#f
())
#(49
"empty signature"
#vu8(49 50 51 52 48 48)
#vu8()
#f
())
#(50
"PKCS #1 v1.5 signature"
#vu8(49 50 51 52 48 48)
#vu8(127 182 78 241 13 233 107 52 86 250 10 245 69 114 89 94 69 50 134 18 218 210 6 65 25 203 198 114 189 124 110 185 144 40 237 121 165 248 19 120 206 141 230 73 149 161 180 76 63 107 14 245 208 50 76 227 212 130 128 89 145 38 226 59 167 191 97 203 40 79 82 189 96 118 151 48 201 215 170 189 142 121 113 231 35 27 88 139 205 136 17 153 76 158 87 167 61 66 75 15 191 122 137 177 204 226 34 83 175 98 242 150 53 153 62 244 210 205 12 239 192 26 66 28 201 149 7 161 228 224 117 47 196 103 203 192 85 234 102 121 186 0 167 24 176 211 155 141 228 83 8 147 162 178 137 204 8 57 96 69 25 138 138 186 140 101 157 229 99 32 255 42 176 175 240 194 170 15 88 163 219 231 242 171 21 68 195 70 114 219 16 190 248 57 99 138 146 181 78 120 150 138 15 158 167 127 160 55 72 244 0 71 60 213 169 3 180 75 19 65 53 221 175 237 23 79 201 44 74 232 183 172 50 39 48 214 209 238 15 119 112 98 108 235 249 15 15 20 74 63 102 83 83 48 186 79)
#f
())))
| null | https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/8d3be98032133507b87d6c0466d60f982ebf9b15/ext/crypto/tests/testvectors/signature/rsa_pss_2048_sha512_256_mgf1_28_test.scm | scheme | (test-signature/testvector
"rsa_pss_2048_sha512_256_mgf1_28_test"
:algorithm
"RSASSA-PSS"
:digest
"SHA-512/224"
:public-key
#vu8(48 130 1 34 48 13 6 9 42 134 72 134 247 13 1 1 1 5 0 3 130 1 15 0 48 130 1 10 2 130 1 1 0 163 143 188 243 78 239 24 16 203 42 226 31 239 30 154 30 3 127 125 37 212 62 139 79 5 30 167 76 54 123 221 178 50 122 123 204 197 51 79 230 16 247 169 133 94 43 118 193 233 113 89 112 194 44 39 70 22 253 148 96 215 39 175 233 161 73 194 59 107 151 48 193 60 79 98 19 224 193 18 164 157 178 229 89 147 182 12 82 14 183 48 66 199 160 177 191 228 226 123 17 164 199 57 80 87 35 82 51 253 138 179 137 138 213 106 120 147 7 123 188 68 20 180 8 154 89 76 156 190 197 222 202 9 46 251 77 132 217 119 185 243 127 217 130 52 29 169 99 162 10 246 128 255 74 119 78 200 90 16 74 104 70 72 176 169 11 108 196 247 212 128 141 182 102 235 171 128 138 33 2 15 140 0 92 103 147 241 150 24 120 17 147 85 38 202 241 182 206 228 122 12 20 224 130 63 135 215 170 130 233 245 166 53 202 17 102 134 210 218 113 156 218 38 156 57 216 99 87 28 96 110 92 229 51 66 84 228 150 72 252 252 245 2 161 50 28 192 113 241 0 13 86 39 35 21 111 2 3 1 0 1)
:mgf
"MGF1"
:mgf-digest
"SHA-512/224"
:salt-length
28
:der-encode
#t
:tests
'(#(1
""
#vu8()
#vu8(95 248 66 38 168 12 143 145 84 165 0 131 254 4 172 31 229 122 131 122 21 228 113 185 188 97 250 133 43 46 67 182 243 65 140 162 167 19 0 55 215 73 85 119 142 70 63 36 182 50 213 58 246 221 20 26 45 145 223 171 20 4 155 119 98 235 192 172 251 164 89 205 140 157 221 41 167 176 126 151 208 109 184 29 73 190 185 237 12 201 186 109 192 96 151 136 246 41 30 55 83 144 124 138 193 20 89 184 58 28 10 10 205 62 247 143 154 198 132 152 215 132 9 161 243 181 78 246 80 241 8 214 14 114 103 53 71 135 220 213 255 12 54 72 195 173 58 23 150 222 162 50 189 155 142 129 103 38 16 159 178 229 116 152 53 206 179 115 117 248 195 216 214 35 75 88 40 176 105 107 1 225 71 159 227 137 53 210 125 186 54 84 222 56 209 254 219 191 194 14 102 168 155 64 129 17 180 253 57 235 69 29 171 71 42 102 252 142 59 49 188 72 123 238 62 251 129 197 13 217 48 126 103 78 157 200 164 117 19 173 17 155 225 221 84 23 65 193 252 232 27 99 141 31 63 193)
#t
())
#(2
""
#vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#vu8(120 111 32 220 194 15 27 132 241 93 221 176 60 187 134 29 155 203 180 27 48 63 168 238 152 191 230 201 239 138 245 106 16 71 161 254 32 50 51 43 192 48 156 164 166 145 63 138 202 97 120 36 165 87 41 48 26 13 185 215 4 20 73 92 254 73 78 220 210 122 123 83 56 162 122 43 33 216 182 117 241 188 144 42 115 159 17 41 198 97 146 125 16 83 112 69 182 156 69 4 103 123 115 239 236 85 31 199 105 6 39 181 199 42 113 14 195 206 174 73 18 79 149 242 141 128 45 164 193 188 137 77 239 143 246 74 61 149 171 86 220 181 76 26 160 97 192 213 240 92 165 237 138 120 140 206 171 225 165 66 174 125 65 75 154 169 122 178 18 158 136 67 140 228 143 165 199 7 220 248 40 9 170 85 56 187 123 217 114 12 37 29 193 123 1 216 113 166 82 123 195 116 79 112 220 157 19 15 90 206 183 178 172 215 12 237 181 1 203 214 123 120 65 113 59 147 167 9 75 182 15 50 38 145 242 86 65 194 178 43 72 128 92 17 176 118 102 246 38 114 199 38 174 168 211 37)
#t
())
#(3
""
#vu8(84 101 115 116)
#vu8(107 111 140 172 206 14 80 66 158 94 96 235 21 173 71 70 236 173 65 211 187 185 115 165 108 236 31 120 48 35 224 240 4 165 194 109 223 73 76 255 202 41 213 208 237 209 169 197 47 24 29 105 191 115 69 12 97 234 158 160 16 43 180 18 36 77 91 79 246 226 194 22 190 118 244 82 56 23 8 180 95 14 128 174 182 57 26 74 213 211 137 21 95 181 229 203 56 230 162 227 3 224 188 99 245 45 39 131 11 253 30 56 7 190 237 197 217 73 91 125 92 253 17 61 192 198 225 188 23 8 93 234 151 187 202 95 13 70 43 99 190 197 166 100 235 92 31 245 135 69 144 56 245 190 124 220 76 220 179 32 215 104 106 11 151 255 253 35 65 234 242 134 233 0 23 111 133 20 23 16 102 108 107 207 58 121 127 158 130 130 167 145 8 37 215 191 77 41 48 220 32 138 172 54 102 112 112 27 88 59 132 129 126 99 105 162 24 48 84 184 148 229 5 220 236 245 64 91 33 16 249 107 107 139 36 69 66 164 102 191 15 15 113 65 205 222 238 127 6 19 55 144 40 209 165 188)
#t
())
#(4
""
#vu8(49 50 51 52 48 48)
#vu8(105 248 249 9 198 244 207 78 217 153 80 204 194 133 21 88 138 154 120 28 37 89 222 142 44 232 176 167 63 244 35 190 71 91 88 217 29 110 181 122 112 144 38 4 97 95 217 250 178 230 188 166 181 253 48 46 176 44 95 75 110 53 167 205 17 50 5 134 246 41 88 52 181 93 76 79 9 196 169 123 158 242 45 35 33 168 244 238 241 163 144 74 33 101 124 52 103 63 251 114 216 60 160 68 228 45 114 134 194 104 19 47 172 78 60 51 118 212 178 112 179 221 162 191 224 226 190 186 45 134 112 167 194 36 187 123 192 39 19 239 190 239 118 125 80 14 234 78 62 255 76 145 88 8 156 95 29 150 245 193 10 22 84 131 125 16 232 77 35 188 132 22 107 20 200 82 169 175 12 226 15 76 248 166 59 123 90 219 119 90 174 13 210 250 151 205 187 88 141 54 231 15 171 169 73 228 85 65 168 59 180 233 234 53 117 38 79 143 29 130 25 83 208 175 1 219 42 22 172 64 18 238 151 185 241 202 235 174 206 90 177 201 68 85 155 12 148 65 74 236 173 214 102 107 25 164)
#t
())
#(5
""
#vu8(77 101 115 115 97 103 101)
#vu8(117 127 78 235 219 3 104 55 132 68 5 131 25 244 124 116 214 165 77 65 113 16 55 15 218 208 50 173 43 154 198 23 65 61 67 177 34 114 223 210 0 245 246 153 68 169 204 175 246 80 170 197 236 85 60 117 119 249 171 75 43 37 164 191 134 151 141 0 191 18 94 153 218 140 3 241 239 142 162 35 207 28 75 222 90 102 7 239 98 37 58 21 81 72 52 185 2 151 1 92 194 72 175 39 40 68 56 235 195 203 65 102 39 178 80 84 207 113 154 159 213 159 21 114 187 240 13 199 179 109 48 61 218 108 227 150 249 252 141 199 129 18 133 77 26 104 195 156 251 50 183 197 111 12 67 170 91 134 219 225 150 55 164 243 171 86 132 75 154 228 66 10 85 175 180 84 147 31 141 92 186 88 88 161 252 235 239 248 223 33 162 123 51 73 103 94 0 144 233 186 185 191 215 86 42 180 189 86 151 116 250 218 69 236 195 143 194 206 192 24 155 202 222 137 139 141 232 108 243 144 129 189 217 95 56 217 80 47 32 177 41 180 217 212 101 193 20 58 134 157 31 172 88 216 39 199)
#t
())
#(6
""
#vu8(97)
#vu8(55 190 58 193 227 250 27 240 88 0 226 238 150 138 101 214 88 14 101 60 220 104 117 239 189 105 8 129 83 54 119 122 29 143 179 163 39 58 21 210 190 152 139 177 22 23 153 100 23 4 246 18 28 48 61 98 169 87 104 155 185 2 62 166 101 86 31 95 43 1 51 46 247 20 41 213 101 152 123 162 217 190 130 111 1 225 211 220 66 125 135 245 20 236 167 74 146 151 116 19 70 115 195 174 171 36 230 141 36 102 27 11 128 87 125 163 32 3 13 98 211 199 199 225 163 83 0 189 117 205 18 13 189 172 29 42 169 123 249 4 255 158 247 74 245 50 55 195 218 20 189 213 112 34 246 169 184 252 147 171 72 34 123 115 84 104 189 132 96 197 9 205 217 39 121 170 13 198 242 115 203 228 91 188 215 60 166 211 41 102 203 51 200 174 97 116 63 24 21 125 49 198 59 144 90 200 106 20 165 232 34 205 206 201 43 125 66 103 198 248 201 18 227 96 221 152 254 114 73 72 179 154 181 70 178 64 61 175 116 11 120 233 85 226 13 55 254 228 80 65 41 254 77 74 125 196)
#t
())
#(7
""
#vu8(224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255)
#vu8(56 42 106 0 192 44 147 153 31 78 117 202 234 241 153 233 230 6 158 65 76 182 23 145 98 191 71 203 210 236 15 89 242 20 255 17 32 121 69 181 98 30 41 189 29 157 11 110 229 117 59 164 125 237 123 37 177 204 240 221 11 110 243 147 2 177 112 86 92 85 243 126 99 254 252 126 215 153 171 199 60 231 90 176 86 173 31 28 248 209 193 176 66 5 206 80 32 186 156 47 189 251 166 18 134 125 213 237 132 72 237 121 51 31 243 31 25 234 123 42 78 249 201 27 234 158 56 105 121 96 54 58 176 85 22 94 75 104 221 47 85 28 65 2 228 131 174 68 138 124 115 32 129 12 40 73 161 87 242 249 20 24 180 242 130 213 150 179 81 248 237 122 93 77 176 112 25 102 142 210 123 112 208 224 46 215 14 150 37 151 196 249 94 46 11 200 161 41 78 32 166 155 107 115 155 185 112 75 133 87 190 42 167 181 48 215 9 86 60 209 207 150 107 232 240 108 131 18 18 73 211 73 152 193 236 184 111 115 245 179 122 196 147 21 244 223 219 214 158 78 11 29 195 42 167 149)
#t
())
#(8
"first byte of m_hash modified"
#vu8(49 50 51 52 48 48)
#vu8(1 173 5 50 240 177 17 231 235 182 170 142 14 42 125 40 119 0 128 98 26 7 57 203 194 107 236 30 14 108 214 212 116 176 247 74 29 200 45 50 3 29 80 59 218 98 235 210 220 166 205 42 40 130 28 60 37 121 199 32 169 217 175 29 162 81 43 31 187 113 250 116 182 82 98 219 235 28 111 9 96 19 136 167 33 80 21 50 242 179 127 68 25 135 12 149 176 89 80 7 242 232 248 220 113 130 183 199 27 39 247 230 235 184 78 115 108 16 126 192 81 64 178 87 211 23 194 98 173 4 66 36 32 137 96 198 243 29 113 82 101 209 148 7 100 151 212 82 25 86 247 164 140 252 9 66 139 189 203 79 197 58 216 190 17 83 105 136 115 243 96 237 9 201 254 16 211 185 213 235 45 250 15 234 199 74 118 75 224 68 177 204 93 94 123 103 68 69 95 163 136 156 98 89 8 10 158 198 114 160 23 201 229 179 122 232 124 174 133 211 219 113 248 23 133 227 68 224 18 85 172 236 141 121 190 48 141 172 174 156 49 170 144 8 48 139 67 18 111 114 54 241 4 245 67 194)
#f
())
#(9
"first byte of m_hash modified"
#vu8(49 50 51 52 48 48)
#vu8(13 110 126 116 138 165 55 163 9 220 59 56 156 250 176 176 180 145 198 243 225 172 177 177 148 81 65 54 128 232 15 195 217 138 28 51 170 177 1 133 224 202 163 95 183 135 7 247 181 223 83 218 83 78 168 140 6 67 235 45 140 169 212 32 66 60 223 17 72 161 117 121 204 107 36 252 249 255 145 7 174 232 197 196 33 157 16 105 180 39 48 228 112 22 93 112 119 91 113 96 223 34 57 188 31 27 174 28 247 232 140 134 169 107 68 171 164 152 131 72 58 56 181 72 20 213 186 144 84 11 193 103 199 114 242 254 127 197 136 220 120 152 209 191 157 232 99 194 145 143 36 104 81 79 8 57 54 151 192 29 246 180 201 195 68 129 83 241 162 34 147 106 255 18 61 214 76 24 166 2 31 187 142 227 50 39 82 159 193 148 40 41 37 226 164 97 86 142 116 241 77 7 43 253 17 73 177 9 178 169 175 145 231 203 244 61 255 187 186 94 21 130 24 0 95 132 46 17 134 4 179 141 210 58 10 181 231 163 236 69 36 250 236 20 175 241 157 136 99 56 210 217 75 25 239 242)
#f
())
#(10
"last byte of m_hash modified"
#vu8(49 50 51 52 48 48)
#vu8(158 242 44 46 173 169 53 9 200 168 200 214 146 213 249 188 195 253 76 138 17 74 162 242 96 165 69 160 158 117 81 35 33 211 215 126 83 97 77 146 139 113 61 150 47 38 23 161 50 5 4 20 81 212 121 208 227 159 233 18 224 152 192 149 56 106 237 33 166 6 220 130 240 5 61 52 89 94 81 184 35 38 40 203 54 113 51 239 15 169 143 79 173 228 180 32 166 56 60 124 10 131 33 184 86 10 192 235 93 57 123 238 223 227 11 76 74 171 88 254 35 16 161 142 242 144 90 157 90 101 189 95 129 158 57 43 218 193 103 166 212 51 35 227 97 30 215 171 246 68 92 240 136 171 17 243 199 57 120 30 47 122 3 31 215 128 178 2 118 126 51 192 233 145 177 26 10 238 132 3 151 251 140 229 120 182 81 59 243 9 23 145 46 178 160 106 193 48 9 8 115 79 248 2 186 14 54 70 89 63 244 249 42 97 205 46 25 50 31 240 103 46 42 253 144 45 238 19 190 246 123 25 125 254 26 196 228 140 225 120 5 234 103 165 207 60 58 28 7 236 173 254 113 10 150 52)
#f
())
#(11
"last byte of m_hash modified"
#vu8(49 50 51 52 48 48)
#vu8(136 254 107 5 191 29 184 41 7 83 226 26 112 38 102 91 18 34 27 167 151 98 198 105 161 145 16 192 34 33 233 1 56 173 189 208 20 126 82 230 159 196 129 121 32 131 76 158 79 50 215 147 45 117 151 114 125 139 30 139 168 141 87 146 204 12 122 74 153 38 28 139 244 71 229 105 253 29 17 242 123 84 65 185 133 252 91 85 19 74 63 63 16 229 119 74 198 196 38 197 90 8 25 71 184 155 83 126 238 12 125 42 226 243 234 104 186 79 29 136 132 83 158 45 106 38 198 219 19 37 4 57 231 137 101 187 241 48 238 79 242 161 139 66 63 233 101 149 234 255 81 14 127 140 32 144 180 205 65 139 183 42 224 219 252 200 204 174 45 150 128 10 109 163 7 130 179 57 224 229 223 241 141 240 204 1 203 94 207 120 167 227 43 216 17 186 221 171 216 41 121 184 249 235 187 194 184 183 50 34 102 15 48 181 202 18 66 49 199 151 246 35 159 181 207 60 94 62 106 233 235 77 158 102 179 76 91 127 127 172 56 81 6 15 192 157 91 13 234 115 32 171 243 246 112 117)
#f
())
#(12
"all bits in m_hash flipped"
#vu8(49 50 51 52 48 48)
#vu8(77 29 15 245 228 77 42 10 121 78 249 228 248 225 56 64 72 36 215 218 51 186 41 28 105 84 160 97 188 208 130 125 208 36 52 68 47 109 56 221 157 162 234 130 104 195 175 17 187 241 188 25 24 55 182 76 219 239 11 196 219 54 1 229 190 193 207 183 51 33 71 74 33 236 136 228 62 18 166 221 113 31 31 44 202 68 1 60 3 38 23 57 53 113 174 28 30 30 26 89 92 221 217 34 20 207 140 232 211 57 35 151 186 104 77 176 227 27 208 154 200 229 137 181 242 179 235 246 162 211 64 58 232 215 239 123 45 14 28 53 253 73 178 238 252 137 110 250 51 109 248 218 66 16 83 5 235 211 152 202 139 194 206 7 115 50 96 229 8 113 255 214 204 176 58 161 159 165 253 135 228 154 152 50 106 183 138 199 174 153 241 41 22 102 152 33 55 166 63 229 70 195 243 77 85 12 253 207 77 250 116 174 80 231 130 47 185 206 197 20 77 138 250 190 212 74 237 97 195 169 142 132 163 218 125 59 118 121 158 30 192 201 54 174 193 120 212 113 225 161 99 135 174 66 200 121)
#f
())
#(13
"s_len changed to 0"
#vu8(49 50 51 52 48 48)
#vu8(49 158 118 253 64 248 249 113 192 97 133 135 77 97 81 44 40 20 1 158 47 92 104 248 170 99 122 174 189 25 232 223 56 250 243 53 83 52 136 112 194 232 181 72 48 174 61 252 183 19 86 167 62 54 159 230 45 91 185 223 128 205 151 96 164 27 178 154 100 184 110 95 92 12 186 113 240 29 218 53 148 3 102 168 244 149 53 205 248 244 150 202 243 72 228 1 9 101 207 152 228 206 237 147 147 251 97 210 37 46 209 113 102 130 183 144 84 162 221 214 195 21 212 120 197 34 167 206 2 181 76 90 146 23 31 11 126 43 189 243 87 20 95 131 10 198 242 58 166 32 193 196 48 152 232 48 19 76 12 28 170 126 66 180 151 208 75 199 44 73 19 138 205 107 80 229 216 47 113 227 112 250 220 246 4 179 218 24 178 166 133 221 153 236 216 224 14 229 141 93 238 229 36 91 158 36 125 10 200 11 59 202 136 72 96 209 195 26 103 125 72 26 0 188 5 249 214 206 61 23 233 8 186 199 71 137 81 38 230 140 141 89 168 44 195 223 153 86 162 75 119 190 110 42 211 155)
#f
())
#(14
"s_len changed to 20"
#vu8(49 50 51 52 48 48)
#vu8(113 36 44 73 12 201 119 52 209 130 65 253 196 38 33 123 140 125 224 137 193 128 116 157 100 209 103 227 250 150 201 54 5 65 211 214 201 246 52 134 211 151 83 157 142 129 255 128 99 207 21 225 56 38 251 148 97 140 99 134 32 247 143 168 27 33 166 60 26 162 32 208 174 26 35 92 227 52 89 42 13 139 237 110 52 104 39 12 195 251 40 158 87 255 243 183 70 53 29 78 157 65 227 52 87 141 26 115 48 250 156 235 71 41 143 86 56 167 134 249 15 127 247 121 247 164 98 105 19 136 182 10 82 206 207 8 183 161 3 143 21 77 143 117 180 214 102 105 11 125 11 143 142 206 238 12 93 139 96 123 183 192 185 98 112 219 160 196 181 229 25 153 253 237 94 109 229 9 90 114 212 91 32 148 92 71 174 190 113 126 141 153 86 132 88 43 9 152 131 67 31 78 215 59 115 84 157 65 81 142 97 214 220 118 217 87 205 13 137 138 124 181 81 251 210 166 91 101 11 182 51 231 67 245 169 113 182 195 181 99 127 235 160 117 184 152 133 179 98 167 224 240 218 59 158 227)
#f
())
#(15
"s_len changed to 32"
#vu8(49 50 51 52 48 48)
#vu8(146 88 227 227 222 255 239 192 250 64 109 252 28 98 197 129 168 39 60 172 185 52 35 102 219 156 156 41 132 198 208 8 71 49 49 213 166 167 142 192 217 28 253 32 211 1 24 26 134 195 52 170 82 205 243 101 56 68 67 150 56 68 239 8 90 86 32 187 33 129 89 120 2 181 223 250 113 179 64 132 96 122 39 252 221 127 117 16 238 193 57 89 209 57 255 20 18 194 138 201 253 220 51 174 55 115 60 118 125 113 190 110 194 3 79 162 205 40 164 24 220 64 202 179 208 47 36 35 185 209 55 241 29 103 7 182 127 17 211 9 81 225 16 199 197 197 79 172 176 208 105 240 157 84 69 109 189 255 42 215 170 197 188 88 77 73 132 38 182 136 141 69 169 228 207 30 122 32 172 18 175 59 49 157 73 226 113 255 232 26 239 185 160 234 25 55 221 126 89 193 204 182 193 137 161 52 136 37 101 92 113 118 238 238 250 243 95 157 224 227 57 24 124 217 156 231 224 133 76 144 7 94 91 159 194 167 196 112 23 198 221 76 73 192 212 226 71 79 236 150 227 195 170 138 2 63)
#f
())
#(16
"salt is all 0"
#vu8(49 50 51 52 48 48)
#vu8(74 159 184 209 160 79 253 54 163 78 250 69 5 249 149 0 219 119 101 115 112 181 187 133 71 166 66 132 119 184 9 149 52 234 202 97 29 231 87 183 3 178 80 109 70 63 82 194 107 189 159 246 187 127 250 252 62 163 142 134 254 253 147 98 136 133 73 116 205 77 184 79 216 163 188 49 193 39 101 205 165 94 118 238 56 78 222 130 49 124 205 120 2 134 181 108 31 145 110 84 95 115 94 67 39 250 240 91 158 196 213 9 80 148 173 177 158 85 250 103 3 185 34 119 83 63 233 188 185 58 0 82 213 223 237 73 48 21 23 178 56 216 225 37 226 222 228 131 228 210 131 155 138 127 168 141 15 222 224 22 76 8 174 134 107 137 204 127 227 189 73 74 45 42 60 46 55 7 175 37 124 199 186 229 60 217 59 134 161 157 204 115 152 80 128 192 53 179 68 174 79 232 146 71 165 22 92 231 189 193 177 81 61 197 188 105 60 73 122 3 255 118 31 137 145 229 36 221 119 155 223 47 121 108 124 67 164 230 244 83 117 46 172 16 151 220 60 10 146 131 14 1 188 165 98 88)
#t
())
#(17
"salt is all 1"
#vu8(49 50 51 52 48 48)
#vu8(71 69 147 234 71 1 62 98 183 21 102 4 194 97 148 59 59 110 186 37 233 14 51 156 166 101 154 5 75 205 10 6 193 0 84 81 32 240 163 45 97 76 66 141 226 138 240 5 248 103 218 116 228 76 45 254 208 231 145 214 253 201 180 43 92 197 47 169 134 144 240 83 247 236 20 12 98 134 216 8 226 203 222 176 199 217 16 33 27 254 242 252 15 144 29 244 149 141 246 21 50 148 240 221 215 112 159 190 201 42 220 60 194 163 217 79 62 139 152 60 34 219 25 197 25 50 239 71 252 46 8 146 228 159 67 244 43 221 173 232 134 163 214 92 48 73 211 145 113 132 57 218 71 209 251 180 212 226 60 108 2 92 209 20 59 249 248 235 254 211 114 60 150 221 161 38 175 10 35 94 58 32 247 22 221 242 125 116 247 241 210 176 226 53 77 22 198 238 250 32 87 57 166 119 82 151 233 5 167 98 210 180 61 86 49 156 93 101 32 242 201 67 199 242 244 169 24 131 107 142 193 188 182 171 67 124 178 70 144 116 110 158 184 225 62 243 12 143 139 219 68 166 216 44 91 103)
#t
())
#(18
"byte 0 in zero padding modified"
#vu8(49 50 51 52 48 48)
#vu8(137 232 73 239 194 104 3 227 161 82 118 95 197 59 16 213 69 213 190 87 79 50 151 98 59 202 239 253 26 180 45 214 113 144 42 191 154 153 208 177 105 204 62 173 112 10 33 118 48 77 3 51 239 49 47 38 172 38 61 89 75 174 57 210 64 79 213 230 150 90 231 135 149 245 48 128 134 179 251 230 136 16 113 41 126 196 183 76 162 64 24 36 73 7 173 206 151 166 205 9 172 160 233 114 22 157 249 29 71 68 228 194 65 238 218 88 219 206 0 194 200 108 187 157 11 27 77 29 169 32 26 17 233 96 21 207 93 155 214 204 251 216 63 18 188 134 39 105 122 27 158 16 44 130 47 242 3 235 43 134 182 104 177 81 24 233 115 114 149 120 3 134 188 5 5 219 72 228 110 202 29 117 38 103 55 64 101 205 8 78 53 121 5 240 69 37 183 26 98 70 84 202 151 212 170 46 106 86 98 40 254 172 161 15 178 250 122 189 123 47 203 103 156 137 199 48 232 11 44 30 89 78 231 133 133 91 221 75 203 121 169 248 85 163 193 126 60 227 35 173 4 175 237 216 145 12)
#f
())
#(19
"byte 7 in zero padding modified"
#vu8(49 50 51 52 48 48)
#vu8(63 231 202 71 156 41 203 99 146 77 18 244 120 29 177 223 252 67 185 42 160 182 2 218 226 144 207 59 207 10 112 84 80 176 207 99 153 231 177 44 250 79 84 63 51 76 129 157 218 92 21 173 45 211 67 207 151 171 5 141 40 120 14 218 225 132 218 13 162 21 197 28 112 84 195 106 199 18 68 103 234 219 37 26 175 94 218 148 119 109 229 125 239 32 66 10 200 241 84 228 65 86 32 47 78 71 159 82 97 76 193 27 236 105 71 217 107 235 41 28 79 66 200 113 183 1 206 142 116 70 70 177 46 150 117 87 187 144 51 71 86 148 233 138 46 162 214 248 109 51 157 55 122 199 234 141 254 64 87 233 2 152 25 49 9 91 158 0 76 81 9 227 45 202 197 96 215 240 210 99 1 123 50 24 195 57 251 46 43 209 48 39 227 12 209 148 170 147 78 21 170 252 193 51 220 20 124 20 84 253 97 214 161 128 59 62 156 33 214 233 21 143 204 26 144 182 119 158 158 13 140 129 80 241 100 116 190 155 22 78 111 155 217 137 39 176 105 100 28 237 191 216 60 100 51 75)
#f
())
#(20
"all bytes in zero padding modified"
#vu8(49 50 51 52 48 48)
#vu8(92 132 100 145 48 176 189 19 229 85 42 66 117 192 2 210 24 206 119 53 56 42 123 87 113 167 211 52 166 88 85 12 162 238 69 160 209 165 107 76 12 45 109 17 52 215 204 165 219 100 66 173 175 238 4 77 185 44 48 61 86 197 81 32 80 210 216 29 189 2 181 8 234 215 220 170 1 255 8 29 104 237 138 179 50 67 215 254 244 51 201 243 175 211 177 131 151 37 214 254 121 54 182 104 167 92 164 116 50 249 46 125 197 37 152 76 1 177 120 45 131 56 48 187 158 110 228 82 116 107 47 74 89 210 113 42 31 169 64 248 22 136 152 10 172 220 188 157 179 166 85 22 243 0 178 217 16 76 253 206 61 112 2 116 32 97 247 21 0 112 233 225 116 168 61 119 152 88 188 242 70 218 171 93 41 182 129 238 82 223 174 179 66 128 110 245 106 144 147 28 210 27 149 222 175 16 92 1 184 199 175 116 140 15 156 236 173 135 2 133 253 198 164 63 149 248 124 5 47 195 95 26 49 83 184 208 155 34 24 207 190 114 116 180 140 143 111 233 93 154 136 219 99 77 21 91)
#f
())
#(21
"first byte of hash h modified"
#vu8(49 50 51 52 48 48)
#vu8(111 48 183 207 46 94 53 135 37 244 38 183 57 144 23 30 141 89 249 236 107 224 204 210 18 73 74 63 236 165 126 43 9 73 1 29 252 237 147 146 63 147 203 136 163 157 44 3 185 220 193 6 232 215 2 207 53 255 51 130 236 80 134 99 70 120 31 190 241 155 215 121 42 252 30 130 221 158 21 246 4 250 232 121 156 219 220 128 70 144 152 255 161 169 171 80 115 163 66 204 209 255 127 70 20 234 6 204 69 229 155 35 125 243 138 34 241 93 27 247 86 96 40 236 75 225 122 193 149 122 100 137 12 125 204 96 19 67 204 254 176 120 135 13 217 9 132 31 124 82 12 159 43 46 223 122 136 7 72 116 196 114 195 220 66 65 152 18 22 229 156 236 204 190 118 94 128 153 38 5 123 134 82 84 115 139 196 247 202 17 234 239 4 86 21 239 155 78 34 65 83 179 46 42 212 237 222 171 94 42 129 8 16 69 184 171 103 159 95 179 63 83 12 234 69 230 235 239 240 172 73 65 218 247 41 83 184 73 114 4 203 233 142 211 129 113 64 183 187 157 112 173 232 164 148 115)
#f
())
#(22
"first byte of hash h modified"
#vu8(49 50 51 52 48 48)
#vu8(126 208 235 36 3 155 228 105 93 222 81 125 148 209 183 190 127 42 229 159 59 163 167 226 32 80 247 254 137 158 67 48 185 96 80 130 143 80 55 14 203 80 195 87 175 71 75 216 102 236 235 147 176 116 155 243 138 151 172 188 249 191 168 255 83 163 4 144 174 195 204 95 107 57 200 182 193 148 137 30 121 114 166 158 61 194 208 87 151 82 66 0 204 2 175 8 51 206 162 132 5 59 159 149 60 34 48 49 105 11 30 31 184 167 178 96 158 107 185 79 60 112 28 218 72 77 79 125 132 144 43 98 252 145 224 240 236 105 56 125 93 244 151 227 24 182 112 106 16 164 88 30 63 7 60 117 5 10 148 102 60 200 51 53 213 15 5 31 245 208 5 151 79 54 164 84 31 101 165 96 229 135 240 156 146 79 82 167 129 83 116 89 242 5 38 248 148 89 118 91 75 173 243 160 64 195 57 34 116 64 225 98 80 123 192 249 250 145 225 106 78 77 88 198 200 31 239 199 110 109 184 34 14 180 159 109 18 118 205 220 20 111 13 150 74 175 190 244 156 147 95 83 184 162 178 21)
#f
())
#(23
"last byte of hash h modified"
#vu8(49 50 51 52 48 48)
#vu8(99 40 66 230 205 25 11 10 160 49 5 73 146 64 160 77 251 61 97 33 118 100 45 223 104 238 254 143 246 125 225 140 211 135 22 91 245 243 78 120 5 46 241 209 171 136 140 97 104 170 33 249 119 217 54 133 110 174 197 202 0 52 172 236 33 99 16 52 48 76 71 16 245 102 90 130 23 243 20 209 191 151 5 135 217 158 6 239 56 110 156 11 225 165 251 198 69 197 243 243 110 73 126 69 87 226 172 131 3 55 24 35 9 100 25 154 223 133 122 217 113 236 105 212 33 106 172 208 237 37 126 222 199 60 138 100 74 162 94 23 82 151 244 20 184 201 17 233 220 91 182 134 109 193 185 199 229 45 94 101 109 89 140 122 112 7 167 200 66 130 142 147 74 80 142 124 14 64 3 38 62 101 126 132 191 45 16 160 204 187 71 98 11 236 190 15 82 195 240 149 177 126 61 212 233 6 251 173 127 69 235 219 232 153 90 97 203 248 43 110 213 138 50 241 46 51 179 144 15 186 7 216 20 150 147 164 60 52 100 156 189 52 170 122 107 147 3 212 15 24 123 188 246 26 19 206)
#f
())
#(24
"last byte of hash h modified"
#vu8(49 50 51 52 48 48)
#vu8(84 94 205 58 27 135 153 183 73 227 123 196 95 168 185 151 209 95 18 209 18 58 187 7 118 97 48 231 68 41 162 190 207 150 132 235 237 160 133 93 240 117 226 177 138 199 202 145 231 125 142 104 46 23 19 25 247 66 235 109 131 60 19 131 255 35 52 17 221 127 163 102 57 239 98 143 191 111 165 58 176 115 131 193 102 54 65 255 228 205 3 13 32 254 75 53 117 151 213 27 203 226 114 92 6 186 0 5 36 26 121 88 185 97 169 107 180 69 191 25 185 5 111 215 21 69 19 207 125 34 96 42 14 39 29 233 39 50 4 149 91 217 68 152 78 216 41 44 18 82 33 5 156 38 185 211 206 220 121 240 117 14 67 14 136 98 118 42 57 122 10 135 55 254 86 35 230 104 188 36 165 236 139 97 158 5 6 208 151 32 190 174 207 2 200 67 33 83 212 201 24 164 97 199 211 37 93 177 155 177 44 140 95 254 4 111 208 103 107 230 133 138 232 131 161 62 113 230 156 53 238 47 9 55 95 1 161 253 94 23 230 96 97 79 31 41 61 176 167 103 1 204 162 123 150 153)
#f
())
#(25
"all bytes of h replaced by 0"
#vu8(49 50 51 52 48 48)
#vu8(158 1 88 200 203 52 111 227 135 225 29 117 20 31 36 51 54 175 11 149 96 96 126 42 249 241 108 96 242 113 182 97 74 136 66 163 71 161 122 39 187 73 241 63 137 76 210 228 148 193 136 131 101 180 51 195 196 204 107 176 223 210 219 223 83 7 49 73 106 253 243 154 112 202 242 146 113 172 197 138 116 212 25 107 133 187 143 55 111 172 223 134 35 43 157 0 249 245 202 191 10 55 195 47 113 230 176 215 203 120 162 233 50 102 59 243 60 104 52 42 23 87 120 38 162 48 185 7 46 111 151 169 155 207 103 155 112 150 88 194 158 224 126 243 128 146 57 233 83 188 121 147 62 75 228 131 99 12 177 250 223 149 20 60 96 234 43 67 84 68 233 114 180 130 72 179 153 205 146 38 28 11 201 249 73 255 108 220 82 225 255 105 51 71 231 94 101 250 170 106 254 60 165 82 205 54 134 214 99 214 49 169 97 4 107 123 170 10 174 14 98 120 60 223 23 92 23 140 145 246 18 72 34 157 85 132 224 7 15 34 24 196 129 173 115 222 124 218 190 97 233 51 230 47 63 83)
#f
())
#(26
"all bits of h replaced by 1s"
#vu8(49 50 51 52 48 48)
#vu8(30 201 149 96 239 112 240 44 82 60 57 203 210 26 234 13 14 106 101 147 178 2 158 201 233 244 153 248 221 189 134 74 10 133 188 220 216 172 234 134 112 144 197 17 235 214 51 16 91 131 3 81 85 7 72 12 203 88 219 244 223 160 59 185 2 217 50 115 135 48 41 248 225 10 2 188 20 9 19 213 173 28 30 109 135 169 123 66 117 86 145 84 29 254 125 52 75 176 204 32 157 210 188 138 44 54 179 202 248 41 90 17 189 208 96 222 52 125 78 145 178 56 42 83 188 174 250 41 223 0 151 141 73 64 111 192 93 84 12 239 106 221 89 57 202 9 21 208 215 217 143 8 131 231 207 80 4 211 218 144 160 251 61 11 156 230 184 86 127 208 63 241 207 68 200 216 10 63 249 241 179 22 194 40 64 18 73 2 202 215 191 43 212 78 147 212 195 68 198 169 87 164 157 91 132 123 121 174 210 249 151 87 225 207 204 24 202 154 190 46 123 44 26 250 162 156 1 101 239 197 235 172 28 128 168 94 193 113 99 114 104 190 237 83 110 89 29 55 236 109 166 158 226 229 58 168)
#f
())
#(27
"all bits in hash h flipped"
#vu8(49 50 51 52 48 48)
#vu8(43 79 240 127 119 136 175 160 207 99 162 133 162 184 136 96 249 167 95 126 215 104 161 70 128 171 61 16 93 112 166 18 250 201 138 30 135 132 121 15 246 193 202 3 220 206 90 30 216 74 134 196 80 38 15 154 136 204 83 43 252 48 230 183 255 2 48 160 220 86 6 119 159 21 83 68 114 148 179 105 46 137 203 145 134 79 58 149 197 145 233 206 132 162 243 133 21 130 109 197 99 60 7 92 189 173 3 239 240 106 132 102 214 236 153 195 39 117 12 110 120 200 215 126 51 87 59 229 25 8 85 213 144 176 126 121 187 61 96 153 104 140 95 57 193 146 196 215 191 143 191 32 93 38 120 155 140 199 178 144 216 64 112 107 163 49 144 19 108 186 58 166 189 22 238 20 229 65 43 200 217 157 125 36 87 88 9 58 34 54 165 60 245 88 37 213 114 230 145 8 176 43 25 24 139 250 0 69 87 63 99 158 22 148 247 175 30 214 41 158 16 242 138 26 149 60 167 41 74 14 250 70 47 159 209 135 109 111 175 46 124 64 229 85 79 255 128 200 239 37 110 66 79 2 227 244)
#f
())
#(28
"hash of salt missing"
#vu8(49 50 51 52 48 48)
#vu8(109 236 65 10 78 53 102 165 33 91 108 157 15 229 250 11 95 92 101 223 12 79 149 45 203 124 72 215 206 245 123 22 218 163 21 215 209 224 92 89 40 188 6 21 221 14 81 189 83 60 82 117 60 107 84 181 36 165 76 120 122 169 86 189 58 248 174 126 172 31 205 180 173 236 187 189 17 74 154 225 155 103 103 201 231 71 78 250 84 232 248 97 186 185 62 12 148 248 176 201 54 25 83 201 65 30 18 243 75 95 158 132 250 95 138 234 41 227 22 235 152 59 136 50 40 87 69 101 230 213 61 130 196 117 69 170 199 13 61 59 36 238 62 43 58 205 89 126 227 36 100 23 109 169 14 150 35 236 44 208 40 49 222 64 225 253 92 98 123 66 25 65 101 23 27 200 135 112 67 254 143 89 117 227 134 49 165 87 1 216 78 137 95 166 157 214 119 141 218 132 152 117 100 82 209 113 199 25 88 152 239 233 203 131 123 42 189 154 34 165 140 18 48 251 127 171 44 107 149 91 92 210 78 185 124 246 127 234 1 140 47 40 50 52 165 189 138 190 6 149 178 82 176 71 220 240)
#f
())
#(29
"first byte of ps modified"
#vu8(49 50 51 52 48 48)
#vu8(97 70 66 65 153 82 138 73 143 109 254 242 42 153 208 166 135 31 43 110 39 224 29 173 223 201 133 220 86 84 66 148 24 23 160 165 223 202 236 62 229 186 164 142 14 12 144 43 43 169 182 47 4 125 128 33 11 97 76 165 206 243 92 204 214 1 17 25 139 177 41 229 156 167 182 219 46 13 236 143 162 118 41 7 208 214 237 0 194 153 92 7 58 204 190 203 202 131 107 226 206 177 187 183 193 77 242 31 159 219 64 158 120 191 157 64 154 56 152 195 78 228 72 187 184 143 146 172 213 41 111 80 116 43 248 49 224 18 63 78 184 104 176 114 23 199 112 126 3 44 245 221 130 30 56 163 248 150 113 122 238 125 67 221 62 214 203 185 23 37 151 206 132 15 18 110 199 138 130 148 242 2 86 148 252 93 97 140 255 160 173 189 197 113 124 67 192 80 109 16 188 3 51 4 167 31 90 225 3 1 105 218 103 161 175 237 206 133 164 27 127 150 78 15 181 64 4 216 207 4 234 147 36 179 176 201 52 232 40 87 222 211 175 109 249 144 62 232 111 161 251 36 88 172 157 18)
#f
())
#(30
"last byte of ps modified"
#vu8(49 50 51 52 48 48)
#vu8(43 55 57 56 37 209 250 248 156 234 98 177 38 35 123 13 104 7 187 79 181 117 107 154 158 32 207 73 186 109 238 70 2 237 171 205 116 211 183 48 174 197 144 236 81 132 205 56 24 73 47 76 138 255 222 8 36 255 66 81 86 75 21 65 14 173 154 90 39 230 143 71 173 252 175 232 181 151 49 17 240 0 188 102 49 232 28 69 74 79 238 111 250 34 221 47 1 242 134 128 239 116 250 208 195 8 11 191 121 88 203 110 72 134 240 26 66 33 15 26 159 75 193 250 110 138 113 171 227 154 65 241 241 192 158 252 190 166 161 10 187 12 30 34 117 77 32 161 42 56 165 178 104 150 226 186 159 248 133 177 122 223 101 202 104 17 80 112 251 209 201 12 5 145 120 224 68 196 94 36 40 230 112 131 235 101 229 72 16 84 249 203 76 35 179 15 180 55 19 57 106 64 159 44 152 220 113 131 73 135 136 101 239 32 15 159 245 220 45 154 4 119 161 46 195 18 205 197 101 181 231 91 159 223 29 229 63 230 248 177 118 52 129 122 58 202 131 224 42 2 94 220 3 83 36 115)
#f
())
#(31
"all bytes of ps changed to 0xff"
#vu8(49 50 51 52 48 48)
#vu8(151 94 132 177 21 108 236 63 54 205 169 151 85 80 109 208 187 205 66 161 17 110 155 134 50 116 96 13 245 27 230 113 3 176 196 75 106 90 136 100 19 106 74 37 164 125 142 246 26 217 29 97 13 105 110 1 88 65 56 80 103 151 98 5 21 20 80 4 106 191 164 249 81 79 116 135 242 25 26 28 185 57 222 88 33 143 69 112 182 26 107 166 246 214 234 75 42 192 157 183 156 65 107 247 115 111 230 113 253 17 198 100 115 50 206 74 110 38 159 183 174 50 9 128 248 245 24 99 86 38 0 244 187 84 58 209 41 82 237 169 34 113 193 76 181 86 21 15 234 188 65 72 230 210 138 44 133 141 154 78 132 171 152 95 164 22 254 97 25 252 36 22 89 19 154 151 131 240 28 196 104 52 239 53 172 92 33 91 179 116 188 55 32 174 225 154 191 36 149 91 122 11 162 212 134 134 26 152 113 187 170 103 2 221 40 9 249 157 190 162 158 41 33 40 107 93 95 127 213 253 197 148 194 149 47 154 57 0 63 227 188 14 35 191 112 38 173 169 25 142 174 201 199 221 38 122)
#f
())
#(32
"all bytes of ps changed to 0x80"
#vu8(49 50 51 52 48 48)
#vu8(110 35 97 202 229 245 215 227 236 182 180 96 15 26 39 219 16 178 185 181 154 29 98 13 199 49 75 204 206 241 11 197 42 13 208 171 127 220 38 186 182 30 207 117 217 43 222 18 172 145 88 247 233 172 110 140 7 49 164 113 75 187 171 50 53 247 82 65 55 177 111 39 38 168 126 54 11 130 249 216 36 81 18 189 50 48 135 195 78 148 160 155 215 94 164 90 43 144 76 53 68 162 9 143 83 103 222 198 87 247 231 24 69 87 237 78 178 227 189 176 31 220 201 216 232 235 32 148 133 212 99 66 242 32 130 118 188 166 49 167 84 100 236 27 143 58 211 77 238 221 11 141 151 166 2 147 12 134 63 117 119 127 38 184 50 78 13 103 252 177 218 178 234 85 104 70 249 56 179 26 123 177 216 96 196 215 55 255 69 214 181 149 97 150 58 3 104 242 166 72 191 223 129 193 71 190 29 107 191 1 20 55 233 139 104 85 116 119 176 49 20 245 3 39 87 143 17 25 108 208 23 183 254 234 34 235 148 126 187 213 198 8 4 53 181 233 160 26 81 96 6 127 88 113 29 143)
#f
())
#(33
"ps followed by 0"
#vu8(49 50 51 52 48 48)
#vu8(10 47 110 234 163 51 173 5 218 17 63 160 12 220 211 136 143 173 115 150 5 196 217 179 69 0 13 106 227 216 10 119 34 80 16 159 164 36 239 133 21 57 31 62 164 196 20 156 62 112 115 242 10 79 45 133 164 182 246 50 236 114 92 196 165 199 150 174 29 214 76 74 219 174 73 79 105 51 233 203 28 64 69 231 125 153 26 218 50 46 130 163 49 81 15 123 72 192 158 98 225 242 133 0 90 21 170 180 185 100 93 95 118 67 86 227 38 106 165 65 4 118 239 206 68 123 15 140 248 241 30 245 143 82 8 156 243 69 228 112 83 83 42 18 217 254 17 251 252 73 218 159 61 220 205 93 91 51 131 23 213 167 9 136 59 127 79 130 48 111 90 236 92 130 39 35 140 253 246 203 158 143 235 231 47 146 63 226 226 67 156 189 218 91 246 51 24 39 162 24 150 19 2 58 73 64 28 22 200 91 177 99 198 83 4 228 194 199 73 234 39 168 176 112 129 77 102 248 233 254 89 114 91 150 207 215 109 12 76 97 45 90 73 166 26 115 228 124 75 231 114 149 147 241 215 91)
#f
())
#(34
"ps followed by 0xff"
#vu8(49 50 51 52 48 48)
#vu8(116 27 92 111 232 221 43 175 165 3 31 11 174 5 123 124 107 91 192 210 196 242 96 223 36 73 194 187 217 71 178 204 6 255 70 174 103 175 115 121 93 208 93 118 190 225 95 75 38 114 144 207 165 141 187 249 178 159 153 195 101 228 132 18 65 178 46 19 93 171 212 7 0 214 169 44 241 70 190 117 29 190 143 126 133 190 250 234 156 51 113 44 246 43 224 195 215 111 106 81 79 239 19 161 186 111 206 108 103 136 136 16 2 47 76 22 139 37 23 163 1 45 231 98 255 16 32 85 4 237 39 184 14 191 173 237 18 189 26 187 37 119 251 98 11 215 12 241 174 136 106 184 16 20 104 150 215 66 142 132 244 139 160 181 247 230 126 22 148 17 191 32 125 203 67 192 225 133 239 130 241 187 220 67 26 112 209 3 87 119 120 189 202 180 36 239 63 97 159 61 228 170 73 236 46 72 252 64 221 68 249 15 214 252 165 13 2 241 162 115 82 96 84 138 1 165 104 199 54 157 98 153 157 48 93 195 205 21 220 236 242 166 65 124 213 180 194 106 197 21 94 190 232 229 119 247)
#f
())
#(35
"shifted salt"
#vu8(49 50 51 52 48 48)
#vu8(127 238 30 158 95 119 125 95 80 116 58 30 197 53 57 213 240 130 68 50 191 220 155 126 243 29 43 24 82 128 71 115 150 151 150 213 3 253 178 180 139 8 205 141 189 217 10 255 198 160 199 244 99 159 217 49 21 93 220 61 82 82 153 62 206 245 179 223 135 38 9 228 137 10 228 120 248 9 237 255 213 226 114 95 46 41 179 202 64 42 244 133 62 207 164 169 174 113 182 140 59 17 68 206 212 122 39 163 14 39 45 205 251 153 219 206 15 253 59 191 206 18 165 147 60 46 182 142 176 59 157 41 180 192 177 110 102 156 218 192 244 45 0 206 66 24 100 65 139 113 195 84 186 17 198 90 250 236 169 25 244 220 179 240 155 200 190 146 0 27 66 152 18 142 131 45 101 89 206 157 252 66 227 234 42 226 37 155 25 21 50 174 178 65 154 143 33 215 67 69 121 178 201 3 67 5 195 69 140 235 102 224 72 185 3 210 45 227 9 165 9 91 68 114 226 165 133 14 224 119 127 14 230 36 100 99 159 118 110 237 213 211 80 212 16 154 243 176 165 46 220 115 115 248 249 58)
#f
())
#(36
"including garbage"
#vu8(49 50 51 52 48 48)
#vu8(23 149 172 64 200 0 58 149 61 13 13 224 142 227 86 19 239 58 201 82 66 82 25 227 123 86 153 206 0 42 108 87 70 85 229 39 207 140 67 61 123 115 179 19 99 139 43 157 240 233 163 109 181 118 183 40 247 200 231 82 19 146 165 250 81 252 15 197 136 233 37 81 89 75 167 155 70 182 115 103 70 93 21 117 241 46 60 244 34 127 234 80 129 100 35 44 65 211 195 207 146 208 90 203 78 251 220 90 59 102 160 147 167 147 130 20 62 15 192 248 246 171 201 13 92 152 98 234 186 141 186 137 100 173 77 253 23 162 20 172 203 76 75 84 138 87 87 19 90 246 141 72 142 254 104 231 230 106 114 121 242 238 190 170 250 102 200 124 104 24 239 201 217 250 218 22 69 85 41 166 22 134 22 94 13 139 148 236 255 211 70 244 108 212 66 20 233 199 31 244 87 120 187 221 61 243 165 142 245 216 192 46 4 105 167 112 119 133 104 164 49 106 185 83 26 119 203 124 229 93 224 97 248 162 39 237 44 93 236 94 99 197 186 204 42 71 77 157 107 119 240 97 59 90 111 163)
#f
())
#(37
"bit 7 of masked_db not cleared"
#vu8(49 50 51 52 48 48)
#vu8(92 110 80 84 244 17 203 67 241 94 228 96 34 24 125 164 92 130 20 160 245 246 229 44 77 234 245 122 164 64 64 192 135 184 40 209 195 213 162 225 195 120 7 124 81 249 188 73 89 154 252 254 157 176 53 16 55 99 146 1 97 73 173 97 190 193 32 59 244 253 5 103 35 65 246 44 179 46 154 77 127 142 145 210 149 60 229 232 51 112 191 74 94 209 195 19 41 197 98 42 125 85 168 46 138 25 236 194 89 132 236 217 159 56 25 135 150 254 49 195 222 241 6 198 232 25 70 34 74 124 26 13 147 88 105 254 142 246 187 137 47 182 223 128 108 245 45 224 159 74 200 106 190 81 241 177 72 246 179 45 187 151 203 248 124 221 37 154 197 118 102 222 221 10 252 182 221 124 171 82 125 140 184 71 207 26 24 240 27 10 20 240 241 243 181 15 203 154 244 105 42 188 166 11 18 51 21 16 193 236 207 219 170 18 139 219 159 2 93 117 254 138 73 218 44 239 4 48 121 18 162 210 144 126 190 106 119 221 68 219 204 93 131 117 48 150 235 14 186 134 190 212 47 216 79 36)
#f
())
#(38
"first byte of masked_db changed to 0"
#vu8(49 50 51 52 48 48)
#vu8(121 40 197 135 125 187 22 199 97 209 94 89 151 81 33 89 186 178 148 252 29 28 199 58 88 101 248 72 64 243 105 214 188 71 80 75 186 132 50 0 58 79 28 188 252 233 125 238 19 118 96 233 115 229 24 31 126 129 248 151 250 96 121 65 161 29 149 171 35 12 140 42 254 171 37 38 197 217 6 89 117 147 148 139 126 150 119 130 61 177 60 18 6 44 86 208 184 244 188 162 131 220 144 163 150 44 252 152 8 158 9 205 199 145 229 202 96 118 202 142 110 11 115 29 133 237 95 75 227 142 215 152 231 11 67 127 30 236 75 181 183 10 143 191 53 243 192 95 15 147 243 65 103 236 102 103 131 160 128 98 194 35 13 18 249 210 145 236 180 229 35 189 126 144 211 248 210 149 213 114 63 193 189 53 137 34 7 66 63 32 225 201 37 194 112 241 232 182 229 118 184 114 223 71 93 86 27 93 199 117 112 91 205 171 162 21 243 196 238 156 37 113 228 27 154 65 255 35 246 1 60 2 32 39 85 182 5 187 162 29 43 198 252 172 108 254 228 81 130 193 31 72 83 219 38 181)
#f
())
#(39
"last byte in em modified"
#vu8(49 50 51 52 48 48)
#vu8(9 252 98 137 11 38 212 89 86 175 170 165 125 99 213 78 32 92 31 91 98 4 136 155 248 62 90 216 137 95 237 173 234 30 184 94 78 73 102 61 36 96 93 76 74 47 127 198 133 14 128 103 144 78 112 1 85 92 11 171 89 93 59 195 109 182 47 54 150 41 201 83 68 103 64 110 234 224 79 214 59 241 100 199 125 119 206 123 91 192 31 30 207 164 229 208 0 201 74 79 55 196 248 241 111 208 197 170 68 209 226 246 167 54 27 73 123 206 195 29 108 251 235 92 128 93 92 181 50 26 13 232 242 200 224 251 158 14 25 183 66 30 177 164 50 179 22 208 235 46 114 213 201 56 2 143 233 143 88 71 185 12 135 189 34 187 165 222 129 255 160 201 177 122 232 106 50 188 166 67 48 7 171 68 86 81 184 217 65 88 178 251 169 33 74 98 160 246 146 252 18 211 254 248 247 134 121 96 19 148 148 59 191 72 19 174 86 17 12 236 161 146 155 254 34 90 84 57 214 162 229 175 173 80 51 47 173 223 67 69 89 160 48 58 45 223 174 239 71 26 151 78 56 243 158 196)
#f
())
#(40
"last byte in em modified"
#vu8(49 50 51 52 48 48)
#vu8(10 24 200 191 190 210 176 253 116 224 110 45 223 181 236 133 25 141 206 217 84 111 139 198 248 12 159 140 165 42 13 21 58 96 156 219 61 100 93 125 124 185 205 118 14 159 231 102 18 126 181 194 206 5 204 103 141 116 157 5 250 55 223 6 170 236 21 199 119 217 49 136 239 86 200 73 156 80 181 218 189 84 59 20 170 201 253 140 9 221 201 111 128 192 226 116 131 52 161 140 75 16 213 189 26 67 194 19 157 71 117 28 51 201 70 163 117 62 19 96 168 29 31 103 113 178 65 25 85 90 51 143 46 130 64 105 233 70 73 125 155 144 134 46 243 179 156 5 186 103 77 234 169 93 211 41 26 224 92 190 212 244 184 104 175 237 46 101 92 223 204 54 192 167 3 165 86 26 132 109 230 106 122 230 118 52 164 91 198 14 150 108 129 182 52 62 203 218 70 204 117 146 104 126 116 160 62 88 99 223 14 183 251 77 162 238 195 137 82 88 31 162 234 72 198 36 71 137 49 145 181 98 177 144 92 166 13 249 135 10 7 74 58 97 1 145 26 49 200 249 60 59 231 167 226 29)
#f
())
#(41
"last byte in em modified"
#vu8(49 50 51 52 48 48)
#vu8(99 192 3 185 187 228 38 123 216 62 249 240 28 11 222 9 67 180 38 134 253 246 209 220 111 243 238 233 106 208 235 186 33 226 194 17 157 60 232 113 10 211 105 115 92 169 242 196 254 254 255 219 216 147 55 54 104 41 113 180 171 98 11 119 83 251 123 134 103 5 203 9 238 34 75 197 178 215 120 213 136 54 173 49 211 195 236 252 99 177 222 160 206 71 32 52 229 8 240 87 250 208 60 81 94 235 11 98 121 3 135 242 234 216 239 197 66 26 153 46 61 113 165 61 180 137 128 218 222 207 182 216 55 197 1 176 140 121 30 36 70 94 44 180 41 114 211 69 11 230 209 86 31 177 196 22 243 6 130 12 181 21 108 234 68 201 101 202 100 226 148 24 83 113 137 116 200 176 231 109 197 246 224 245 128 207 82 167 225 102 237 182 212 29 121 166 145 184 246 128 122 137 117 46 133 46 212 226 7 176 120 243 200 189 253 241 106 105 20 185 112 250 121 137 248 26 87 63 177 241 165 39 51 199 33 34 66 221 103 63 244 133 113 165 104 113 58 172 9 73 73 161 44 154 117 94)
#f
())
#(42
"signature is 0"
#vu8(49 50 51 52 48 48)
#vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#f
())
#(43
"signature is 1"
#vu8(49 50 51 52 48 48)
#vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1)
#f
())
#(44
"signature is n-1"
#vu8(49 50 51 52 48 48)
#vu8(163 143 188 243 78 239 24 16 203 42 226 31 239 30 154 30 3 127 125 37 212 62 139 79 5 30 167 76 54 123 221 178 50 122 123 204 197 51 79 230 16 247 169 133 94 43 118 193 233 113 89 112 194 44 39 70 22 253 148 96 215 39 175 233 161 73 194 59 107 151 48 193 60 79 98 19 224 193 18 164 157 178 229 89 147 182 12 82 14 183 48 66 199 160 177 191 228 226 123 17 164 199 57 80 87 35 82 51 253 138 179 137 138 213 106 120 147 7 123 188 68 20 180 8 154 89 76 156 190 197 222 202 9 46 251 77 132 217 119 185 243 127 217 130 52 29 169 99 162 10 246 128 255 74 119 78 200 90 16 74 104 70 72 176 169 11 108 196 247 212 128 141 182 102 235 171 128 138 33 2 15 140 0 92 103 147 241 150 24 120 17 147 85 38 202 241 182 206 228 122 12 20 224 130 63 135 215 170 130 233 245 166 53 202 17 102 134 210 218 113 156 218 38 156 57 216 99 87 28 96 110 92 229 51 66 84 228 150 72 252 252 245 2 161 50 28 192 113 241 0 13 86 39 35 21 110)
#f
())
#(45
"signature is n"
#vu8(49 50 51 52 48 48)
#vu8(163 143 188 243 78 239 24 16 203 42 226 31 239 30 154 30 3 127 125 37 212 62 139 79 5 30 167 76 54 123 221 178 50 122 123 204 197 51 79 230 16 247 169 133 94 43 118 193 233 113 89 112 194 44 39 70 22 253 148 96 215 39 175 233 161 73 194 59 107 151 48 193 60 79 98 19 224 193 18 164 157 178 229 89 147 182 12 82 14 183 48 66 199 160 177 191 228 226 123 17 164 199 57 80 87 35 82 51 253 138 179 137 138 213 106 120 147 7 123 188 68 20 180 8 154 89 76 156 190 197 222 202 9 46 251 77 132 217 119 185 243 127 217 130 52 29 169 99 162 10 246 128 255 74 119 78 200 90 16 74 104 70 72 176 169 11 108 196 247 212 128 141 182 102 235 171 128 138 33 2 15 140 0 92 103 147 241 150 24 120 17 147 85 38 202 241 182 206 228 122 12 20 224 130 63 135 215 170 130 233 245 166 53 202 17 102 134 210 218 113 156 218 38 156 57 216 99 87 28 96 110 92 229 51 66 84 228 150 72 252 252 245 2 161 50 28 192 113 241 0 13 86 39 35 21 111)
#f
())
#(46
"prepending 0's to signature"
#vu8(49 50 51 52 48 48)
#vu8(0 0 105 248 249 9 198 244 207 78 217 153 80 204 194 133 21 88 138 154 120 28 37 89 222 142 44 232 176 167 63 244 35 190 71 91 88 217 29 110 181 122 112 144 38 4 97 95 217 250 178 230 188 166 181 253 48 46 176 44 95 75 110 53 167 205 17 50 5 134 246 41 88 52 181 93 76 79 9 196 169 123 158 242 45 35 33 168 244 238 241 163 144 74 33 101 124 52 103 63 251 114 216 60 160 68 228 45 114 134 194 104 19 47 172 78 60 51 118 212 178 112 179 221 162 191 224 226 190 186 45 134 112 167 194 36 187 123 192 39 19 239 190 239 118 125 80 14 234 78 62 255 76 145 88 8 156 95 29 150 245 193 10 22 84 131 125 16 232 77 35 188 132 22 107 20 200 82 169 175 12 226 15 76 248 166 59 123 90 219 119 90 174 13 210 250 151 205 187 88 141 54 231 15 171 169 73 228 85 65 168 59 180 233 234 53 117 38 79 143 29 130 25 83 208 175 1 219 42 22 172 64 18 238 151 185 241 202 235 174 206 90 177 201 68 85 155 12 148 65 74 236 173 214 102 107 25 164)
#f
())
#(47
"appending 0's to signature"
#vu8(49 50 51 52 48 48)
#vu8(105 248 249 9 198 244 207 78 217 153 80 204 194 133 21 88 138 154 120 28 37 89 222 142 44 232 176 167 63 244 35 190 71 91 88 217 29 110 181 122 112 144 38 4 97 95 217 250 178 230 188 166 181 253 48 46 176 44 95 75 110 53 167 205 17 50 5 134 246 41 88 52 181 93 76 79 9 196 169 123 158 242 45 35 33 168 244 238 241 163 144 74 33 101 124 52 103 63 251 114 216 60 160 68 228 45 114 134 194 104 19 47 172 78 60 51 118 212 178 112 179 221 162 191 224 226 190 186 45 134 112 167 194 36 187 123 192 39 19 239 190 239 118 125 80 14 234 78 62 255 76 145 88 8 156 95 29 150 245 193 10 22 84 131 125 16 232 77 35 188 132 22 107 20 200 82 169 175 12 226 15 76 248 166 59 123 90 219 119 90 174 13 210 250 151 205 187 88 141 54 231 15 171 169 73 228 85 65 168 59 180 233 234 53 117 38 79 143 29 130 25 83 208 175 1 219 42 22 172 64 18 238 151 185 241 202 235 174 206 90 177 201 68 85 155 12 148 65 74 236 173 214 102 107 25 164 0 0)
#f
())
#(48
"truncated signature"
#vu8(49 50 51 52 48 48)
#vu8(105 248 249 9 198 244 207 78 217 153 80 204 194 133 21 88 138 154 120 28 37 89 222 142 44 232 176 167 63 244 35 190 71 91 88 217 29 110 181 122 112 144 38 4 97 95 217 250 178 230 188 166 181 253 48 46 176 44 95 75 110 53 167 205 17 50 5 134 246 41 88 52 181 93 76 79 9 196 169 123 158 242 45 35 33 168 244 238 241 163 144 74 33 101 124 52 103 63 251 114 216 60 160 68 228 45 114 134 194 104 19 47 172 78 60 51 118 212 178 112 179 221 162 191 224 226 190 186 45 134 112 167 194 36 187 123 192 39 19 239 190 239 118 125 80 14 234 78 62 255 76 145 88 8 156 95 29 150 245 193 10 22 84 131 125 16 232 77 35 188 132 22 107 20 200 82 169 175 12 226 15 76 248 166 59 123 90 219 119 90 174 13 210 250 151 205 187 88 141 54 231 15 171 169 73 228 85 65 168 59 180 233 234 53 117 38 79 143 29 130 25 83 208 175 1 219 42 22 172 64 18 238 151 185 241 202 235 174 206 90 177 201 68 85 155 12 148 65 74 236 173 214 102 107)
#f
())
#(49
"empty signature"
#vu8(49 50 51 52 48 48)
#vu8()
#f
())
#(50
"PKCS #1 v1.5 signature"
#vu8(49 50 51 52 48 48)
#vu8(127 182 78 241 13 233 107 52 86 250 10 245 69 114 89 94 69 50 134 18 218 210 6 65 25 203 198 114 189 124 110 185 144 40 237 121 165 248 19 120 206 141 230 73 149 161 180 76 63 107 14 245 208 50 76 227 212 130 128 89 145 38 226 59 167 191 97 203 40 79 82 189 96 118 151 48 201 215 170 189 142 121 113 231 35 27 88 139 205 136 17 153 76 158 87 167 61 66 75 15 191 122 137 177 204 226 34 83 175 98 242 150 53 153 62 244 210 205 12 239 192 26 66 28 201 149 7 161 228 224 117 47 196 103 203 192 85 234 102 121 186 0 167 24 176 211 155 141 228 83 8 147 162 178 137 204 8 57 96 69 25 138 138 186 140 101 157 229 99 32 255 42 176 175 240 194 170 15 88 163 219 231 242 171 21 68 195 70 114 219 16 190 248 57 99 138 146 181 78 120 150 138 15 158 167 127 160 55 72 244 0 71 60 213 169 3 180 75 19 65 53 221 175 237 23 79 201 44 74 232 183 172 50 39 48 214 209 238 15 119 112 98 108 235 249 15 15 20 74 63 102 83 83 48 186 79)
#f
())))
|
|
194991c71f30880c9514c185a44693e5eca9c3a431ce6460735dbaf031da6d7d | alephcloud/wai-cors | Cors.hs | -- ------------------------------------------------------ --
Copyright © 2014 AlephCloud Systems , Inc.
-- ------------------------------------------------------ --
# LANGUAGE UnicodeSyntax #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE RecordWildCards #
# LANGUAGE LambdaCase #
{-# LANGUAGE GADTs #-}
# LANGUAGE PatternGuards #
# LANGUAGE CPP #
| An implemenation of Cross - Origin resource sharing ( CORS ) for WAI that
-- aims to be compliant with <>.
--
-- The function 'simpleCors' enables support of simple cross-origin requests.
--
-- The following is an example how to enable support for simple cross-origin requests
for a < > application .
--
-- > {-# LANGUAGE UnicodeSyntax #-}
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > module Main
-- > ( main
-- > ) where
-- >
> import Network . Wai . Middleware . Cors
> import Web .
-- >
> main ∷ IO ( )
-- > main = scotty 8080 $ do
-- > middleware simpleCors
> matchAny " / " $ text " Success "
--
-- The result of following curl command will include the HTTP response header
@Access - Control - Allow - Origin : * @.
--
> curl -i :8888 -H ' Origin : 127.0.0.1 ' -v
--
module Network.Wai.Middleware.Cors
( Origin
, CorsResourcePolicy(..)
, simpleCorsResourcePolicy
, cors
, simpleCors
-- * Utils
, isSimple
, simpleResponseHeaders
, simpleHeaders
, simpleContentTypes
, simpleMethods
) where
#ifndef MIN_VESION_base
#define MIN_VESION_base(x,y,z) 1
#endif
#if ! MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.Monad.Error.Class
import Control.Monad.Trans.Except
#if ! MIN_VERSION_wai(2,0,0)
import Control.Monad.Trans.Resource
#endif
import qualified Data.Attoparsec.ByteString as AttoParsec
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as LB8
import qualified Data.CaseInsensitive as CI
import qualified Data.CharSet as CS
import Data.List (intersect, (\\), union)
import Data.Maybe (catMaybes)
import Data.Monoid.Unicode
import Data.String
import qualified Network.HTTP.Types as HTTP
import qualified Network.Wai as WAI
import Prelude.Unicode
import qualified Text.Parser.Char as P
import qualified Text.Parser.Combinators as P
#if MIN_VERSION_wai(2,0,0)
type ReqMonad = IO
#else
type ReqMonad = ResourceT IO
#endif
| Origins are expected to be formated as described in RFC 6454 ( section
6.2 ) . In particular the string @*@ is not a valid origin ( but the string
-- @null@ is).
--
type Origin = B8.ByteString
data CorsResourcePolicy = CorsResourcePolicy
{
| HTTP origins that are allowed in CORS requests .
--
-- A value of 'Nothing' indicates unrestricted cross-origin sharing and
results in @*@ as value for the @Access - Control - Allow - Origin@ HTTP
-- response header.
--
-- A value other than 'Nothing' is a tuple that consists of a list of
origins each with a Boolean flag that indicates if credentials are used
to access the resource via CORS .
--
Origins must be formated as described in RFC6454 ( section 6.2 ) . In
-- particular the string @*@ is not a valid origin (but the string @null@
-- is).
--
corsOrigins ∷ !(Maybe ([Origin], Bool))
| HTTP methods that are allowed in CORS requests .
--
, corsMethods ∷ ![HTTP.Method]
| Field names of HTTP request headers that are allowed in CORS requests .
-- Header names that are included in 'simpleHeaders', except for
-- @content-type@, are implicitely included an thus optional in this list.
--
, corsRequestHeaders ∷ ![HTTP.HeaderName]
-- | Field names of HTTP headers that are exposed on the client.
--
, corsExposedHeaders ∷ !(Maybe [HTTP.HeaderName])
-- | Number of seconds that the response may be cached by the client.
--
, corsMaxAge ∷ !(Maybe Int)
-- | If the resource is shared by multiple origins but
@Access - Control - Allow - Origin@ is not set to @*@ this may be set to
-- 'True'.
--
, corsVaryOrigin ∷ !Bool
-- | If this is 'True' and the request does not include an @Origin@ header
the response has HTTP status 400 ( bad request ) and the body contains
-- a short error message.
--
-- If this is 'False' and the request does not include an @Origin@ header
-- the request is passed on unchanged to the application.
--
-- /since version 0.2/
, corsRequireOrigin ∷ !Bool
-- | In the case that
--
-- * the request contains an @Origin@ header and
--
-- * the client does not conform with the CORS protocol
-- (/request is out of scope/)
--
-- then
--
-- * the request is passed on unchanged to the application if this field is
-- 'True' or
--
* an response with HTTP status 400 ( bad request ) and short
-- error message is returned if this field is 'False'.
--
-- /since version 0.2/
--
, corsIgnoreFailures ∷ !Bool
}
deriving (Show,Read,Eq,Ord)
-- | A 'CorsResourcePolicy' that supports /simple cross-origin requests/ as defined
-- in </>.
--
* The HTTP header @Access - Control - Allow - Origin@ is set to @*@.
--
* Request methods are constraint to /simple methods/ ( @GET@ , @HEAD@ , ) .
--
-- * Request headers are constraint to /simple request headers/
( @Accept@ , , @Content - Language@ , @Content - Type@ ) .
--
* If the request is a @POST@ request the content type is constraint to
-- /simple content types/
( @application / x - www - form - urlencoded@ , @multipart / form - data@ , @text / plain@ ) ,
--
-- * Only /simple response headers/ may be exposed on the client
( @Cache - Control@ , @Content - Language@ , @Content - Type@ , @Expires@ , @Last - Modified@ , @Pragma@ )
--
-- * The @Vary-Origin@ header is left unchanged (possibly unset).
--
-- * If the request doesn't include an @Origin@ header the request is passed unchanged to
-- the application.
--
-- * If the request includes an @Origin@ header but does not conform to the CORS
protocol ( /request is out of scope/ ) an response with HTTP status 400 ( bad request )
-- and a short error message is returned.
--
For /simple cross - origin requests/ a preflight request is not required . However , if
-- the client chooses to make a preflight request it is answered in accordance with
the policy for /simple cross - origin requests/.
--
simpleCorsResourcePolicy ∷ CorsResourcePolicy
simpleCorsResourcePolicy = CorsResourcePolicy
{ corsOrigins = Nothing
, corsMethods = simpleMethods
, corsRequestHeaders = []
, corsExposedHeaders = Nothing
, corsMaxAge = Nothing
, corsVaryOrigin = False
, corsRequireOrigin = False
, corsIgnoreFailures = False
}
-- | A Cross-Origin resource sharing (CORS) middleware.
--
-- The middleware is given a function that serves as a pattern to decide
-- whether a requested resource is available for CORS. If the match fails with
-- 'Nothing' the request is passed unmodified to the inner application.
--
-- The current version of this module does only aim at compliance with the CORS
-- protocol as specified in </>. In accordance with
-- that standard the role of the server side is to support the client to
-- enforce CORS restrictions. This module does not implement any enforcement of
-- authorization policies that are possibly implied by the
' CorsResourcePolicy ' . It is up to the inner WAI application to enforce such
-- policy and make sure that it is in accordance with the configuration of the
-- 'cors' middleware.
--
-- Matches are done as follows: @*@ matches every origin. For all other cases a
-- match succeeds if and only if the ASCII serializations (as described in
RCF6454 section 6.2 ) are equal .
--
-- The OPTIONS method may return options for resources that are not actually
-- available. In particular for preflight requests the implementation returns
for the HTTP response headers @Access - Control - Allow - Headers@ and
@Access - Control - Allow - Methods@ all values specified in the
-- 'CorsResourcePolicy' together with the respective values for simple requests
-- (except @content-type@). This does not imply that the application actually
-- supports the respective values are for the requested resource. Thus,
depending on the application , an actual request may still fail with 404 even
-- if the preflight request /supported/ the usage of the HTTP method with CORS.
--
-- The implementation does not distinguish between simple requests and requests
-- that require preflight. The client is free to omit a preflight request or do
-- a preflight request in cases when it wouldn't be required.
--
-- For application authors it is strongly recommended to take into account the
security considerations in section 6.3 of < > .
--
-- /TODO/
--
-- * We may consider adding optional enforcment aspects to this module: we may
-- check if a request respects our origin restrictions and we may check that a
-- CORS request respects the restrictions that we publish in the preflight
-- responses.
--
-- * Even though slightly out of scope we may (optionally) check if
-- host header matches the actual host of the resource, since clients
using CORS may expect this , since this check is recommended in
-- <>.
--
* We may consider integrating CORS policy handling more closely with the
-- handling of the source, for instance by integrating with 'ActionM' from
.
--
cors
∷ (WAI.Request → Maybe CorsResourcePolicy) -- ^ A value of 'Nothing' indicates that the resource is not available for CORS
→ WAI.Middleware
#if MIN_VERSION_wai(3,0,0)
cors policyPattern app r respond
#else
cors policyPattern app r
#endif
| Just policy ← policyPattern r = case hdrOrigin of
No origin header : requect request
Nothing → if corsRequireOrigin policy
then res $ corsFailure "Origin header is missing"
else runApp
-- Origin header: apply CORS policy to request
Just origin → applyCorsPolicy policy origin
| otherwise = runApp
where
#if MIN_VERSION_wai(3,0,0)
res = respond
runApp = app r respond
#else
res = return
runApp = app r
#endif
-- Lookup the HTTP origin request header
--
hdrOrigin = lookup "origin" (WAI.requestHeaders r)
-- Process a CORS request
--
applyCorsPolicy policy origin = do
-- The error continuation
let err e = if corsIgnoreFailures policy
then runApp
else res $ corsFailure (B8.pack e)
-- Match request origin with corsOrigins from policy
let respOrigin = case corsOrigins policy of
Nothing → return Nothing
Just (originList, withCreds) → if origin `elem` originList
then Right $ Just (origin, withCreds)
else Left $ "Unsupported origin: " ⊕ B8.unpack origin
case respOrigin of
Left e → err e
Right respOrigin → do
-- Determine headers that are common to actuall responses and preflight responses
let ch = commonCorsHeaders respOrigin (corsVaryOrigin policy)
case WAI.requestMethod r of
-- Preflight CORS request
"OPTIONS" → runExceptT (preflightHeaders policy) >>= \case
Left e → err e
Right headers → res $ WAI.responseLBS HTTP.ok200 (ch ⊕ headers) ""
-- Actual CORS request
#if MIN_VERSION_wai(3,0,0)
_ → addHeaders (ch ⊕ respCorsHeaders policy) app r respond
#else
_ → addHeaders (ch ⊕ respCorsHeaders policy) app r
#endif
-- Compute HTTP response headers for a preflight request
--
preflightHeaders ∷ (Functor μ, Monad μ) ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
preflightHeaders policy = concat <$> sequence
[ hdrReqMethod policy
, hdrRequestHeader policy
, hdrMaxAge policy
]
hdrMaxAge ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
hdrMaxAge policy = case corsMaxAge policy of
Nothing → return []
Just secs → return [("Access-Control-Max-Age", sshow secs)]
hdrReqMethod ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
hdrReqMethod policy = case lookup "Access-Control-Request-Method" (WAI.requestHeaders r) of
Nothing → throwError "Access-Control-Request-Method header is missing in CORS preflight request"
Just x → if x `elem` supportedMethods
then return [("Access-Control-Allow-Methods", hdrL supportedMethods)]
else throwError
$ "Method requested in Access-Control-Request-Method of CORS request is not supported; requested: "
⊕ B8.unpack x
⊕ "; supported are "
⊕ B8.unpack (hdrL supportedMethods)
⊕ "."
where
supportedMethods = corsMethods policy `union` simpleMethods
hdrRequestHeader ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
hdrRequestHeader policy = case lookup "Access-Control-Request-Headers" (WAI.requestHeaders r) of
Nothing → return []
Just hdrsBytes → do
hdrs ← either throwError return $ AttoParsec.parseOnly httpHeaderNameListParser hdrsBytes
if hdrs `isSubsetOf` supportedHeaders
then return [("Access-Control-Allow-Headers", hdrLI supportedHeaders)]
else throwError
$ "HTTP header requested in Access-Control-Request-Headers of CORS request is not supported; requested: "
⊕ B8.unpack (hdrLI hdrs)
⊕ "; supported are "
⊕ B8.unpack (hdrLI supportedHeaders)
⊕ "."
where
supportedHeaders = corsRequestHeaders policy `union` simpleHeadersWithoutContentType
simpleHeadersWithoutContentType = simpleHeaders \\ ["content-type"]
-- HTTP response headers that are common to normal and preflight CORS responses
--
commonCorsHeaders ∷ Maybe (Origin, Bool) → Bool → HTTP.ResponseHeaders
commonCorsHeaders Nothing True = [("Access-Control-Allow-Origin", "*"), ("Vary", "Origin")]
commonCorsHeaders Nothing False = [("Access-Control-Allow-Origin", "*")]
commonCorsHeaders (Just (o, False)) _ = [("Access-Control-Allow-Origin", o)]
commonCorsHeaders (Just (o, True)) _ = [("Access-Control-Allow-Origin", o), ("Access-Control-Allow-Credentials", "true")]
-- HTTP response headers that are only used with normal CORS responses
--
respCorsHeaders ∷ CorsResourcePolicy → HTTP.ResponseHeaders
respCorsHeaders policy = catMaybes
[ fmap (\x → ("Access-Control-Expose-Headers", hdrLI x)) (corsExposedHeaders policy)
]
-- | A CORS middleware that supports simple cross-origin requests for all
-- resources.
--
-- This middleware does not check if the resource corresponds to the
-- restrictions for simple requests. This is in accordance with
-- </>. The client (user-agent) is supposed to
enforcement CORS policy . The role of the server is to provide the client
-- with the respective policy constraints.
--
-- It is out of the scope of the this module if the server chooses to
-- enforce rules on its resources in relation to CORS policy itself.
--
simpleCors ∷ WAI.Middleware
simpleCors = cors (const $ Just simpleCorsResourcePolicy)
-- -------------------------------------------------------------------------- --
-- Definition from Standards
-- | Simple HTTP response headers as defined in </>
--
simpleResponseHeaders ∷ [HTTP.HeaderName]
simpleResponseHeaders =
[ "Cache-Control"
, "Content-Language"
, "Content-Type"
, "Expires"
, "Last-Modified"
, "Pragma"
]
simpleHeaders ∷ [HTTP.HeaderName]
simpleHeaders =
[ "Accept"
, "Accept-Language"
, "Content-Language"
, "Content-Type"
]
simpleContentTypes ∷ [CI.CI B8.ByteString]
simpleContentTypes =
[ "application/x-www-form-urlencoded"
, "multipart/form-data"
, "text/plain"
]
-- | Simple HTTP methods as defined in </>
--
simpleMethods ∷ [HTTP.Method]
simpleMethods =
[ "GET"
, "HEAD"
, "POST"
]
isSimple ∷ HTTP.Method → HTTP.RequestHeaders → Bool
isSimple method headers
= method `elem` simpleMethods
∧ map fst headers `isSubsetOf` simpleHeaders
∧ case (method, lookup "content-type" headers) of
("POST", Just x) → CI.mk x `elem` simpleContentTypes
_ → True
| Valid characters for HTTP header names according to RFC2616 ( section 4.2 )
--
httpHeaderNameCharSet ∷ CS.CharSet
httpHeaderNameCharSet = CS.range (toEnum 33) (toEnum 126) CS.\\ CS.fromList "()<>@,;:\\\"/[]?={}"
httpHeaderNameParser ∷ P.CharParsing μ ⇒ μ HTTP.HeaderName
httpHeaderNameParser = fromString <$> P.some (P.oneOfSet httpHeaderNameCharSet) P.<?> "HTTP Header Name"
-- -------------------------------------------------------------------------- --
-- Generic Tools
httpHeaderNameListParser ∷ P.CharParsing μ ⇒ μ [HTTP.HeaderName]
httpHeaderNameListParser = P.spaces *> P.sepBy (httpHeaderNameParser <* P.spaces) (P.char ',') <* P.spaces
sshow ∷ (IsString α, Show β) ⇒ β → α
sshow = fromString ∘ show
isSubsetOf ∷ Eq α ⇒ [α] → [α] → Bool
isSubsetOf l1 l2 = intersect l1 l2 ≡ l1
-- | Add HTTP headers to a WAI response
--
#if MIN_VERSION_wai(3,0,0)
addHeaders ∷ HTTP.ResponseHeaders → WAI.Middleware
addHeaders hdrs app req respond = app req $ \response → do
let (st, headers, streamHandle) = WAI.responseToStream response
streamHandle $ \streamBody →
respond $ WAI.responseStream st (headers ⊕ hdrs) streamBody
#elif MIN_VERSION_wai(2,0,0)
addHeaders ∷ HTTP.ResponseHeaders → WAI.Middleware
addHeaders hdrs app req = do
(st, headers, src) ← WAI.responseToSource <$> app req
WAI.responseSource st (headers ⊕ hdrs) <$> src return
#else
addHeaders ∷ HTTP.ResponseHeaders → WAI.Middleware
addHeaders hdrs app req = do
(st, headers, src) ← WAI.responseSource <$> app req
return $ WAI.ResponseSource st (headers ⊕ hdrs) src
#endif
-- | Format a list of 'HTTP.HeaderName's such that it can be used as
-- an HTTP header value
--
hdrLI ∷ [HTTP.HeaderName] → B8.ByteString
hdrLI l = B8.intercalate ", " (map CI.original l)
-- | Format a list of 'B8.ByteString's such that it can be used as
-- an HTTP header value
--
hdrL ∷ [B8.ByteString] → B8.ByteString
hdrL l = B8.intercalate ", " l
corsFailure
∷ B8.ByteString -- ^ body
→ WAI.Response
corsFailure msg = WAI.responseLBS HTTP.status400 [("Content-Type", "text/html; charset-utf-8")] (LB8.fromStrict msg)
| null | https://raw.githubusercontent.com/alephcloud/wai-cors/069b7ecf63812223e589d78ed6f2c398c383b3f9/src/Network/Wai/Middleware/Cors.hs | haskell | ------------------------------------------------------ --
------------------------------------------------------ --
# LANGUAGE OverloadedStrings #
# LANGUAGE GADTs #
aims to be compliant with <>.
The function 'simpleCors' enables support of simple cross-origin requests.
The following is an example how to enable support for simple cross-origin requests
> {-# LANGUAGE UnicodeSyntax #-}
> {-# LANGUAGE OverloadedStrings #-}
>
> module Main
> ( main
> ) where
>
>
> main = scotty 8080 $ do
> middleware simpleCors
The result of following curl command will include the HTTP response header
* Utils
@null@ is).
A value of 'Nothing' indicates unrestricted cross-origin sharing and
response header.
A value other than 'Nothing' is a tuple that consists of a list of
particular the string @*@ is not a valid origin (but the string @null@
is).
Header names that are included in 'simpleHeaders', except for
@content-type@, are implicitely included an thus optional in this list.
| Field names of HTTP headers that are exposed on the client.
| Number of seconds that the response may be cached by the client.
| If the resource is shared by multiple origins but
'True'.
| If this is 'True' and the request does not include an @Origin@ header
a short error message.
If this is 'False' and the request does not include an @Origin@ header
the request is passed on unchanged to the application.
/since version 0.2/
| In the case that
* the request contains an @Origin@ header and
* the client does not conform with the CORS protocol
(/request is out of scope/)
then
* the request is passed on unchanged to the application if this field is
'True' or
error message is returned if this field is 'False'.
/since version 0.2/
| A 'CorsResourcePolicy' that supports /simple cross-origin requests/ as defined
in </>.
* Request headers are constraint to /simple request headers/
/simple content types/
* Only /simple response headers/ may be exposed on the client
* The @Vary-Origin@ header is left unchanged (possibly unset).
* If the request doesn't include an @Origin@ header the request is passed unchanged to
the application.
* If the request includes an @Origin@ header but does not conform to the CORS
and a short error message is returned.
the client chooses to make a preflight request it is answered in accordance with
| A Cross-Origin resource sharing (CORS) middleware.
The middleware is given a function that serves as a pattern to decide
whether a requested resource is available for CORS. If the match fails with
'Nothing' the request is passed unmodified to the inner application.
The current version of this module does only aim at compliance with the CORS
protocol as specified in </>. In accordance with
that standard the role of the server side is to support the client to
enforce CORS restrictions. This module does not implement any enforcement of
authorization policies that are possibly implied by the
policy and make sure that it is in accordance with the configuration of the
'cors' middleware.
Matches are done as follows: @*@ matches every origin. For all other cases a
match succeeds if and only if the ASCII serializations (as described in
The OPTIONS method may return options for resources that are not actually
available. In particular for preflight requests the implementation returns
'CorsResourcePolicy' together with the respective values for simple requests
(except @content-type@). This does not imply that the application actually
supports the respective values are for the requested resource. Thus,
if the preflight request /supported/ the usage of the HTTP method with CORS.
The implementation does not distinguish between simple requests and requests
that require preflight. The client is free to omit a preflight request or do
a preflight request in cases when it wouldn't be required.
For application authors it is strongly recommended to take into account the
/TODO/
* We may consider adding optional enforcment aspects to this module: we may
check if a request respects our origin restrictions and we may check that a
CORS request respects the restrictions that we publish in the preflight
responses.
* Even though slightly out of scope we may (optionally) check if
host header matches the actual host of the resource, since clients
<>.
handling of the source, for instance by integrating with 'ActionM' from
^ A value of 'Nothing' indicates that the resource is not available for CORS
Origin header: apply CORS policy to request
Lookup the HTTP origin request header
Process a CORS request
The error continuation
Match request origin with corsOrigins from policy
Determine headers that are common to actuall responses and preflight responses
Preflight CORS request
Actual CORS request
Compute HTTP response headers for a preflight request
HTTP response headers that are common to normal and preflight CORS responses
HTTP response headers that are only used with normal CORS responses
| A CORS middleware that supports simple cross-origin requests for all
resources.
This middleware does not check if the resource corresponds to the
restrictions for simple requests. This is in accordance with
</>. The client (user-agent) is supposed to
with the respective policy constraints.
It is out of the scope of the this module if the server chooses to
enforce rules on its resources in relation to CORS policy itself.
-------------------------------------------------------------------------- --
Definition from Standards
| Simple HTTP response headers as defined in </>
| Simple HTTP methods as defined in </>
-------------------------------------------------------------------------- --
Generic Tools
| Add HTTP headers to a WAI response
| Format a list of 'HTTP.HeaderName's such that it can be used as
an HTTP header value
| Format a list of 'B8.ByteString's such that it can be used as
an HTTP header value
^ body | Copyright © 2014 AlephCloud Systems , Inc.
# LANGUAGE UnicodeSyntax #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE RecordWildCards #
# LANGUAGE LambdaCase #
# LANGUAGE PatternGuards #
# LANGUAGE CPP #
| An implemenation of Cross - Origin resource sharing ( CORS ) for WAI that
for a < > application .
> import Network . Wai . Middleware . Cors
> import Web .
> main ∷ IO ( )
> matchAny " / " $ text " Success "
@Access - Control - Allow - Origin : * @.
> curl -i :8888 -H ' Origin : 127.0.0.1 ' -v
module Network.Wai.Middleware.Cors
( Origin
, CorsResourcePolicy(..)
, simpleCorsResourcePolicy
, cors
, simpleCors
, isSimple
, simpleResponseHeaders
, simpleHeaders
, simpleContentTypes
, simpleMethods
) where
#ifndef MIN_VESION_base
#define MIN_VESION_base(x,y,z) 1
#endif
#if ! MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.Monad.Error.Class
import Control.Monad.Trans.Except
#if ! MIN_VERSION_wai(2,0,0)
import Control.Monad.Trans.Resource
#endif
import qualified Data.Attoparsec.ByteString as AttoParsec
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as LB8
import qualified Data.CaseInsensitive as CI
import qualified Data.CharSet as CS
import Data.List (intersect, (\\), union)
import Data.Maybe (catMaybes)
import Data.Monoid.Unicode
import Data.String
import qualified Network.HTTP.Types as HTTP
import qualified Network.Wai as WAI
import Prelude.Unicode
import qualified Text.Parser.Char as P
import qualified Text.Parser.Combinators as P
#if MIN_VERSION_wai(2,0,0)
type ReqMonad = IO
#else
type ReqMonad = ResourceT IO
#endif
| Origins are expected to be formated as described in RFC 6454 ( section
6.2 ) . In particular the string @*@ is not a valid origin ( but the string
type Origin = B8.ByteString
data CorsResourcePolicy = CorsResourcePolicy
{
| HTTP origins that are allowed in CORS requests .
results in @*@ as value for the @Access - Control - Allow - Origin@ HTTP
origins each with a Boolean flag that indicates if credentials are used
to access the resource via CORS .
Origins must be formated as described in RFC6454 ( section 6.2 ) . In
corsOrigins ∷ !(Maybe ([Origin], Bool))
| HTTP methods that are allowed in CORS requests .
, corsMethods ∷ ![HTTP.Method]
| Field names of HTTP request headers that are allowed in CORS requests .
, corsRequestHeaders ∷ ![HTTP.HeaderName]
, corsExposedHeaders ∷ !(Maybe [HTTP.HeaderName])
, corsMaxAge ∷ !(Maybe Int)
@Access - Control - Allow - Origin@ is not set to @*@ this may be set to
, corsVaryOrigin ∷ !Bool
the response has HTTP status 400 ( bad request ) and the body contains
, corsRequireOrigin ∷ !Bool
* an response with HTTP status 400 ( bad request ) and short
, corsIgnoreFailures ∷ !Bool
}
deriving (Show,Read,Eq,Ord)
* The HTTP header @Access - Control - Allow - Origin@ is set to @*@.
* Request methods are constraint to /simple methods/ ( @GET@ , @HEAD@ , ) .
( @Accept@ , , @Content - Language@ , @Content - Type@ ) .
* If the request is a @POST@ request the content type is constraint to
( @application / x - www - form - urlencoded@ , @multipart / form - data@ , @text / plain@ ) ,
( @Cache - Control@ , @Content - Language@ , @Content - Type@ , @Expires@ , @Last - Modified@ , @Pragma@ )
protocol ( /request is out of scope/ ) an response with HTTP status 400 ( bad request )
For /simple cross - origin requests/ a preflight request is not required . However , if
the policy for /simple cross - origin requests/.
simpleCorsResourcePolicy ∷ CorsResourcePolicy
simpleCorsResourcePolicy = CorsResourcePolicy
{ corsOrigins = Nothing
, corsMethods = simpleMethods
, corsRequestHeaders = []
, corsExposedHeaders = Nothing
, corsMaxAge = Nothing
, corsVaryOrigin = False
, corsRequireOrigin = False
, corsIgnoreFailures = False
}
' CorsResourcePolicy ' . It is up to the inner WAI application to enforce such
RCF6454 section 6.2 ) are equal .
for the HTTP response headers @Access - Control - Allow - Headers@ and
@Access - Control - Allow - Methods@ all values specified in the
depending on the application , an actual request may still fail with 404 even
security considerations in section 6.3 of < > .
using CORS may expect this , since this check is recommended in
* We may consider integrating CORS policy handling more closely with the
.
cors
→ WAI.Middleware
#if MIN_VERSION_wai(3,0,0)
cors policyPattern app r respond
#else
cors policyPattern app r
#endif
| Just policy ← policyPattern r = case hdrOrigin of
No origin header : requect request
Nothing → if corsRequireOrigin policy
then res $ corsFailure "Origin header is missing"
else runApp
Just origin → applyCorsPolicy policy origin
| otherwise = runApp
where
#if MIN_VERSION_wai(3,0,0)
res = respond
runApp = app r respond
#else
res = return
runApp = app r
#endif
hdrOrigin = lookup "origin" (WAI.requestHeaders r)
applyCorsPolicy policy origin = do
let err e = if corsIgnoreFailures policy
then runApp
else res $ corsFailure (B8.pack e)
let respOrigin = case corsOrigins policy of
Nothing → return Nothing
Just (originList, withCreds) → if origin `elem` originList
then Right $ Just (origin, withCreds)
else Left $ "Unsupported origin: " ⊕ B8.unpack origin
case respOrigin of
Left e → err e
Right respOrigin → do
let ch = commonCorsHeaders respOrigin (corsVaryOrigin policy)
case WAI.requestMethod r of
"OPTIONS" → runExceptT (preflightHeaders policy) >>= \case
Left e → err e
Right headers → res $ WAI.responseLBS HTTP.ok200 (ch ⊕ headers) ""
#if MIN_VERSION_wai(3,0,0)
_ → addHeaders (ch ⊕ respCorsHeaders policy) app r respond
#else
_ → addHeaders (ch ⊕ respCorsHeaders policy) app r
#endif
preflightHeaders ∷ (Functor μ, Monad μ) ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
preflightHeaders policy = concat <$> sequence
[ hdrReqMethod policy
, hdrRequestHeader policy
, hdrMaxAge policy
]
hdrMaxAge ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
hdrMaxAge policy = case corsMaxAge policy of
Nothing → return []
Just secs → return [("Access-Control-Max-Age", sshow secs)]
hdrReqMethod ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
hdrReqMethod policy = case lookup "Access-Control-Request-Method" (WAI.requestHeaders r) of
Nothing → throwError "Access-Control-Request-Method header is missing in CORS preflight request"
Just x → if x `elem` supportedMethods
then return [("Access-Control-Allow-Methods", hdrL supportedMethods)]
else throwError
$ "Method requested in Access-Control-Request-Method of CORS request is not supported; requested: "
⊕ B8.unpack x
⊕ "; supported are "
⊕ B8.unpack (hdrL supportedMethods)
⊕ "."
where
supportedMethods = corsMethods policy `union` simpleMethods
hdrRequestHeader ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
hdrRequestHeader policy = case lookup "Access-Control-Request-Headers" (WAI.requestHeaders r) of
Nothing → return []
Just hdrsBytes → do
hdrs ← either throwError return $ AttoParsec.parseOnly httpHeaderNameListParser hdrsBytes
if hdrs `isSubsetOf` supportedHeaders
then return [("Access-Control-Allow-Headers", hdrLI supportedHeaders)]
else throwError
$ "HTTP header requested in Access-Control-Request-Headers of CORS request is not supported; requested: "
⊕ B8.unpack (hdrLI hdrs)
⊕ "; supported are "
⊕ B8.unpack (hdrLI supportedHeaders)
⊕ "."
where
supportedHeaders = corsRequestHeaders policy `union` simpleHeadersWithoutContentType
simpleHeadersWithoutContentType = simpleHeaders \\ ["content-type"]
commonCorsHeaders ∷ Maybe (Origin, Bool) → Bool → HTTP.ResponseHeaders
commonCorsHeaders Nothing True = [("Access-Control-Allow-Origin", "*"), ("Vary", "Origin")]
commonCorsHeaders Nothing False = [("Access-Control-Allow-Origin", "*")]
commonCorsHeaders (Just (o, False)) _ = [("Access-Control-Allow-Origin", o)]
commonCorsHeaders (Just (o, True)) _ = [("Access-Control-Allow-Origin", o), ("Access-Control-Allow-Credentials", "true")]
respCorsHeaders ∷ CorsResourcePolicy → HTTP.ResponseHeaders
respCorsHeaders policy = catMaybes
[ fmap (\x → ("Access-Control-Expose-Headers", hdrLI x)) (corsExposedHeaders policy)
]
enforcement CORS policy . The role of the server is to provide the client
simpleCors ∷ WAI.Middleware
simpleCors = cors (const $ Just simpleCorsResourcePolicy)
simpleResponseHeaders ∷ [HTTP.HeaderName]
simpleResponseHeaders =
[ "Cache-Control"
, "Content-Language"
, "Content-Type"
, "Expires"
, "Last-Modified"
, "Pragma"
]
simpleHeaders ∷ [HTTP.HeaderName]
simpleHeaders =
[ "Accept"
, "Accept-Language"
, "Content-Language"
, "Content-Type"
]
simpleContentTypes ∷ [CI.CI B8.ByteString]
simpleContentTypes =
[ "application/x-www-form-urlencoded"
, "multipart/form-data"
, "text/plain"
]
simpleMethods ∷ [HTTP.Method]
simpleMethods =
[ "GET"
, "HEAD"
, "POST"
]
isSimple ∷ HTTP.Method → HTTP.RequestHeaders → Bool
isSimple method headers
= method `elem` simpleMethods
∧ map fst headers `isSubsetOf` simpleHeaders
∧ case (method, lookup "content-type" headers) of
("POST", Just x) → CI.mk x `elem` simpleContentTypes
_ → True
| Valid characters for HTTP header names according to RFC2616 ( section 4.2 )
httpHeaderNameCharSet ∷ CS.CharSet
httpHeaderNameCharSet = CS.range (toEnum 33) (toEnum 126) CS.\\ CS.fromList "()<>@,;:\\\"/[]?={}"
httpHeaderNameParser ∷ P.CharParsing μ ⇒ μ HTTP.HeaderName
httpHeaderNameParser = fromString <$> P.some (P.oneOfSet httpHeaderNameCharSet) P.<?> "HTTP Header Name"
httpHeaderNameListParser ∷ P.CharParsing μ ⇒ μ [HTTP.HeaderName]
httpHeaderNameListParser = P.spaces *> P.sepBy (httpHeaderNameParser <* P.spaces) (P.char ',') <* P.spaces
sshow ∷ (IsString α, Show β) ⇒ β → α
sshow = fromString ∘ show
isSubsetOf ∷ Eq α ⇒ [α] → [α] → Bool
isSubsetOf l1 l2 = intersect l1 l2 ≡ l1
#if MIN_VERSION_wai(3,0,0)
addHeaders ∷ HTTP.ResponseHeaders → WAI.Middleware
addHeaders hdrs app req respond = app req $ \response → do
let (st, headers, streamHandle) = WAI.responseToStream response
streamHandle $ \streamBody →
respond $ WAI.responseStream st (headers ⊕ hdrs) streamBody
#elif MIN_VERSION_wai(2,0,0)
addHeaders ∷ HTTP.ResponseHeaders → WAI.Middleware
addHeaders hdrs app req = do
(st, headers, src) ← WAI.responseToSource <$> app req
WAI.responseSource st (headers ⊕ hdrs) <$> src return
#else
addHeaders ∷ HTTP.ResponseHeaders → WAI.Middleware
addHeaders hdrs app req = do
(st, headers, src) ← WAI.responseSource <$> app req
return $ WAI.ResponseSource st (headers ⊕ hdrs) src
#endif
hdrLI ∷ [HTTP.HeaderName] → B8.ByteString
hdrLI l = B8.intercalate ", " (map CI.original l)
hdrL ∷ [B8.ByteString] → B8.ByteString
hdrL l = B8.intercalate ", " l
corsFailure
→ WAI.Response
corsFailure msg = WAI.responseLBS HTTP.status400 [("Content-Type", "text/html; charset-utf-8")] (LB8.fromStrict msg)
|
d687b55b65834b687f0ee9cebc11120e9b6f0d7d2baba21b1266eb5e3cb0ae08 | opencog/learn | launch-mst-parser.scm | ;
; launch-mst-parser.scm
;
; Run the cogserver, needed for the language-learning disjunct
; counting pipeline. Starts the cogserver, opens the database,
loads the database ( which can take an hour or more ! )
;
(use-modules (opencog) (opencog persist) (opencog persist-sql))
(use-modules (opencog cogserver))
(use-modules (opencog nlp))
(use-modules (system repl common))
(use-modules (system repl server))
(use-modules (opencog logger))
(use-modules (opencog matrix))
(add-to-load-path ".")
(load "utilities.scm")
; Get the database connection and language details
(define database-uri (get-connection-uri))
(define language (get-lang))
; set the prompt for the given language
(repl-default-option-set! 'prompt (string-append "scheme@("
language "-mst)> "))
; Start the cogserver with configs for the given language
(start-cogserver (string-append "config/opencog-mst-" language ".conf"))
; Open the database.
(sql-open database-uri)
NOTE : This script assumes that has
; already stored the mutual information for the pairs after
; an observe pass over the same sentences to be parsed.
; Load up the words
(display "Fetching all words from database. This may take a few minutes.\n")
(fetch-all-words)
Load up the word - pairs -- this can take over half an hour !
(display "Fetching all word-pairs. This may take a few minutes.\n")
; The object which will be providing pair-counts for us.
; We can also do MST parsing with other kinds of pair-count objects,
; for example, the clique-pairs, or the distance-pairs.
(define pair-obj (make-any-link-api))
;(define pair-obj (make-clique-pair-api))
(define star-obj (add-pair-stars pair-obj))
(pair-obj 'fetch-pairs)
Print the sql stats
(sql-stats)
; Clear the sql cache and the stats counters
(sql-clear-cache)
(sql-clear-stats)
;(print-matrix-summary-report star-obj)
(display "Done fetching pairs.\n")
| null | https://raw.githubusercontent.com/opencog/learn/c599c856f59c1815b92520bee043c588d0d1ebf9/attic/run-poc/misc/launch-mst-parser.scm | scheme |
launch-mst-parser.scm
Run the cogserver, needed for the language-learning disjunct
counting pipeline. Starts the cogserver, opens the database,
Get the database connection and language details
set the prompt for the given language
Start the cogserver with configs for the given language
Open the database.
already stored the mutual information for the pairs after
an observe pass over the same sentences to be parsed.
Load up the words
The object which will be providing pair-counts for us.
We can also do MST parsing with other kinds of pair-count objects,
for example, the clique-pairs, or the distance-pairs.
(define pair-obj (make-clique-pair-api))
Clear the sql cache and the stats counters
(print-matrix-summary-report star-obj) | loads the database ( which can take an hour or more ! )
(use-modules (opencog) (opencog persist) (opencog persist-sql))
(use-modules (opencog cogserver))
(use-modules (opencog nlp))
(use-modules (system repl common))
(use-modules (system repl server))
(use-modules (opencog logger))
(use-modules (opencog matrix))
(add-to-load-path ".")
(load "utilities.scm")
(define database-uri (get-connection-uri))
(define language (get-lang))
(repl-default-option-set! 'prompt (string-append "scheme@("
language "-mst)> "))
(start-cogserver (string-append "config/opencog-mst-" language ".conf"))
(sql-open database-uri)
NOTE : This script assumes that has
(display "Fetching all words from database. This may take a few minutes.\n")
(fetch-all-words)
Load up the word - pairs -- this can take over half an hour !
(display "Fetching all word-pairs. This may take a few minutes.\n")
(define pair-obj (make-any-link-api))
(define star-obj (add-pair-stars pair-obj))
(pair-obj 'fetch-pairs)
Print the sql stats
(sql-stats)
(sql-clear-cache)
(sql-clear-stats)
(display "Done fetching pairs.\n")
|
835fcb744cd636902548fe7174a828e180273a9dceba364d9fe030445bc92818 | metosin/sormilla | math_test.clj | (ns sormilla.math-test
(:require [midje.sweet :refer :all]
[sormilla.math :refer :all]))
(facts "avg"
(avg [1.0 1.0 1.0]) => (roughly 1.0)
(avg [1.0 2.0 3.0]) => (roughly 2.0))
(facts "lin-scale"
(let [s (lin-scale [0.0 1.0] [10.0 20.0])]
(s 0.0) => (roughly 10.0)
(s 0.5) => (roughly 15.0)
(s 1.0) => (roughly 20.0)))
(facts "bound"
((bound 0.0 1.0) 0.5) => (roughly 0.5)
((bound 0.0 1.0) -0.5) => (roughly 0.0)
((bound 0.0 1.0) 1.5) => (roughly 1.0))
(facts "abs"
(abs 1.0) => (roughly 1.0)
(abs -1.0) => (roughly 1.0))
(facts "clip-to-zero"
(let [c (clip-to-zero 0.2)]
(c +0.3) => (roughly +0.1)
(c +0.2) => (roughly +0.0)
(c +0.1) => (roughly 0.0)
(c +0.0) => (roughly 0.0)
(c -0.1) => (roughly 0.0)
(c -0.2) => (roughly -0.0)
(c -0.3) => (roughly -0.1)))
(fact "averager"
(let [a (averager 3)]
(a 1.0) => (roughly (avg [1.0 0.0 0.0]))
(a 2.0) => (roughly (avg [2.0 1.0 0.0]))
(a 3.0) => (roughly (avg [3.0 2.0 1.0]))
(a 4.0) => (roughly (avg [4.0 3.0 2.0]))
(a 5.0) => (roughly (avg [5.0 4.0 3.0])))) | null | https://raw.githubusercontent.com/metosin/sormilla/e50930930c41f64272f06c4bd02a4e3ab58e923f/test/sormilla/math_test.clj | clojure | (ns sormilla.math-test
(:require [midje.sweet :refer :all]
[sormilla.math :refer :all]))
(facts "avg"
(avg [1.0 1.0 1.0]) => (roughly 1.0)
(avg [1.0 2.0 3.0]) => (roughly 2.0))
(facts "lin-scale"
(let [s (lin-scale [0.0 1.0] [10.0 20.0])]
(s 0.0) => (roughly 10.0)
(s 0.5) => (roughly 15.0)
(s 1.0) => (roughly 20.0)))
(facts "bound"
((bound 0.0 1.0) 0.5) => (roughly 0.5)
((bound 0.0 1.0) -0.5) => (roughly 0.0)
((bound 0.0 1.0) 1.5) => (roughly 1.0))
(facts "abs"
(abs 1.0) => (roughly 1.0)
(abs -1.0) => (roughly 1.0))
(facts "clip-to-zero"
(let [c (clip-to-zero 0.2)]
(c +0.3) => (roughly +0.1)
(c +0.2) => (roughly +0.0)
(c +0.1) => (roughly 0.0)
(c +0.0) => (roughly 0.0)
(c -0.1) => (roughly 0.0)
(c -0.2) => (roughly -0.0)
(c -0.3) => (roughly -0.1)))
(fact "averager"
(let [a (averager 3)]
(a 1.0) => (roughly (avg [1.0 0.0 0.0]))
(a 2.0) => (roughly (avg [2.0 1.0 0.0]))
(a 3.0) => (roughly (avg [3.0 2.0 1.0]))
(a 4.0) => (roughly (avg [4.0 3.0 2.0]))
(a 5.0) => (roughly (avg [5.0 4.0 3.0])))) |
|
95513af55c079527926e5f8b816528a1344bac7349386e7b915c1a92db22e3fb | lfe/rebar3_lfe | rebar3_lfe.erl | -module(rebar3_lfe).
-export([init/1]).
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
rebar_api:debug("Intializing rebar3_lfe plugin ...", []),
Commands = [ fun rebar3_lfe_prv_clean:init/1,
fun rebar3_lfe_prv_clean_all:init/1,
fun rebar3_lfe_prv_clean_build:init/1,
fun rebar3_lfe_prv_clean_cache:init/1,
fun rebar3_lfe_prv_compile:init/1,
fun rebar3_lfe_prv_confabulate:init/1,
fun rebar3_lfe_prv_escriptize:init/1,
fun rebar3_lfe_prv_ltest:init/1,
fun rebar3_lfe_prv_release:init/1,
fun rebar3_lfe_prv_repl:init/1,
fun rebar3_lfe_prv_run:init/1,
fun rebar3_lfe_prv_run_escript:init/1,
fun rebar3_lfe_prv_run_release:init/1,
fun rebar3_lfe_prv_versions:init/1
],
FoldFun = fun(F, {ok, StateAcc}) -> F(StateAcc) end,
lists:foldl(FoldFun, {ok, State}, Commands).
%% Useful for debugging new plugins:
%%
%% {ok, State} = rebar3_lfe:init(rebar_state:new()).
rebar3_lfe_prv_ltest : do(State ) .
%% rebar_state:command_parsed_args(rebar_state:new()).
%% rebar_prv_eunit:eunit_opts(rebar_state:new()).
| null | https://raw.githubusercontent.com/lfe/rebar3_lfe/9b929daf74d95e3ed048878569ced99eded0b2a7/src/rebar3_lfe.erl | erlang | Useful for debugging new plugins:
{ok, State} = rebar3_lfe:init(rebar_state:new()).
rebar_state:command_parsed_args(rebar_state:new()).
rebar_prv_eunit:eunit_opts(rebar_state:new()). | -module(rebar3_lfe).
-export([init/1]).
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
rebar_api:debug("Intializing rebar3_lfe plugin ...", []),
Commands = [ fun rebar3_lfe_prv_clean:init/1,
fun rebar3_lfe_prv_clean_all:init/1,
fun rebar3_lfe_prv_clean_build:init/1,
fun rebar3_lfe_prv_clean_cache:init/1,
fun rebar3_lfe_prv_compile:init/1,
fun rebar3_lfe_prv_confabulate:init/1,
fun rebar3_lfe_prv_escriptize:init/1,
fun rebar3_lfe_prv_ltest:init/1,
fun rebar3_lfe_prv_release:init/1,
fun rebar3_lfe_prv_repl:init/1,
fun rebar3_lfe_prv_run:init/1,
fun rebar3_lfe_prv_run_escript:init/1,
fun rebar3_lfe_prv_run_release:init/1,
fun rebar3_lfe_prv_versions:init/1
],
FoldFun = fun(F, {ok, StateAcc}) -> F(StateAcc) end,
lists:foldl(FoldFun, {ok, State}, Commands).
rebar3_lfe_prv_ltest : do(State ) .
|
77896ac6ca7eb3e0b70082b9cbdad480b6e0f76521349c72155aa32f823c8de1 | spartango/CS153 | mips.ml | This structure defines the abstract syntax for MIPS assembly
* language that we will be using . It should be fairly self-
* explanatory .
*
* IMPORTANT : do not use registers R1 , R26 , or R27 as these
* are reserved by the assembler and operating system . See
* page A-24 of the MIPS documentation for details on the
* register conventions .
* language that we will be using. It should be fairly self-
* explanatory.
*
* IMPORTANT: do not use registers R1, R26, or R27 as these
* are reserved by the assembler and operating system. See
* page A-24 of the MIPS documentation for details on the
* register conventions.
*)
type label = string
type reg = R0
| R1 (* DO NOT USE ME: assembler temp *)
| R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9
| R10 | R11 | R12 | R13 | R14 | R15 | R16 | R17 | R18 | R19
| R20 | R21 | R22 | R23 | R24 | R25
| R26 | R27 (* DO NOT USE ME: reserved for OS *)
| R28
| R29 | R30 |R31 (* used for special purposes... *)
type operand = Reg of reg | Immed of Word32.word
type inst =
Add of reg * reg * operand
| And of reg * reg * operand
| Div of reg * reg * reg
| Mul of reg * reg * reg
| Nor of reg * reg * reg
| Or of reg * reg * operand
| Sll of reg * reg * operand
| Sra of reg * reg * operand
| Srl of reg * reg * operand
| Sub of reg * reg * reg
| Xor of reg * reg * operand
| Li of reg * Word32.word
| Slt of reg * reg * operand
| Sltu of reg * reg * operand
| Sge of reg * reg * reg
| Sgeu of reg * reg * reg
| Sgt of reg * reg * reg
| Sgtu of reg * reg * reg
| Sle of reg * reg * reg
| Sleu of reg * reg * reg
| Seq of reg * reg * reg
| Sne of reg * reg * reg
| B of label
| Beq of reg * reg * label
| Bgez of reg * label
| Bgtz of reg * label
| Blez of reg * label
| Bltz of reg * label
| Bne of reg * reg * label
| J of label
| Jal of label
| Jr of reg
| Jalr of reg * reg
| La of reg * label
| Lb of reg * reg * Word32.word
| Lbu of reg * reg * Word32.word
| Lh of reg * reg * Word32.word
| Lhu of reg * reg * Word32.word
| Lw of reg * reg * Word32.word
| Sb of reg * reg * Word32.word
| Sh of reg * reg * Word32.word
| Sw of reg * reg * Word32.word
| Label of label
The functions below are used to convert MIPS instructions
* into strings , suitable for output to an assembly file .
* into strings, suitable for output to an assembly file. *)
let reg2string (r:reg):string =
match r with
R0 -> "$0" | R1 -> "$1" | R2 -> "$2" | R3 -> "$3" | R4 -> "$4"
| R5 -> "$5" | R6 -> "$6" | R7 -> "$7" | R8 -> "$8" | R9 -> "$9"
| R10 -> "$10" | R11 -> "$11" | R12 -> "$12" | R13 -> "$13"
| R14 -> "$14" | R15 -> "$15" | R16 -> "$16"
| R17 -> "$17" | R18 -> "$18" | R19 -> "$19" | R20 -> "$20"
| R21 -> "$21" | R22 -> "$22" | R23 -> "$23" | R24 -> "$24"
| R25 -> "$25" | R26 -> "$26" | R27 -> "$27" | R28 -> "$28"
| R29 -> "$29" | R30 -> "$30" | R31 -> "$31"
type fmt = R of reg | L of label | W of Word32.word
let fmt2string(f:fmt):string =
match f with
R r -> reg2string r
| W w -> (Word32.toStringX w)
| L x -> x
let i2s (i:string) (x:fmt list):string =
"\t" ^ i ^ "\t" ^ (String.concat ", " (List.map fmt2string x))
let w2s(w:Word32.word):string =
if Word32.andb (w,0x80000000l) = 0x80000000l then
let wneg = Word32.neg w in
"-" ^ (Word32.toString wneg)
else Word32.toString w
let i2as (i:string) ((r1:reg),(r2:reg),(w:Word32.word)):string =
"\t" ^ i ^ "\t" ^ (reg2string r1) ^ ", "^(w2s w)^"(" ^ (reg2string r2) ^ ")"
(* Converts an instruction to a string *)
let inst2string(i:inst):string =
match i with
Add (r1,r2,Reg r3) -> i2s "add" [R r1;R r2;R r3]
| Add (r1,r2,Immed w) -> i2s "addi" [R r1;R r2;W w]
| And (r1,r2,Reg r3) -> i2s "and" [R r1;R r2;R r3]
| And (r1,r2,Immed w) -> i2s "andi" [R r1;R r2;W w]
| Div (r1,r2,r3) -> i2s "div" [R r1;R r2;R r3]
| Mul (r1,r2,r3) -> i2s "mul" [R r1;R r2;R r3]
| Nor (r1,r2,r3) -> i2s "nor" [R r1;R r2;R r3]
| Or (r1,r2,Reg r3) -> i2s "or" [R r1;R r2;R r3]
| Or (r1,r2,Immed w) -> i2s "ori" [R r1;R r2;W w]
| Sll (r1,r2,Reg r3) -> i2s "sllv" [R r1;R r2;R r3]
| Sll (r1,r2,Immed w) -> i2s "sll" [R r1;R r2;W w]
| Sra (r1,r2,Reg r3) -> i2s "srav" [R r1;R r2;R r3]
| Sra (r1,r2,Immed w) -> i2s "sra" [R r1;R r2;W w]
| Srl (r1,r2,Reg r3) -> i2s "srlv" [R r1;R r2;R r3]
| Srl (r1,r2,Immed w) -> i2s "srl" [R r1;R r2;W w]
| Sub (r1,r2,r3) -> i2s "sub" [R r1;R r2;R r3]
| Xor (r1,r2,Reg r3) -> i2s "xor" [R r1;R r2;R r3]
| Xor (r1,r2,Immed w) -> i2s "xori" [R r1;R r2;W w]
| Li (r,w) -> i2s "li" [R r;W w]
| Slt (r1,r2,Reg r3) -> i2s "slt" [R r1;R r2;R r3]
| Slt (r1,r2,Immed w) -> i2s "slti" [R r1;R r2;W w]
| Sltu (r1,r2,Reg r3) -> i2s "sltu" [R r1;R r2;R r3]
| Sltu (r1,r2,Immed w) -> i2s "sltiu" [R r1;R r2;W w]
| Sge (r1,r2,r3) -> i2s "sge" [R r1;R r2;R r3]
| Sgeu (r1,r2,r3) -> i2s "sgeu" [R r1;R r2;R r3]
| Sgt (r1,r2,r3) -> i2s "sgt" [R r1;R r2;R r3]
| Sgtu (r1,r2,r3) -> i2s "sgtu" [R r1;R r2;R r3]
| Sle (r1,r2,r3) -> i2s "sle" [R r1;R r2;R r3]
| Sleu (r1,r2,r3) -> i2s "sleu" [R r1;R r2;R r3]
| Sne (r1,r2,r3) -> i2s "sne" [R r1;R r2;R r3]
| Seq (r1,r2,r3) -> i2s "seq" [R r1;R r2;R r3]
| B x -> "\tb "^x
| Beq (r1,r2,x) -> i2s "beq" [R r1;R r2;L x]
| Bgez (r1,x) -> i2s "bgez" [R r1; L x]
| Bgtz (r1,x) -> i2s "bgtz" [R r1; L x]
| Blez (r1,x) -> i2s "blez" [R r1; L x]
| Bltz (r1,x) -> i2s "bltz" [R r1; L x]
| Bne (r1,r2,x) -> i2s "bne" [R r1; R r2;L x]
| J x -> "\tj "^x
| Jal x -> "\tjal "^x
| Jr r1 -> i2s "jr" [R r1]
| Jalr (r1,r2) -> i2s "jalr" [R r1; R r2]
| La (r1,x) -> i2s "la" [R r1;L x]
| Lb (r1,r2,w) -> i2as "lb" (r1,r2,w)
| Lbu (r1,r2,w) -> i2as "lbu" (r1,r2,w)
| Lh (r1,r2,w) -> i2as "lh" (r1,r2,w)
| Lhu (r1,r2,w) -> i2as "lhu" (r1,r2,w)
| Lw (r1,r2,w) -> i2as "lw" (r1,r2,w)
| Sb (r1,r2,w) -> i2as "sb" (r1,r2,w)
| Sh (r1,r2,w) -> i2as "sh" (r1,r2,w)
| Sw (r1,r2,w) -> i2as "sw" (r1,r2,w)
| Label x -> x ^ ":"
| null | https://raw.githubusercontent.com/spartango/CS153/16faf133889f1b287cb95c1ea1245d76c1d8db49/ps6/mips.ml | ocaml | DO NOT USE ME: assembler temp
DO NOT USE ME: reserved for OS
used for special purposes...
Converts an instruction to a string | This structure defines the abstract syntax for MIPS assembly
* language that we will be using . It should be fairly self-
* explanatory .
*
* IMPORTANT : do not use registers R1 , R26 , or R27 as these
* are reserved by the assembler and operating system . See
* page A-24 of the MIPS documentation for details on the
* register conventions .
* language that we will be using. It should be fairly self-
* explanatory.
*
* IMPORTANT: do not use registers R1, R26, or R27 as these
* are reserved by the assembler and operating system. See
* page A-24 of the MIPS documentation for details on the
* register conventions.
*)
type label = string
type reg = R0
| R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9
| R10 | R11 | R12 | R13 | R14 | R15 | R16 | R17 | R18 | R19
| R20 | R21 | R22 | R23 | R24 | R25
| R28
type operand = Reg of reg | Immed of Word32.word
type inst =
Add of reg * reg * operand
| And of reg * reg * operand
| Div of reg * reg * reg
| Mul of reg * reg * reg
| Nor of reg * reg * reg
| Or of reg * reg * operand
| Sll of reg * reg * operand
| Sra of reg * reg * operand
| Srl of reg * reg * operand
| Sub of reg * reg * reg
| Xor of reg * reg * operand
| Li of reg * Word32.word
| Slt of reg * reg * operand
| Sltu of reg * reg * operand
| Sge of reg * reg * reg
| Sgeu of reg * reg * reg
| Sgt of reg * reg * reg
| Sgtu of reg * reg * reg
| Sle of reg * reg * reg
| Sleu of reg * reg * reg
| Seq of reg * reg * reg
| Sne of reg * reg * reg
| B of label
| Beq of reg * reg * label
| Bgez of reg * label
| Bgtz of reg * label
| Blez of reg * label
| Bltz of reg * label
| Bne of reg * reg * label
| J of label
| Jal of label
| Jr of reg
| Jalr of reg * reg
| La of reg * label
| Lb of reg * reg * Word32.word
| Lbu of reg * reg * Word32.word
| Lh of reg * reg * Word32.word
| Lhu of reg * reg * Word32.word
| Lw of reg * reg * Word32.word
| Sb of reg * reg * Word32.word
| Sh of reg * reg * Word32.word
| Sw of reg * reg * Word32.word
| Label of label
The functions below are used to convert MIPS instructions
* into strings , suitable for output to an assembly file .
* into strings, suitable for output to an assembly file. *)
let reg2string (r:reg):string =
match r with
R0 -> "$0" | R1 -> "$1" | R2 -> "$2" | R3 -> "$3" | R4 -> "$4"
| R5 -> "$5" | R6 -> "$6" | R7 -> "$7" | R8 -> "$8" | R9 -> "$9"
| R10 -> "$10" | R11 -> "$11" | R12 -> "$12" | R13 -> "$13"
| R14 -> "$14" | R15 -> "$15" | R16 -> "$16"
| R17 -> "$17" | R18 -> "$18" | R19 -> "$19" | R20 -> "$20"
| R21 -> "$21" | R22 -> "$22" | R23 -> "$23" | R24 -> "$24"
| R25 -> "$25" | R26 -> "$26" | R27 -> "$27" | R28 -> "$28"
| R29 -> "$29" | R30 -> "$30" | R31 -> "$31"
type fmt = R of reg | L of label | W of Word32.word
let fmt2string(f:fmt):string =
match f with
R r -> reg2string r
| W w -> (Word32.toStringX w)
| L x -> x
let i2s (i:string) (x:fmt list):string =
"\t" ^ i ^ "\t" ^ (String.concat ", " (List.map fmt2string x))
let w2s(w:Word32.word):string =
if Word32.andb (w,0x80000000l) = 0x80000000l then
let wneg = Word32.neg w in
"-" ^ (Word32.toString wneg)
else Word32.toString w
let i2as (i:string) ((r1:reg),(r2:reg),(w:Word32.word)):string =
"\t" ^ i ^ "\t" ^ (reg2string r1) ^ ", "^(w2s w)^"(" ^ (reg2string r2) ^ ")"
let inst2string(i:inst):string =
match i with
Add (r1,r2,Reg r3) -> i2s "add" [R r1;R r2;R r3]
| Add (r1,r2,Immed w) -> i2s "addi" [R r1;R r2;W w]
| And (r1,r2,Reg r3) -> i2s "and" [R r1;R r2;R r3]
| And (r1,r2,Immed w) -> i2s "andi" [R r1;R r2;W w]
| Div (r1,r2,r3) -> i2s "div" [R r1;R r2;R r3]
| Mul (r1,r2,r3) -> i2s "mul" [R r1;R r2;R r3]
| Nor (r1,r2,r3) -> i2s "nor" [R r1;R r2;R r3]
| Or (r1,r2,Reg r3) -> i2s "or" [R r1;R r2;R r3]
| Or (r1,r2,Immed w) -> i2s "ori" [R r1;R r2;W w]
| Sll (r1,r2,Reg r3) -> i2s "sllv" [R r1;R r2;R r3]
| Sll (r1,r2,Immed w) -> i2s "sll" [R r1;R r2;W w]
| Sra (r1,r2,Reg r3) -> i2s "srav" [R r1;R r2;R r3]
| Sra (r1,r2,Immed w) -> i2s "sra" [R r1;R r2;W w]
| Srl (r1,r2,Reg r3) -> i2s "srlv" [R r1;R r2;R r3]
| Srl (r1,r2,Immed w) -> i2s "srl" [R r1;R r2;W w]
| Sub (r1,r2,r3) -> i2s "sub" [R r1;R r2;R r3]
| Xor (r1,r2,Reg r3) -> i2s "xor" [R r1;R r2;R r3]
| Xor (r1,r2,Immed w) -> i2s "xori" [R r1;R r2;W w]
| Li (r,w) -> i2s "li" [R r;W w]
| Slt (r1,r2,Reg r3) -> i2s "slt" [R r1;R r2;R r3]
| Slt (r1,r2,Immed w) -> i2s "slti" [R r1;R r2;W w]
| Sltu (r1,r2,Reg r3) -> i2s "sltu" [R r1;R r2;R r3]
| Sltu (r1,r2,Immed w) -> i2s "sltiu" [R r1;R r2;W w]
| Sge (r1,r2,r3) -> i2s "sge" [R r1;R r2;R r3]
| Sgeu (r1,r2,r3) -> i2s "sgeu" [R r1;R r2;R r3]
| Sgt (r1,r2,r3) -> i2s "sgt" [R r1;R r2;R r3]
| Sgtu (r1,r2,r3) -> i2s "sgtu" [R r1;R r2;R r3]
| Sle (r1,r2,r3) -> i2s "sle" [R r1;R r2;R r3]
| Sleu (r1,r2,r3) -> i2s "sleu" [R r1;R r2;R r3]
| Sne (r1,r2,r3) -> i2s "sne" [R r1;R r2;R r3]
| Seq (r1,r2,r3) -> i2s "seq" [R r1;R r2;R r3]
| B x -> "\tb "^x
| Beq (r1,r2,x) -> i2s "beq" [R r1;R r2;L x]
| Bgez (r1,x) -> i2s "bgez" [R r1; L x]
| Bgtz (r1,x) -> i2s "bgtz" [R r1; L x]
| Blez (r1,x) -> i2s "blez" [R r1; L x]
| Bltz (r1,x) -> i2s "bltz" [R r1; L x]
| Bne (r1,r2,x) -> i2s "bne" [R r1; R r2;L x]
| J x -> "\tj "^x
| Jal x -> "\tjal "^x
| Jr r1 -> i2s "jr" [R r1]
| Jalr (r1,r2) -> i2s "jalr" [R r1; R r2]
| La (r1,x) -> i2s "la" [R r1;L x]
| Lb (r1,r2,w) -> i2as "lb" (r1,r2,w)
| Lbu (r1,r2,w) -> i2as "lbu" (r1,r2,w)
| Lh (r1,r2,w) -> i2as "lh" (r1,r2,w)
| Lhu (r1,r2,w) -> i2as "lhu" (r1,r2,w)
| Lw (r1,r2,w) -> i2as "lw" (r1,r2,w)
| Sb (r1,r2,w) -> i2as "sb" (r1,r2,w)
| Sh (r1,r2,w) -> i2as "sh" (r1,r2,w)
| Sw (r1,r2,w) -> i2as "sw" (r1,r2,w)
| Label x -> x ^ ":"
|
109f403c0a0eb68a5de0307c2f21d764bb82a219c8ba031798bcb885629c0527 | LightTable/LightTable | deploy.cljs | (ns lt.objs.deploy
"Provide behaviors to check for app updates and fns for downloading
and unpacking downloaded assets"
(:require [lt.object :as object]
[lt.objs.clients :as clients]
[lt.objs.files :as files]
[lt.objs.popup :as popup]
[lt.objs.cache :as cache]
[lt.objs.notifos :as notifos]
[lt.objs.platform :as platform]
[lt.objs.sidebar.command :as cmd]
[lt.objs.console :as console]
[lt.objs.app :as app]
[lt.util.load :as load]
[lt.util.js :refer [every]]
[lt.util.cljs :refer [str-contains?]]
[clojure.string :as string]
[fetch.core :as fetch])
(:require-macros [fetch.macros :refer [letrem]]
[lt.macros :refer [behavior defui]]))
(def shell (load/node-module "shelljs"))
(def fs (js/require "fs"))
(def zlib (js/require "zlib"))
(def request (load/node-module "request"))
(def tar (load/node-module "tar"))
(def home-path (files/lt-home ""))
;; TODO: get-proxy
( def get - proxy ( .-App.getProxyForURL ( js / require " nw.gui " ) ) )
(def get-proxy)
(def request-strict-ssl true)
(defn tar-path [v]
(if (cache/fetch :edge)
(str "")
(str "/" v)))
(def version-regex #"^\d+\.\d+\.\d+(-.*)?$")
(defn get-versions []
(let [vstr (:content (files/open-sync (files/lt-home "core/version.json")))]
(js->clj (.parse js/JSON vstr) :keywordize-keys true)))
(defn proxy? []
(let [p (get-proxy (tar-path "0.5.0"))]
(when (str-contains? p "PROXY")
(-> p
(string/split " ")
(second)))))
(def version-timeout (* 60 60 1000))
(def version (get-versions))
(defn str->version [s]
(let [[major minor patch] (string/split s ".")]
{:major (js/parseInt major)
:minor (js/parseInt minor)
:patch (js/parseInt patch)}))
(defn compare-versions [v1 v2]
(if (= v1 v2)
false
(not (or (< (:major v2) (:major v1))
(and (= (:major v2) (:major v1))
(< (:minor v2) (:minor v1)))
(and (= (:major v2) (:major v1))
(= (:minor v2) (:minor v1))
(< (:patch v2) (:patch v1)))))))
(defn is-newer?
"Returns true if second version is newer/greater than first version."
[v1 v2]
(compare-versions (str->version v1) (str->version v2)))
(defn download-file [from to cb]
(let [options (js-obj "url" from
"headers" (js-obj "User-Agent" "Light Table")
"strictSSL" request-strict-ssl)
out (.createWriteStream fs to)]
(when-let [proxy (or js/process.env.http_proxy js/process.env.https_proxy)]
(set! (.-proxy options) proxy))
(-> (.get request options cb)
(.on "response" (fn [resp]
(when-not (= (.-statusCode resp) 200)
(notifos/done-working)
(throw (js/Error. (str "Error downloading: " from " status code: " (.-statusCode resp)))))))
(.pipe out))))
(defn download-zip [ver cb]
(let [n (notifos/working (str "Downloading version " ver " .."))]
(download-file (tar-path ver) (str home-path "/tmp.tar.gz") (fn [e r body]
(notifos/done-working)
(cb e r body)))))
(defn untar [from to cb]
(let [t (.createReadStream fs from)]
(.. t
(pipe (.createGunzip zlib))
(pipe (.Extract tar (js-obj "path" to)))
(on "end" cb))))
(defn move-tmp []
(let [parent-dir (first (files/full-path-ls (str home-path "/tmp/")))]
(doseq [file (files/full-path-ls (str parent-dir "/deploy/"))]
(.cp shell "-rf" file home-path)))
(.rm shell "-rf" (str home-path "/tmp*")))
(defn fetch-and-deploy [ver]
(download-zip ver (fn []
(notifos/working "Extracting update...")
(untar (str home-path "/tmp.tar.gz") (str home-path "/tmp")
(fn []
(move-tmp)
(notifos/done-working)
(set! version (assoc version :version ver))
(popup/popup! {:header "Light Table has been updated!"
:body (str "Light Table has been updated to " ver "! Just
restart to get the latest and greatest.")
:buttons [{:label "ok"}]}))))))
(def tags-url "")
(defn should-update-popup [data]
(popup/popup! {:header "There's a newer version of Light Table!"
:body (str "Would you like us to download and install version " data "?")
:buttons [{:label "Cancel"}
{:label "Download and install"
:action (fn []
(fetch-and-deploy data))}]}))
(defn ->latest-version
"Returns latest LT version for github api tags endpoint."
[body]
(when-let [parsed-body
(try (js/JSON.parse body)
(catch :default e
(console/error (str "Invalid JSON response from " tags-url ": " (pr-str body)))))]
(->> parsed-body
;; Ensure only version tags
(keep #(when (re-find version-regex (.-name %)) (.-name %)))
sort
last)))
(defn check-version [& [notify?]]
(fetch/xhr tags-url {}
(fn [data]
(let [latest-version (->latest-version data)]
(when (re-find version-regex latest-version)
(if (and (not= latest-version "")
(not= latest-version (:version version))
(is-newer? (:version version) latest-version)
(or notify?
(not= js/localStorage.fetchedVersion latest-version)))
(do
(set! js/localStorage.fetchedVersion latest-version)
(should-update-popup latest-version))
(when notify?
(notifos/set-msg! (str "At latest version: " (:version version))))))))))
(defn binary-version
"Binary/electron version. The two versions are in sync since binaries updates
only occur with electron updates."
[]
(aget js/process.versions "electron"))
(defui button [label & [cb]]
[:div.button.right label]
:click (fn []
(when cb
(cb))))
(defn alert-binary-update []
(popup/popup! {:header "There's been a binary update!"
:body "There's a new version of the Light Table binary. Clicking below will open the
Light Table website so you can download the updated version."
:buttons [{:label "Download latest"
:action (fn []
(platform/open-url "")
(popup/remain-open))}]}))
;;*********************************************************
;; Behaviors
;;*********************************************************
(behavior ::check-deploy
:triggers #{:deploy}
:reaction (fn [this]
Latest : electron version changes after LT auto - updates and user restarts
(when (is-newer? (binary-version) (:electron version))
(alert-binary-update))))
(behavior ::check-version
:triggers #{:init}
:type :user
:desc "App: Automatically check for updates"
:reaction (fn [this]
;; (when-let [proxy (proxy?)]
;; (.defaults request (clj->js {:proxy proxy})))
(when (app/first-window?)
(set! js/localStorage.fetchedVersion nil))
(check-version)
(every version-timeout check-version)))
(behavior ::strict-ssl
:triggers #{:object.instant}
:type :user
:exclusive [::disable-strict-ssl]
:desc "Enables strict SSL certificate checking when downloading LT and LT plugin repos (default setting)"
:reaction (fn [this]
(set! request-strict-ssl true)))
(behavior ::disable-strict-ssl
:triggers #{:object.instant}
:type :user
:exclusive [::strict-ssl]
:desc "Disables strict SSL certificate checking when downloading LT and LT plugin repos"
:details "In some enterprise environments with SSL proxies strict certificate checking will fail due to MITM certificates used for monitoring SSL traffic. This option allows these network requests to succeed in such environments."
:reaction (fn [this]
(set! request-strict-ssl false)))
(object/tag-behaviors :app [::check-deploy])
| null | https://raw.githubusercontent.com/LightTable/LightTable/3760844132a17fb0c9cf3f3b099905865aed7e3b/src/lt/objs/deploy.cljs | clojure | TODO: get-proxy
Ensure only version tags
*********************************************************
Behaviors
*********************************************************
(when-let [proxy (proxy?)]
(.defaults request (clj->js {:proxy proxy}))) | (ns lt.objs.deploy
"Provide behaviors to check for app updates and fns for downloading
and unpacking downloaded assets"
(:require [lt.object :as object]
[lt.objs.clients :as clients]
[lt.objs.files :as files]
[lt.objs.popup :as popup]
[lt.objs.cache :as cache]
[lt.objs.notifos :as notifos]
[lt.objs.platform :as platform]
[lt.objs.sidebar.command :as cmd]
[lt.objs.console :as console]
[lt.objs.app :as app]
[lt.util.load :as load]
[lt.util.js :refer [every]]
[lt.util.cljs :refer [str-contains?]]
[clojure.string :as string]
[fetch.core :as fetch])
(:require-macros [fetch.macros :refer [letrem]]
[lt.macros :refer [behavior defui]]))
(def shell (load/node-module "shelljs"))
(def fs (js/require "fs"))
(def zlib (js/require "zlib"))
(def request (load/node-module "request"))
(def tar (load/node-module "tar"))
(def home-path (files/lt-home ""))
( def get - proxy ( .-App.getProxyForURL ( js / require " nw.gui " ) ) )
(def get-proxy)
(def request-strict-ssl true)
(defn tar-path [v]
(if (cache/fetch :edge)
(str "")
(str "/" v)))
(def version-regex #"^\d+\.\d+\.\d+(-.*)?$")
(defn get-versions []
(let [vstr (:content (files/open-sync (files/lt-home "core/version.json")))]
(js->clj (.parse js/JSON vstr) :keywordize-keys true)))
(defn proxy? []
(let [p (get-proxy (tar-path "0.5.0"))]
(when (str-contains? p "PROXY")
(-> p
(string/split " ")
(second)))))
(def version-timeout (* 60 60 1000))
(def version (get-versions))
(defn str->version [s]
(let [[major minor patch] (string/split s ".")]
{:major (js/parseInt major)
:minor (js/parseInt minor)
:patch (js/parseInt patch)}))
(defn compare-versions [v1 v2]
(if (= v1 v2)
false
(not (or (< (:major v2) (:major v1))
(and (= (:major v2) (:major v1))
(< (:minor v2) (:minor v1)))
(and (= (:major v2) (:major v1))
(= (:minor v2) (:minor v1))
(< (:patch v2) (:patch v1)))))))
(defn is-newer?
"Returns true if second version is newer/greater than first version."
[v1 v2]
(compare-versions (str->version v1) (str->version v2)))
(defn download-file [from to cb]
(let [options (js-obj "url" from
"headers" (js-obj "User-Agent" "Light Table")
"strictSSL" request-strict-ssl)
out (.createWriteStream fs to)]
(when-let [proxy (or js/process.env.http_proxy js/process.env.https_proxy)]
(set! (.-proxy options) proxy))
(-> (.get request options cb)
(.on "response" (fn [resp]
(when-not (= (.-statusCode resp) 200)
(notifos/done-working)
(throw (js/Error. (str "Error downloading: " from " status code: " (.-statusCode resp)))))))
(.pipe out))))
(defn download-zip [ver cb]
(let [n (notifos/working (str "Downloading version " ver " .."))]
(download-file (tar-path ver) (str home-path "/tmp.tar.gz") (fn [e r body]
(notifos/done-working)
(cb e r body)))))
(defn untar [from to cb]
(let [t (.createReadStream fs from)]
(.. t
(pipe (.createGunzip zlib))
(pipe (.Extract tar (js-obj "path" to)))
(on "end" cb))))
(defn move-tmp []
(let [parent-dir (first (files/full-path-ls (str home-path "/tmp/")))]
(doseq [file (files/full-path-ls (str parent-dir "/deploy/"))]
(.cp shell "-rf" file home-path)))
(.rm shell "-rf" (str home-path "/tmp*")))
(defn fetch-and-deploy [ver]
(download-zip ver (fn []
(notifos/working "Extracting update...")
(untar (str home-path "/tmp.tar.gz") (str home-path "/tmp")
(fn []
(move-tmp)
(notifos/done-working)
(set! version (assoc version :version ver))
(popup/popup! {:header "Light Table has been updated!"
:body (str "Light Table has been updated to " ver "! Just
restart to get the latest and greatest.")
:buttons [{:label "ok"}]}))))))
(def tags-url "")
(defn should-update-popup [data]
(popup/popup! {:header "There's a newer version of Light Table!"
:body (str "Would you like us to download and install version " data "?")
:buttons [{:label "Cancel"}
{:label "Download and install"
:action (fn []
(fetch-and-deploy data))}]}))
(defn ->latest-version
"Returns latest LT version for github api tags endpoint."
[body]
(when-let [parsed-body
(try (js/JSON.parse body)
(catch :default e
(console/error (str "Invalid JSON response from " tags-url ": " (pr-str body)))))]
(->> parsed-body
(keep #(when (re-find version-regex (.-name %)) (.-name %)))
sort
last)))
(defn check-version [& [notify?]]
(fetch/xhr tags-url {}
(fn [data]
(let [latest-version (->latest-version data)]
(when (re-find version-regex latest-version)
(if (and (not= latest-version "")
(not= latest-version (:version version))
(is-newer? (:version version) latest-version)
(or notify?
(not= js/localStorage.fetchedVersion latest-version)))
(do
(set! js/localStorage.fetchedVersion latest-version)
(should-update-popup latest-version))
(when notify?
(notifos/set-msg! (str "At latest version: " (:version version))))))))))
(defn binary-version
"Binary/electron version. The two versions are in sync since binaries updates
only occur with electron updates."
[]
(aget js/process.versions "electron"))
(defui button [label & [cb]]
[:div.button.right label]
:click (fn []
(when cb
(cb))))
(defn alert-binary-update []
(popup/popup! {:header "There's been a binary update!"
:body "There's a new version of the Light Table binary. Clicking below will open the
Light Table website so you can download the updated version."
:buttons [{:label "Download latest"
:action (fn []
(platform/open-url "")
(popup/remain-open))}]}))
(behavior ::check-deploy
:triggers #{:deploy}
:reaction (fn [this]
Latest : electron version changes after LT auto - updates and user restarts
(when (is-newer? (binary-version) (:electron version))
(alert-binary-update))))
(behavior ::check-version
:triggers #{:init}
:type :user
:desc "App: Automatically check for updates"
:reaction (fn [this]
(when (app/first-window?)
(set! js/localStorage.fetchedVersion nil))
(check-version)
(every version-timeout check-version)))
(behavior ::strict-ssl
:triggers #{:object.instant}
:type :user
:exclusive [::disable-strict-ssl]
:desc "Enables strict SSL certificate checking when downloading LT and LT plugin repos (default setting)"
:reaction (fn [this]
(set! request-strict-ssl true)))
(behavior ::disable-strict-ssl
:triggers #{:object.instant}
:type :user
:exclusive [::strict-ssl]
:desc "Disables strict SSL certificate checking when downloading LT and LT plugin repos"
:details "In some enterprise environments with SSL proxies strict certificate checking will fail due to MITM certificates used for monitoring SSL traffic. This option allows these network requests to succeed in such environments."
:reaction (fn [this]
(set! request-strict-ssl false)))
(object/tag-behaviors :app [::check-deploy])
|
28a85cf282678e94b1e93bf3c4caed636f4f3beeaa235d8c7d14c1b59ccd4d19 | openbadgefactory/salava | badges_test.clj | (ns salava.gallery.badges-test
(:require [midje.sweet :refer :all]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]))
(def test-user 4)
(def another-user 5)
(def user-with-no-public-badges 3)
(def public-badge-id "f6e2a6480a832a29200007cfc602ed7e79b9ccb00b2611c58041e71a681216ea")
(def another-public-badge-id "c1a766b5c505e158b4ee1fb3c97df553d7aaac9bcbc49e450a6e71fd1cde8546")
(def not-existing-public-badge-id "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
(def search-criteria
{:recipient ""
:issuer ""
:badge ""
:country ""})
(facts "about badge gallery"
(fact "user must be logged in to view badges in gallery"
(:status (test-api-request :post "/gallery/badges" search-criteria)) => 401)
(apply login! (test-user-credentials test-user))
(fact "recipient name, issuer name, badge name and country are required parameters when searching badges from gallery"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (dissoc search-criteria :recipient))]
status => 400
body => "{\"errors\":{\"recipient\":\"missing-required-key\"}}")
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (dissoc search-criteria :issuer))]
status => 400
body => "{\"errors\":{\"issuer\":\"missing-required-key\"}}")
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (dissoc search-criteria :badge))]
status => 400
body => "{\"errors\":{\"badge\":\"missing-required-key\"}}")
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (dissoc search-criteria :country))]
status => 400
body => "{\"errors\":{\"country\":\"missing-required-key\"}}"))
(fact "badges from same region as user are shown by default in badge gallery"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" search-criteria)
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 2
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "badges from other regions can be searched"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :country "SE"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 1
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "all public badges can be viewed"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :country "all"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 3
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "badges can be searched by the name of the badge"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :badge "testing gallery 2" :country "all"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 1
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "badges can be searched by recipient's name"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :recipient "Example" :country "all"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 1
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "badges can be searched by the name of the issuer"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :issuer "Test issuer" :country "all"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 2
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "if no badges match the search criteria, badge collection is empty"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :badge "no results" :country "all"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 0))
(logout!)
(apply login! (test-user-credentials another-user))
(fact "badges from same region as user are shown by default in badge gallery"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" search-criteria)
{:keys [user-country badges countries]} body]
status => 200
user-country => "SE"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 1))
(logout!))
(facts "about personal badge gallery"
(apply login! (test-user-credentials test-user))
(fact "user-id must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/gallery/badges/not-integer"))]
status => 400
body => "{\"errors\":{\"userid\":\"(not (integer? \\\"not-integer\\\"))\"}}"))
(fact "user logged in can view public and internal badges of specific user"
(let [{:keys [status body]} (test-api-request :post (str "/gallery/badges/" test-user))
badges (:badges body)]
status => 200
(count badges) => 2
(every? #(= (:visibility %) "public") badges) => false
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :expires_on :issued_on :id :badge_content_id :mtime :assertion_url :visibility] :in-any-order)))
(fact "another user have no public badges"
(let [{:keys [status body]} (test-api-request :post (str "/gallery/badges/" user-with-no-public-badges))
badges (:badges body)]
status => 200
(count badges) => 0))
(fact "non-existing user have no public badges"
(let [{:keys [status body]} (test-api-request :post (str "/gallery/badges/99"))
badges (:badges body)]
status => 200
(count badges) => 0))
(logout!)
(fact "anonymous user can view only public badges of specific user"
(let [{:keys [status body]} (test-api-request :post (str "/gallery/badges/" test-user))
badges (:badges body)]
status => 200
(count badges) => 1
(every? #(= (:visibility %) "public") badges) => true
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :expires_on :issued_on :id :badge_content_id :mtime :assertion_url :visibility] :in-any-order))))
(facts "about badge's public view"
(apply login! (test-user-credentials test-user))
(fact "badge-content-id must be valid"
(let [{:keys [status body]} (test-api-request :get "/gallery/public_badge_content/not-valid")]
status => 500
body => "{\"errors\":{\"badge\":{\"description\":\"missing-required-key\",\"badge_url\":\"missing-required-key\",\"issuer_content_url\":\"missing-required-key\",\"creator_name\":\"missing-required-key\",\"issuer_content_name\":\"missing-required-key\",\"name\":\"missing-required-key\",\"image_file\":\"missing-required-key\",\"issuer_contact\":\"missing-required-key\",\"issuer_image\":\"missing-required-key\",\"html_content\":\"missing-required-key\",\"criteria_url\":\"missing-required-key\",\"creator_email\":\"missing-required-key\",\"creator_image\":\"missing-required-key\",\"creator_url\":\"missing-required-key\",\"issuer_verified\":\"missing-required-key\"}}}")
(let [{:keys [status body]} (test-api-request :get (str "/gallery/public_badge_content/" not-existing-public-badge-id))]
status => 500
body => "{\"errors\":{\"badge\":{\"description\":\"missing-required-key\",\"badge_url\":\"missing-required-key\",\"issuer_content_url\":\"missing-required-key\",\"creator_name\":\"missing-required-key\",\"issuer_content_name\":\"missing-required-key\",\"name\":\"missing-required-key\",\"image_file\":\"missing-required-key\",\"issuer_contact\":\"missing-required-key\",\"issuer_image\":\"missing-required-key\",\"html_content\":\"missing-required-key\",\"criteria_url\":\"missing-required-key\",\"creator_email\":\"missing-required-key\",\"creator_image\":\"missing-required-key\",\"creator_url\":\"missing-required-key\",\"issuer_verified\":\"missing-required-key\"}}}"))
(fact "badge's public information is correct"
(let [{:keys [status body]} (test-api-request :get (str "/gallery/public_badge_content/" public-badge-id))
{:keys [badge public_users private_user_count]} body]
status => 200
private_user_count => 1
(count public_users) => 2
(keys badge) => (just [:description :badge_url :issuer_content_url :creator_name :issuer_content_name :verified_by_obf :name :image_file :rating_count :recipient :issuer_contact :issuer_image :obf_url :html_content :issued_by_obf :criteria_url :creator_email :creator_image :average_rating :creator_url :issuer_verified] :in-any-order))
(let [{:keys [status body]} (test-api-request :get (str "/gallery/public_badge_content/" another-public-badge-id))
{:keys [badge public_users private_user_count]} body]
status => 200
private_user_count => 0
(count public_users) => 1
(keys badge) => (just [:description :badge_url :issuer_content_url :creator_name :issuer_content_name :verified_by_obf :name :image_file :rating_count :recipient :issuer_contact :issuer_image :obf_url :html_content :issued_by_obf :criteria_url :creator_email :creator_image :average_rating :creator_url :issuer_verified] :in-any-order)))
(logout!)
(fact "if user is not logged in, badge recipient information is not available"
(let [{:keys [status body]} (test-api-request :get (str "/gallery/public_badge_content/" public-badge-id))
{:keys [badge public_users private_user_count]} body]
status => 200
private_user_count => 0
public_users => []
(keys badge) => (just [:description :badge_url :issuer_content_url :creator_name :issuer_content_name :verified_by_obf :name :image_file :rating_count :recipient :issuer_contact :issuer_image :obf_url :html_content :issued_by_obf :criteria_url :creator_email :creator_image :average_rating :creator_url :issuer_verified] :in-any-order))))
| null | https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/test_old/clj/salava/gallery/badges_test.clj | clojure | (ns salava.gallery.badges-test
(:require [midje.sweet :refer :all]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]))
(def test-user 4)
(def another-user 5)
(def user-with-no-public-badges 3)
(def public-badge-id "f6e2a6480a832a29200007cfc602ed7e79b9ccb00b2611c58041e71a681216ea")
(def another-public-badge-id "c1a766b5c505e158b4ee1fb3c97df553d7aaac9bcbc49e450a6e71fd1cde8546")
(def not-existing-public-badge-id "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
(def search-criteria
{:recipient ""
:issuer ""
:badge ""
:country ""})
(facts "about badge gallery"
(fact "user must be logged in to view badges in gallery"
(:status (test-api-request :post "/gallery/badges" search-criteria)) => 401)
(apply login! (test-user-credentials test-user))
(fact "recipient name, issuer name, badge name and country are required parameters when searching badges from gallery"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (dissoc search-criteria :recipient))]
status => 400
body => "{\"errors\":{\"recipient\":\"missing-required-key\"}}")
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (dissoc search-criteria :issuer))]
status => 400
body => "{\"errors\":{\"issuer\":\"missing-required-key\"}}")
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (dissoc search-criteria :badge))]
status => 400
body => "{\"errors\":{\"badge\":\"missing-required-key\"}}")
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (dissoc search-criteria :country))]
status => 400
body => "{\"errors\":{\"country\":\"missing-required-key\"}}"))
(fact "badges from same region as user are shown by default in badge gallery"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" search-criteria)
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 2
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "badges from other regions can be searched"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :country "SE"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 1
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "all public badges can be viewed"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :country "all"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 3
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "badges can be searched by the name of the badge"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :badge "testing gallery 2" :country "all"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 1
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "badges can be searched by recipient's name"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :recipient "Example" :country "all"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 1
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "badges can be searched by the name of the issuer"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :issuer "Test issuer" :country "all"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 2
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :recipients :ctime :id :mtime] :in-any-order)))
(fact "if no badges match the search criteria, badge collection is empty"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" (assoc search-criteria :badge "no results" :country "all"))
{:keys [user-country badges countries]} body]
status => 200
user-country => "FI"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 0))
(logout!)
(apply login! (test-user-credentials another-user))
(fact "badges from same region as user are shown by default in badge gallery"
(let [{:keys [status body]} (test-api-request :post "/gallery/badges" search-criteria)
{:keys [user-country badges countries]} body]
status => 200
user-country => "SE"
(keys countries) => (just [:FI :US :SE] :in-any-order)
(count badges) => 1))
(logout!))
(facts "about personal badge gallery"
(apply login! (test-user-credentials test-user))
(fact "user-id must be valid"
(let [{:keys [status body]} (test-api-request :post (str "/gallery/badges/not-integer"))]
status => 400
body => "{\"errors\":{\"userid\":\"(not (integer? \\\"not-integer\\\"))\"}}"))
(fact "user logged in can view public and internal badges of specific user"
(let [{:keys [status body]} (test-api-request :post (str "/gallery/badges/" test-user))
badges (:badges body)]
status => 200
(count badges) => 2
(every? #(= (:visibility %) "public") badges) => false
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :expires_on :issued_on :id :badge_content_id :mtime :assertion_url :visibility] :in-any-order)))
(fact "another user have no public badges"
(let [{:keys [status body]} (test-api-request :post (str "/gallery/badges/" user-with-no-public-badges))
badges (:badges body)]
status => 200
(count badges) => 0))
(fact "non-existing user have no public badges"
(let [{:keys [status body]} (test-api-request :post (str "/gallery/badges/99"))
badges (:badges body)]
status => 200
(count badges) => 0))
(logout!)
(fact "anonymous user can view only public badges of specific user"
(let [{:keys [status body]} (test-api-request :post (str "/gallery/badges/" test-user))
badges (:badges body)]
status => 200
(count badges) => 1
(every? #(= (:visibility %) "public") badges) => true
(keys (first badges)) => (just [:description :issuer_content_url :issuer_content_name :name :image_file :expires_on :issued_on :id :badge_content_id :mtime :assertion_url :visibility] :in-any-order))))
(facts "about badge's public view"
(apply login! (test-user-credentials test-user))
(fact "badge-content-id must be valid"
(let [{:keys [status body]} (test-api-request :get "/gallery/public_badge_content/not-valid")]
status => 500
body => "{\"errors\":{\"badge\":{\"description\":\"missing-required-key\",\"badge_url\":\"missing-required-key\",\"issuer_content_url\":\"missing-required-key\",\"creator_name\":\"missing-required-key\",\"issuer_content_name\":\"missing-required-key\",\"name\":\"missing-required-key\",\"image_file\":\"missing-required-key\",\"issuer_contact\":\"missing-required-key\",\"issuer_image\":\"missing-required-key\",\"html_content\":\"missing-required-key\",\"criteria_url\":\"missing-required-key\",\"creator_email\":\"missing-required-key\",\"creator_image\":\"missing-required-key\",\"creator_url\":\"missing-required-key\",\"issuer_verified\":\"missing-required-key\"}}}")
(let [{:keys [status body]} (test-api-request :get (str "/gallery/public_badge_content/" not-existing-public-badge-id))]
status => 500
body => "{\"errors\":{\"badge\":{\"description\":\"missing-required-key\",\"badge_url\":\"missing-required-key\",\"issuer_content_url\":\"missing-required-key\",\"creator_name\":\"missing-required-key\",\"issuer_content_name\":\"missing-required-key\",\"name\":\"missing-required-key\",\"image_file\":\"missing-required-key\",\"issuer_contact\":\"missing-required-key\",\"issuer_image\":\"missing-required-key\",\"html_content\":\"missing-required-key\",\"criteria_url\":\"missing-required-key\",\"creator_email\":\"missing-required-key\",\"creator_image\":\"missing-required-key\",\"creator_url\":\"missing-required-key\",\"issuer_verified\":\"missing-required-key\"}}}"))
(fact "badge's public information is correct"
(let [{:keys [status body]} (test-api-request :get (str "/gallery/public_badge_content/" public-badge-id))
{:keys [badge public_users private_user_count]} body]
status => 200
private_user_count => 1
(count public_users) => 2
(keys badge) => (just [:description :badge_url :issuer_content_url :creator_name :issuer_content_name :verified_by_obf :name :image_file :rating_count :recipient :issuer_contact :issuer_image :obf_url :html_content :issued_by_obf :criteria_url :creator_email :creator_image :average_rating :creator_url :issuer_verified] :in-any-order))
(let [{:keys [status body]} (test-api-request :get (str "/gallery/public_badge_content/" another-public-badge-id))
{:keys [badge public_users private_user_count]} body]
status => 200
private_user_count => 0
(count public_users) => 1
(keys badge) => (just [:description :badge_url :issuer_content_url :creator_name :issuer_content_name :verified_by_obf :name :image_file :rating_count :recipient :issuer_contact :issuer_image :obf_url :html_content :issued_by_obf :criteria_url :creator_email :creator_image :average_rating :creator_url :issuer_verified] :in-any-order)))
(logout!)
(fact "if user is not logged in, badge recipient information is not available"
(let [{:keys [status body]} (test-api-request :get (str "/gallery/public_badge_content/" public-badge-id))
{:keys [badge public_users private_user_count]} body]
status => 200
private_user_count => 0
public_users => []
(keys badge) => (just [:description :badge_url :issuer_content_url :creator_name :issuer_content_name :verified_by_obf :name :image_file :rating_count :recipient :issuer_contact :issuer_image :obf_url :html_content :issued_by_obf :criteria_url :creator_email :creator_image :average_rating :creator_url :issuer_verified] :in-any-order))))
|
|
364f9cffd03098ebe021ea9e01fe8c91e812e47e848f02bdb716b4b3d288df68 | GaloisInc/msf-haskell | Host.hs | |Various types of hosts that Metasploit might interact
-- with. Particularly, /attackable/ and /scannable/ hosts.
{-# LANGUAGE EmptyDataDecls #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
module MSF.Host where
import MsgPack
-- | A metasploit framework RPC server.
data Server
-- | A host that can have attacks launched against it.
data Attackable
-- | A host that can be scanned.
data Scannable
class ScanCxt t
instance ScanCxt Scannable
instance ScanCxt Attackable
class ScanCxt t => AttackCxt t
instance AttackCxt Attackable
-- Individual Hosts ------------------------------------------------------------
-- | A host is just a name or an address.
newtype Host t = Host
{ getHost :: String
} deriving (Show,Eq,Ord)
-- XXX dangerous, do not export
castHost :: Host t -> Host t'
castHost (Host n) = Host n
attackableHost :: Host Scannable -> Host Attackable
attackableHost = castHost
instance ToObject (Host t) where
toObject = toObject . getHost
instance FromObject (Host t) where
fromObject = fmap Host . fromObject
Host Connections ---------------------------------------------------------
| A connection is a host and a port . The MSF server itself is a connection .
data Con t = Con
{ conHost :: Host t
, conPort :: String
} deriving (Show,Eq)
-- XXX Don't export from a top-level api
getCon :: Con t -> String
getCon con
| null (conPort con) = getHost (conHost con) ++ ":" ++ conPort con
| otherwise = getHost (conHost con)
-- Command Targets ----------------------------------------------------------
-- | One or more targets
newtype Target t = Target
{ getTarget :: [TargetRange t]
} deriving (Show)
-- XXX dangerous, do not export
castTarget :: Target t -> Target t'
castTarget (Target ts) = Target (map castTargetRange ts)
-- | A range of hosts.
data TargetRange t
= CIDR (Host t) Int
| HostRange (Host t) (Host t)
| SingleHost (Host t)
deriving (Show)
-- XXX dangerous, do not export
castTargetRange :: TargetRange t -> TargetRange t'
castTargetRange range = case range of
CIDR h n -> CIDR (castHost h) n
HostRange l r -> HostRange (castHost l) (castHost r)
SingleHost h -> SingleHost (castHost h)
class HostStage l r t | l r -> t
instance HostStage Attackable Attackable Attackable
instance HostStage Attackable Scannable Scannable
instance HostStage Scannable Attackable Scannable
instance HostStage Scannable Scannable Scannable
-- | Target combination. This might need a better operator name at some point.
(&) :: HostStage l r t => Target l -> Target r -> Target t
l & r = Target (getTarget (castTarget l) ++ getTarget (castTarget r))
infixr 1 &
-- | Construct a host range.
to :: Host t -> Host t -> Target t
lo `to` hi = Target [HostRange lo hi]
-- | Construct a host range described by CIDR notation.
cidr :: Host t -> Int -> Target t
cidr h n = Target [CIDR h n]
-- | Lift a single host into a target specification.
single :: Host t -> Target t
single h = Target [SingleHost h]
-- | Convert a @Target@ into an application specific use.
foldTarget :: (TargetRange t -> a -> a) -> a -> Target t -> a
foldTarget fmt z = foldr fmt z . getTarget
| null | https://raw.githubusercontent.com/GaloisInc/msf-haskell/76cee10771f9e9d10aa3301198e09f08bde907be/src/MSF/Host.hs | haskell | with. Particularly, /attackable/ and /scannable/ hosts.
# LANGUAGE EmptyDataDecls #
| A metasploit framework RPC server.
| A host that can have attacks launched against it.
| A host that can be scanned.
Individual Hosts ------------------------------------------------------------
| A host is just a name or an address.
XXX dangerous, do not export
-------------------------------------------------------
XXX Don't export from a top-level api
Command Targets ----------------------------------------------------------
| One or more targets
XXX dangerous, do not export
| A range of hosts.
XXX dangerous, do not export
| Target combination. This might need a better operator name at some point.
| Construct a host range.
| Construct a host range described by CIDR notation.
| Lift a single host into a target specification.
| Convert a @Target@ into an application specific use. | |Various types of hosts that Metasploit might interact
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
module MSF.Host where
import MsgPack
data Server
data Attackable
data Scannable
class ScanCxt t
instance ScanCxt Scannable
instance ScanCxt Attackable
class ScanCxt t => AttackCxt t
instance AttackCxt Attackable
newtype Host t = Host
{ getHost :: String
} deriving (Show,Eq,Ord)
castHost :: Host t -> Host t'
castHost (Host n) = Host n
attackableHost :: Host Scannable -> Host Attackable
attackableHost = castHost
instance ToObject (Host t) where
toObject = toObject . getHost
instance FromObject (Host t) where
fromObject = fmap Host . fromObject
| A connection is a host and a port . The MSF server itself is a connection .
data Con t = Con
{ conHost :: Host t
, conPort :: String
} deriving (Show,Eq)
getCon :: Con t -> String
getCon con
| null (conPort con) = getHost (conHost con) ++ ":" ++ conPort con
| otherwise = getHost (conHost con)
newtype Target t = Target
{ getTarget :: [TargetRange t]
} deriving (Show)
castTarget :: Target t -> Target t'
castTarget (Target ts) = Target (map castTargetRange ts)
data TargetRange t
= CIDR (Host t) Int
| HostRange (Host t) (Host t)
| SingleHost (Host t)
deriving (Show)
castTargetRange :: TargetRange t -> TargetRange t'
castTargetRange range = case range of
CIDR h n -> CIDR (castHost h) n
HostRange l r -> HostRange (castHost l) (castHost r)
SingleHost h -> SingleHost (castHost h)
class HostStage l r t | l r -> t
instance HostStage Attackable Attackable Attackable
instance HostStage Attackable Scannable Scannable
instance HostStage Scannable Attackable Scannable
instance HostStage Scannable Scannable Scannable
(&) :: HostStage l r t => Target l -> Target r -> Target t
l & r = Target (getTarget (castTarget l) ++ getTarget (castTarget r))
infixr 1 &
to :: Host t -> Host t -> Target t
lo `to` hi = Target [HostRange lo hi]
cidr :: Host t -> Int -> Target t
cidr h n = Target [CIDR h n]
single :: Host t -> Target t
single h = Target [SingleHost h]
foldTarget :: (TargetRange t -> a -> a) -> a -> Target t -> a
foldTarget fmt z = foldr fmt z . getTarget
|
137eaba14e94da9e02d1e3dec1226c902eb9180d50f97d8db0b8f5970e43ba47 | mRrvz/bmstu-ca | Main.hs | import Parse
import Spline
import System.IO
main :: IO ()
main = do
handle <- openFile "table.csv" ReadMode
content <- hGetContents handle
let table = parseTable $ lines content
mapM_ print table
hClose handle
putStrLn "Enter X:"
x0 <- fmap toDouble getLine
putStr "Result: "
print $ spline table x0
| null | https://raw.githubusercontent.com/mRrvz/bmstu-ca/866a32b37878d45006ec3c4f99f67983ae681717/lab_03/src/Main.hs | haskell | import Parse
import Spline
import System.IO
main :: IO ()
main = do
handle <- openFile "table.csv" ReadMode
content <- hGetContents handle
let table = parseTable $ lines content
mapM_ print table
hClose handle
putStrLn "Enter X:"
x0 <- fmap toDouble getLine
putStr "Result: "
print $ spline table x0
|
|
67d4f4cc76485da655558e5693602851352f97d6e953f559b00086c170706e02 | erleans/erleans | stateless_test_grain.erl | %%% ---------------------------------------------------------------------------
@author < >
2016 Space - Time Insight < >
%%%
%%% @doc A test grain that increments a counter every time it is activated.
%%% @end
%%% ---------------------------------------------------------------------------
-module(stateless_test_grain).
-behaviour(erleans_grain).
-export([placement/0,
provider/0,
node/1,
deactivated_counter/1,
activated_counter/1,
call_counter/1,
hold/1,
pid/1]).
-export([state/1,
activate/2,
handle_call/3,
handle_cast/2,
deactivate/1]).
-include("erleans.hrl").
placement() ->
{stateless, 3}.
provider() ->
ets.
deactivated_counter(Ref) ->
erleans_grain:call(Ref, deactivated_counter).
activated_counter(Ref) ->
erleans_grain:call(Ref, activated_counter).
call_counter(Ref) ->
erleans_grain:call(Ref, call_counter).
hold(Ref) ->
erleans_grain:call(Ref, hold).
pid(Ref) ->
erleans_grain:call(Ref, pid).
node(Ref) ->
erleans_grain:call(Ref, node).
state(_) ->
#{activated_counter => 0,
deactivated_counter => 0,
call_counter => 0}.
activate(_, State=#{activated_counter := Counter}) ->
{ok, State#{activated_counter => Counter+1}, #{}}.
handle_call(Msg, From, State=#{call_counter := CallCounter}) ->
handle_call_(Msg, From, State#{call_counter => CallCounter+1}).
handle_call_(node, From, State) ->
{ok, State, [{reply, From, {ok, node()}}]};
handle_call_(pid, From, State) ->
{ok, State, [{reply, From, {ok, self()}}]};
handle_call_(call_counter, From, State=#{call_counter := CallCounter}) ->
{ok, State, [{reply, From, {ok, CallCounter}}]};
handle_call_(deactivated_counter, From, State=#{deactivated_counter := Counter}) ->
{ok, State, [{reply, From, {ok, Counter}}]};
handle_call_(deactivated_counter, From, State) ->
{ok, State, [{reply, From, {ok, 0}}]};
handle_call_(hold, From, State=#{}) ->
timer:sleep(3000),
{ok, State, [{reply, From, ok}]};
handle_call_(activated_counter, From, State=#{activated_counter := Counter}) ->
{ok, State, [{reply, From, {ok, Counter}}]};
handle_call_(activated_counter, From, State) ->
{ok, State, [{reply, From, {ok, 0}}]}.
handle_cast(_, State) ->
{noreply, State}.
deactivate(State=#{deactivated_counter := D}) ->
{ok, State#{deactivated_counter => D+1}}.
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/erleans/erleans/ecccf9e900f23660847bd63555b54478e9a00530/test/stateless_test_grain.erl | erlang | ---------------------------------------------------------------------------
@doc A test grain that increments a counter every time it is activated.
@end
---------------------------------------------------------------------------
===================================================================
=================================================================== | @author < >
2016 Space - Time Insight < >
-module(stateless_test_grain).
-behaviour(erleans_grain).
-export([placement/0,
provider/0,
node/1,
deactivated_counter/1,
activated_counter/1,
call_counter/1,
hold/1,
pid/1]).
-export([state/1,
activate/2,
handle_call/3,
handle_cast/2,
deactivate/1]).
-include("erleans.hrl").
placement() ->
{stateless, 3}.
provider() ->
ets.
deactivated_counter(Ref) ->
erleans_grain:call(Ref, deactivated_counter).
activated_counter(Ref) ->
erleans_grain:call(Ref, activated_counter).
call_counter(Ref) ->
erleans_grain:call(Ref, call_counter).
hold(Ref) ->
erleans_grain:call(Ref, hold).
pid(Ref) ->
erleans_grain:call(Ref, pid).
node(Ref) ->
erleans_grain:call(Ref, node).
state(_) ->
#{activated_counter => 0,
deactivated_counter => 0,
call_counter => 0}.
activate(_, State=#{activated_counter := Counter}) ->
{ok, State#{activated_counter => Counter+1}, #{}}.
handle_call(Msg, From, State=#{call_counter := CallCounter}) ->
handle_call_(Msg, From, State#{call_counter => CallCounter+1}).
handle_call_(node, From, State) ->
{ok, State, [{reply, From, {ok, node()}}]};
handle_call_(pid, From, State) ->
{ok, State, [{reply, From, {ok, self()}}]};
handle_call_(call_counter, From, State=#{call_counter := CallCounter}) ->
{ok, State, [{reply, From, {ok, CallCounter}}]};
handle_call_(deactivated_counter, From, State=#{deactivated_counter := Counter}) ->
{ok, State, [{reply, From, {ok, Counter}}]};
handle_call_(deactivated_counter, From, State) ->
{ok, State, [{reply, From, {ok, 0}}]};
handle_call_(hold, From, State=#{}) ->
timer:sleep(3000),
{ok, State, [{reply, From, ok}]};
handle_call_(activated_counter, From, State=#{activated_counter := Counter}) ->
{ok, State, [{reply, From, {ok, Counter}}]};
handle_call_(activated_counter, From, State) ->
{ok, State, [{reply, From, {ok, 0}}]}.
handle_cast(_, State) ->
{noreply, State}.
deactivate(State=#{deactivated_counter := D}) ->
{ok, State#{deactivated_counter => D+1}}.
Internal functions
|
4f10b37c9d25fa72e4fd9f61dfa8dc949343de08769e91f55a31cca922313386 | yueyoum/codebattle-server | cb_observer_sup.erl | -module(cb_observer_sup).
-behaviour(supervisor).
%% API
-export([start_link/0,
create_observer/1]).
%% Supervisor callbacks
-export([init/1]).
-define(CHILD(Id, Mod, Type, Args), {Id, {Mod, start_link, Args},
temporary, brutal_kill, Type, [Mod]}).
%%%===================================================================
%%% API functions
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Starts the supervisor
%%
( ) - > { ok , Pid } | ignore | { error , Error }
%% @end
%%--------------------------------------------------------------------
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
create_observer(Sock) ->
supervisor:start_child(?MODULE, [Sock]).
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
%%--------------------------------------------------------------------
@private
%% @doc
%% Whenever a supervisor is started using supervisor:start_link/[2,3],
%% this function is called by the new process to find out about
%% restart strategy, maximum restart frequency and child
%% specifications.
%%
) - > { ok , { SupFlags , [ ChildSpec ] } } |
%% ignore |
%% {error, Reason}
%% @end
%%--------------------------------------------------------------------
init([]) ->
{ok, {{simple_one_for_one, 0, 1},
[?CHILD(cb_observer, cb_observer, worker, [])]
}}.
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/yueyoum/codebattle-server/5e8ae24649be14eb7c3dc1910502bf88af97ed8d/src/cb_observer_sup.erl | erlang | API
Supervisor callbacks
===================================================================
API functions
===================================================================
--------------------------------------------------------------------
@doc
Starts the supervisor
@end
--------------------------------------------------------------------
===================================================================
Supervisor callbacks
===================================================================
--------------------------------------------------------------------
@doc
Whenever a supervisor is started using supervisor:start_link/[2,3],
this function is called by the new process to find out about
restart strategy, maximum restart frequency and child
specifications.
ignore |
{error, Reason}
@end
--------------------------------------------------------------------
===================================================================
=================================================================== | -module(cb_observer_sup).
-behaviour(supervisor).
-export([start_link/0,
create_observer/1]).
-export([init/1]).
-define(CHILD(Id, Mod, Type, Args), {Id, {Mod, start_link, Args},
temporary, brutal_kill, Type, [Mod]}).
( ) - > { ok , Pid } | ignore | { error , Error }
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
create_observer(Sock) ->
supervisor:start_child(?MODULE, [Sock]).
@private
) - > { ok , { SupFlags , [ ChildSpec ] } } |
init([]) ->
{ok, {{simple_one_for_one, 0, 1},
[?CHILD(cb_observer, cb_observer, worker, [])]
}}.
Internal functions
|
4e662a7c304d6ec388872b705b38169fec42f0e217589721d73f8801a115ad3f | bn-d/ppx_pyformat | utils.mli | val get_arg_name : int -> string
val parse : string -> Types.elements
| null | https://raw.githubusercontent.com/bn-d/ppx_pyformat/bcb0031cf9fbce12d54d0e8d927ecf41ff3cab97/src/utils.mli | ocaml | val get_arg_name : int -> string
val parse : string -> Types.elements
|
|
e58cecc2129f4d7b5273c0c12e20bcbb17b077d0ba56b34c6d692bbcc3353113 | charlieg/Sparser | arg-str-original.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(CTI-source LISP) -*-
copyright ( c ) 1990,1991 Content Technologies Inc. -- all rights reserved
;;;
;;; File: "arg str"
Module : " model forms;sl : whos news : acts : "
version : February 1991 ( v1.8.1 )
(in-package :CTI-source)
;;;---------------------------------------------------------
;;; subcategorization frames of the various job event-types
;;;---------------------------------------------------------
(def-category job-event/co!__pers!title-pp)
(def-category job-event/co!__pers!title)
(def-category job-event/co!__!title)
(def-category job-event/co!__)
(def-category job-event/co!__!pers)
(def-category job-event/pers!__!title-pp)
(def-category job-event/pers!__!title)
(def-category job-event/pers!__!pers)
(def-category job-event/pers!__)
(def-category job-event/pers!__!co)
(def-category job-event/title!__)
(def-category job-event)
;;;------------------------------------------
;;; passive -- promote the internal argument
;;;------------------------------------------
(def-cfr job-event/pers!__!title-pp
(be job-event/co!__pers!title-pp)
:form vg
:referent (:daughter right-edge))
(def-cfr job-event/pers!__!title
(be job-event/co!__pers!title)
:form vg
:referent (:daughter right-edge))
(def-cfr job-event/pers!__
(be job-event/co!__!pers)
:form vg
:referent (:daughter right-edge))
(def-cfr job-event/title!__
(be/neg job-event/co!__pers!title)
:form vg
:referent (:daughter right-edge))
;;;-------------
;;; progressive
;;;-------------
;;-- "is retiring" "is retired"
;;
(def-cfr job-event/pers!__
(be job-event/pers!__)
:form vg
:referent (:daughter right-edge))
;;;----------------
;;; soak up modals
;;;----------------
;;-- "will retire"
;;
(def-cfr job-event/pers!__!title-pp
(modal job-event/pers!__!title-pp)
:form vg
:referent (:daughter right-edge))
;;;-----------------
;;; soak up adverbs
;;;-----------------
(def-cfr job-event/co!__pers!title
(adverb job-event/co!__pers!title)
:referent (:daughter right-edge))
(def-cfr job-event/pers!__!title
(adverb job-event/pers!__!title)
:referent (:daughter right-edge))
(def-cfr job-event/title!__
(adverb job-event/title!__)
:referent (:daughter right-edge))
;;;---------------------------------
;;; compose the title direct object
;;;---------------------------------
(def-cfr job-event/pers!__
(job-event/pers!__!title-pp title-pp)
:form VP
:referent (:composite job-event+title
left-edge right-edge))
(def-cfr job-event/pers!__
(job-event/pers!__!title title)
:form VP
:referent (:composite job-event+title
left-edge right-edge))
(def-cfr job-event/co!__
(job-event/co!__!title title)
:form VP
:referent (:composite job-event+title
right-edge left-edge))
;;--------- swallow a following "to"
( ) " [ pers ] was named to ( the additional post of ... ) "
;;
(def-cfr job-event/pers!__!title
(job-event/pers!__!title "to")
:form vg+prep
:referent (:daughter left-edge))
;;;----------------------------
;;; compose with title subject
;;;----------------------------
(def-cfr job-event
(title job-event/title!__)
:form S
:referent (:composite job-event+title
right-edge left-edge))
;;;-----------------------------------
;;; compose with person direct object
;;;-----------------------------------
(def-cfr job-event/pers!__
(job-event/pers!__!pers person)
:form VP
:referent (:composite job-event+replacing
left-edge right-edge))
(def-cfr job-event/co!__!title
(job-event/co!__!pers!title person)
:form VP
:referent (:composite job-event+person
left-edge right-edge))
(def-cfr job-event/co!__!title
(job-event/co!__pers!title person)
;; !! the only difference here is a "!" --something
;; somewhere is inconsistent
:form VP
:referent (:composite job-event+person
left-edge right-edge))
;;;-----------------------------
;;; compose with person subject
;;;-----------------------------
(def-cfr job-event (person job-event/pers!__)
:form S
:referent (:composite job-event+person
left-edge right-edge))
;;;------------------------------
;;; compose with company subject
;;;------------------------------
(def-cfr job-event (company job-event/co!__)
:form S
:referent (:composite job-event+company
right-edge left-edge))
;;;------------------------------------
;;; compose with company direct object
;;;------------------------------------
(def-cfr job-event/pers!__ (job-event/pers!__!co co)
:form S
:referent (:composite job-event+company
left-edge right-edge))
| null | https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/grammar/model/sl/Who's-News/acts/arg%20str/arg-str-original.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:(CTI-source LISP) -*-
File: "arg str"
---------------------------------------------------------
subcategorization frames of the various job event-types
---------------------------------------------------------
------------------------------------------
passive -- promote the internal argument
------------------------------------------
-------------
progressive
-------------
-- "is retiring" "is retired"
----------------
soak up modals
----------------
-- "will retire"
-----------------
soak up adverbs
-----------------
---------------------------------
compose the title direct object
---------------------------------
--------- swallow a following "to"
----------------------------
compose with title subject
----------------------------
-----------------------------------
compose with person direct object
-----------------------------------
!! the only difference here is a "!" --something
somewhere is inconsistent
-----------------------------
compose with person subject
-----------------------------
------------------------------
compose with company subject
------------------------------
------------------------------------
compose with company direct object
------------------------------------ | copyright ( c ) 1990,1991 Content Technologies Inc. -- all rights reserved
Module : " model forms;sl : whos news : acts : "
version : February 1991 ( v1.8.1 )
(in-package :CTI-source)
(def-category job-event/co!__pers!title-pp)
(def-category job-event/co!__pers!title)
(def-category job-event/co!__!title)
(def-category job-event/co!__)
(def-category job-event/co!__!pers)
(def-category job-event/pers!__!title-pp)
(def-category job-event/pers!__!title)
(def-category job-event/pers!__!pers)
(def-category job-event/pers!__)
(def-category job-event/pers!__!co)
(def-category job-event/title!__)
(def-category job-event)
(def-cfr job-event/pers!__!title-pp
(be job-event/co!__pers!title-pp)
:form vg
:referent (:daughter right-edge))
(def-cfr job-event/pers!__!title
(be job-event/co!__pers!title)
:form vg
:referent (:daughter right-edge))
(def-cfr job-event/pers!__
(be job-event/co!__!pers)
:form vg
:referent (:daughter right-edge))
(def-cfr job-event/title!__
(be/neg job-event/co!__pers!title)
:form vg
:referent (:daughter right-edge))
(def-cfr job-event/pers!__
(be job-event/pers!__)
:form vg
:referent (:daughter right-edge))
(def-cfr job-event/pers!__!title-pp
(modal job-event/pers!__!title-pp)
:form vg
:referent (:daughter right-edge))
(def-cfr job-event/co!__pers!title
(adverb job-event/co!__pers!title)
:referent (:daughter right-edge))
(def-cfr job-event/pers!__!title
(adverb job-event/pers!__!title)
:referent (:daughter right-edge))
(def-cfr job-event/title!__
(adverb job-event/title!__)
:referent (:daughter right-edge))
(def-cfr job-event/pers!__
(job-event/pers!__!title-pp title-pp)
:form VP
:referent (:composite job-event+title
left-edge right-edge))
(def-cfr job-event/pers!__
(job-event/pers!__!title title)
:form VP
:referent (:composite job-event+title
left-edge right-edge))
(def-cfr job-event/co!__
(job-event/co!__!title title)
:form VP
:referent (:composite job-event+title
right-edge left-edge))
( ) " [ pers ] was named to ( the additional post of ... ) "
(def-cfr job-event/pers!__!title
(job-event/pers!__!title "to")
:form vg+prep
:referent (:daughter left-edge))
(def-cfr job-event
(title job-event/title!__)
:form S
:referent (:composite job-event+title
right-edge left-edge))
(def-cfr job-event/pers!__
(job-event/pers!__!pers person)
:form VP
:referent (:composite job-event+replacing
left-edge right-edge))
(def-cfr job-event/co!__!title
(job-event/co!__!pers!title person)
:form VP
:referent (:composite job-event+person
left-edge right-edge))
(def-cfr job-event/co!__!title
(job-event/co!__pers!title person)
:form VP
:referent (:composite job-event+person
left-edge right-edge))
(def-cfr job-event (person job-event/pers!__)
:form S
:referent (:composite job-event+person
left-edge right-edge))
(def-cfr job-event (company job-event/co!__)
:form S
:referent (:composite job-event+company
right-edge left-edge))
(def-cfr job-event/pers!__ (job-event/pers!__!co co)
:form S
:referent (:composite job-event+company
left-edge right-edge))
|
84dbde3ae06def9d24bf4713da16af669c2402fc5b50f66d6443be1b3297e498 | c4-project/c4f | ast.ml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Base_quickcheck
module Tx = Travesty_base_exts
module Ac = C4f_common
module Init = struct
type 'const elt = {id: Ac.C_id.t; value: 'const}
[@@deriving sexp, quickcheck]
type 'const t = 'const elt list [@@deriving sexp, quickcheck]
end
module Decl = struct
type ('const, 'prog) t =
| Program of 'prog
| Init of 'const Init.t
| Post of 'const Postcondition.t
| Locations of Ac.C_id.t list
[@@deriving sexp, variants]
let as_program : (_, 'prog) t -> 'prog option =
Variants.map
~program:(fun _ -> Option.some)
~init:(fun _ _ -> None)
~post:(fun _ _ -> None)
~locations:(fun _ _ -> None)
let as_init : ('const, _) t -> 'const Init.t option =
Variants.map
~program:(fun _ _ -> None)
~init:(fun _ -> Option.some)
~post:(fun _ _ -> None)
~locations:(fun _ _ -> None)
let as_post : ('const, _) t -> 'const Postcondition.t option =
Variants.map
~program:(fun _ _ -> None)
~init:(fun _ _ -> None)
~post:(fun _ -> Option.some)
~locations:(fun _ _ -> None)
let as_locations : (_, _) t -> Ac.C_id.t list option =
Variants.map
~program:(fun _ _ -> None)
~init:(fun _ _ -> None)
~post:(fun _ _ -> None)
~locations:(fun _ -> Option.some)
end
type ('const, 'prog) t =
{language: Ac.C_id.t; name: string; decls: ('const, 'prog) Decl.t list}
[@@deriving sexp, fields]
(** [M] allows AST type creation through referring to an existing language
module. *)
module M (B : sig
module Constant : T
module Program : T
end) =
struct
type nonrec t = (B.Constant.t, B.Program.t) t
end
let get_programs : (_, 'prog) Decl.t list -> 'prog list =
List.filter_map ~f:Decl.as_program
let get_init (decls : ('const, _) Decl.t list) :
(Ac.C_id.t, 'const) List.Assoc.t Or_error.t =
Or_error.(
decls
|> List.filter_map ~f:Decl.as_init
|> Tx.List.one
>>| List.map ~f:(fun {Init.id; value} -> (id, value)))
let get_post (decls : ('const, _) Decl.t list) :
'const Postcondition.t option Or_error.t =
decls |> List.filter_map ~f:Decl.as_post |> Tx.List.at_most_one
let get_locations (decls : (_, _) Decl.t list) :
Ac.C_id.t list option Or_error.t =
decls |> List.filter_map ~f:Decl.as_locations |> Tx.List.at_most_one
let get_header (name : string) (decls : ('const, _) Decl.t list) :
'const Header.t Or_error.t =
Or_error.Let_syntax.(
let%bind init = get_init decls in
let%bind postcondition = get_post decls in
let%map locations = get_locations decls in
Header.make ~name ~init ?postcondition ?locations ())
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/litmus/src/ast.ml | ocaml | * [M] allows AST type creation through referring to an existing language
module. | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Base_quickcheck
module Tx = Travesty_base_exts
module Ac = C4f_common
module Init = struct
type 'const elt = {id: Ac.C_id.t; value: 'const}
[@@deriving sexp, quickcheck]
type 'const t = 'const elt list [@@deriving sexp, quickcheck]
end
module Decl = struct
type ('const, 'prog) t =
| Program of 'prog
| Init of 'const Init.t
| Post of 'const Postcondition.t
| Locations of Ac.C_id.t list
[@@deriving sexp, variants]
let as_program : (_, 'prog) t -> 'prog option =
Variants.map
~program:(fun _ -> Option.some)
~init:(fun _ _ -> None)
~post:(fun _ _ -> None)
~locations:(fun _ _ -> None)
let as_init : ('const, _) t -> 'const Init.t option =
Variants.map
~program:(fun _ _ -> None)
~init:(fun _ -> Option.some)
~post:(fun _ _ -> None)
~locations:(fun _ _ -> None)
let as_post : ('const, _) t -> 'const Postcondition.t option =
Variants.map
~program:(fun _ _ -> None)
~init:(fun _ _ -> None)
~post:(fun _ -> Option.some)
~locations:(fun _ _ -> None)
let as_locations : (_, _) t -> Ac.C_id.t list option =
Variants.map
~program:(fun _ _ -> None)
~init:(fun _ _ -> None)
~post:(fun _ _ -> None)
~locations:(fun _ -> Option.some)
end
type ('const, 'prog) t =
{language: Ac.C_id.t; name: string; decls: ('const, 'prog) Decl.t list}
[@@deriving sexp, fields]
module M (B : sig
module Constant : T
module Program : T
end) =
struct
type nonrec t = (B.Constant.t, B.Program.t) t
end
let get_programs : (_, 'prog) Decl.t list -> 'prog list =
List.filter_map ~f:Decl.as_program
let get_init (decls : ('const, _) Decl.t list) :
(Ac.C_id.t, 'const) List.Assoc.t Or_error.t =
Or_error.(
decls
|> List.filter_map ~f:Decl.as_init
|> Tx.List.one
>>| List.map ~f:(fun {Init.id; value} -> (id, value)))
let get_post (decls : ('const, _) Decl.t list) :
'const Postcondition.t option Or_error.t =
decls |> List.filter_map ~f:Decl.as_post |> Tx.List.at_most_one
let get_locations (decls : (_, _) Decl.t list) :
Ac.C_id.t list option Or_error.t =
decls |> List.filter_map ~f:Decl.as_locations |> Tx.List.at_most_one
let get_header (name : string) (decls : ('const, _) Decl.t list) :
'const Header.t Or_error.t =
Or_error.Let_syntax.(
let%bind init = get_init decls in
let%bind postcondition = get_post decls in
let%map locations = get_locations decls in
Header.make ~name ~init ?postcondition ?locations ())
|
fa4037474b17f350b4302850dc845f75d77d2a8086f51cdaa412a56c300000aa | coot/free-algebras | Free.hs | {-# LANGUAGE CPP #-}
# LANGUAGE TemplateHaskell #
module Test.Data.Group.Free
( tests
) where
#if __GLASGOW_HASKELL__ < 808
import Data.Semigroup (Semigroup (..))
#endif
import Data.Bool (bool)
import Data.Group (invert)
import Data.DList (DList)
import qualified Data.DList as DList
import Hedgehog (Property, Gen, property, (===))
import qualified Hedgehog as H
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Data.Group.Free (fromDList, normalize, fromList, normalizeL)
genList :: Gen a -> Gen [Either a a]
genList gen =
Gen.list (Range.linear 0 100) gen'
where
gen' = Gen.bool >>= bool (Right <$> gen) (Left <$> gen)
genDList :: Gen a -> Gen (DList (Either a a))
genDList gen = DList.fromList <$> genList gen
prop_normalize :: Property
prop_normalize = property $ do
as <- H.forAll (genDList Gen.bool)
normalize (normalize as) === normalize as
normalize (as `DList.append` rev as) === DList.empty
where
rev :: DList (Either a a) -> DList (Either a a)
rev = DList.foldr (\a as -> DList.snoc as (either Right Left a)) DList.empty
prop_invert :: Property
prop_invert = property $ do
fg <- fromDList <$> H.forAll (genDList Gen.bool)
invert (invert fg) === fg
invert fg <> fg === mempty
fg <> invert fg === mempty
prop_unit :: Property
prop_unit = property $ do
fg <- fromDList <$> H.forAll (genDList Gen.bool)
fg <> mempty === fg
mempty <> fg === fg
prop_associativity :: Property
prop_associativity = property $ do
fg <- fromDList <$> H.forAll (genDList Gen.bool)
fg' <- fromDList <$> H.forAll (genDList Gen.bool)
fg'' <- fromDList <$> H.forAll (genDList Gen.bool)
(fg <> fg') <> fg'' === fg <> (fg' <> fg'')
prop_normalizeL :: Property
prop_normalizeL = property $ do
as <- H.forAll (genList Gen.bool)
normalizeL (normalizeL as) === normalizeL as
normalizeL (as ++ rev as) === []
where
rev :: [Either a a] -> [Either a a]
rev = foldl (\as a -> either Right Left a : as) []
prop_invertL :: Property
prop_invertL = property $ do
fg <- fromList <$> H.forAll (genList Gen.bool)
invert (invert fg) === fg
invert fg <> fg === mempty
fg <> invert fg === mempty
prop_unitL :: Property
prop_unitL = property $ do
fg <- fromList <$> H.forAll (genList Gen.bool)
fg <> mempty === fg
mempty <> fg === fg
prop_associativityL :: Property
prop_associativityL = property $ do
fg <- fromList <$> H.forAll (genList Gen.bool)
fg' <- fromList <$> H.forAll (genList Gen.bool)
fg'' <- fromList <$> H.forAll (genList Gen.bool)
(fg <> fg') <> fg'' === fg <> (fg' <> fg'')
tests :: IO Bool
tests = H.checkParallel $$(H.discover)
| null | https://raw.githubusercontent.com/coot/free-algebras/78481662438a66d0af217133eab7769d44bc77e2/test/Test/Data/Group/Free.hs | haskell | # LANGUAGE CPP # | # LANGUAGE TemplateHaskell #
module Test.Data.Group.Free
( tests
) where
#if __GLASGOW_HASKELL__ < 808
import Data.Semigroup (Semigroup (..))
#endif
import Data.Bool (bool)
import Data.Group (invert)
import Data.DList (DList)
import qualified Data.DList as DList
import Hedgehog (Property, Gen, property, (===))
import qualified Hedgehog as H
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Data.Group.Free (fromDList, normalize, fromList, normalizeL)
genList :: Gen a -> Gen [Either a a]
genList gen =
Gen.list (Range.linear 0 100) gen'
where
gen' = Gen.bool >>= bool (Right <$> gen) (Left <$> gen)
genDList :: Gen a -> Gen (DList (Either a a))
genDList gen = DList.fromList <$> genList gen
prop_normalize :: Property
prop_normalize = property $ do
as <- H.forAll (genDList Gen.bool)
normalize (normalize as) === normalize as
normalize (as `DList.append` rev as) === DList.empty
where
rev :: DList (Either a a) -> DList (Either a a)
rev = DList.foldr (\a as -> DList.snoc as (either Right Left a)) DList.empty
prop_invert :: Property
prop_invert = property $ do
fg <- fromDList <$> H.forAll (genDList Gen.bool)
invert (invert fg) === fg
invert fg <> fg === mempty
fg <> invert fg === mempty
prop_unit :: Property
prop_unit = property $ do
fg <- fromDList <$> H.forAll (genDList Gen.bool)
fg <> mempty === fg
mempty <> fg === fg
prop_associativity :: Property
prop_associativity = property $ do
fg <- fromDList <$> H.forAll (genDList Gen.bool)
fg' <- fromDList <$> H.forAll (genDList Gen.bool)
fg'' <- fromDList <$> H.forAll (genDList Gen.bool)
(fg <> fg') <> fg'' === fg <> (fg' <> fg'')
prop_normalizeL :: Property
prop_normalizeL = property $ do
as <- H.forAll (genList Gen.bool)
normalizeL (normalizeL as) === normalizeL as
normalizeL (as ++ rev as) === []
where
rev :: [Either a a] -> [Either a a]
rev = foldl (\as a -> either Right Left a : as) []
prop_invertL :: Property
prop_invertL = property $ do
fg <- fromList <$> H.forAll (genList Gen.bool)
invert (invert fg) === fg
invert fg <> fg === mempty
fg <> invert fg === mempty
prop_unitL :: Property
prop_unitL = property $ do
fg <- fromList <$> H.forAll (genList Gen.bool)
fg <> mempty === fg
mempty <> fg === fg
prop_associativityL :: Property
prop_associativityL = property $ do
fg <- fromList <$> H.forAll (genList Gen.bool)
fg' <- fromList <$> H.forAll (genList Gen.bool)
fg'' <- fromList <$> H.forAll (genList Gen.bool)
(fg <> fg') <> fg'' === fg <> (fg' <> fg'')
tests :: IO Bool
tests = H.checkParallel $$(H.discover)
|
133992bccacb4d2702e441b9f5f32d2516a721a06c2207668c1ae1cc7e09a20b | cedlemo/OCaml-GLib2 | gen.ml | module BG = GI_bindings_generator
module Loader = BG.Loader
(** The namespace to be loaded: ie. the lib for which the bindings will be
* generated. *)
let namespace = "GLib"
let version = "2.0"
* A suffix for the filenames of the raw bindings of the Core part . For example ,
* all the constants and functions defined directly in the namespace are defined
* in a " Core " module and generated in " Core.ml " and " Core.mli " files . But , in
* in order to be able to tweak those automatically generated bindings , a
* suffix is added . Here , all the constants and functions of the namespaces
* will be found in the module Core_raw . Then in the lib / Core.ml file , I just
* load / open the Core_raw .
* all the constants and functions defined directly in the namespace are defined
* in a "Core" module and generated in "Core.ml" and "Core.mli" files. But, in
* in order to be able to tweak those automatically generated bindings, a
* suffix is added. Here, all the constants and functions of the namespaces
* will be found in the module Core_raw. Then in the lib/Core.ml file, I just
* load/open the Core_raw. *)
let files_suffix = "Raw"
(** Instead of generate all the data structures (and theirs related methods or
* constants), the idea is to choose what is needed. *)
let data_structures =
["Error"; "Rand"; "Date"; "DateTime"; "TimeVal"; "TimeZone";]
(** One can choose to skip the bindings of some constants because they are not
* needed or because you want to create manually the bindings in the "Core.ml"
* file. *)
let const_to_skip = ["MAJOR_VERSION"; "MINOR_VERSION"; "MICRO_VERSION"]
(** Like for the data_structures, you have to choose with function should have
* its bindings generated. *)
let functions = ["random_double"; "random_double_range";
"random_int"; "random_int_range";
"get_current_time";
"filename_to_uri"; "get_charset";
"dir_make_tmp"]
let cwd = Sys.getcwd ()
let dest_dir = cwd ^ "/lib"
let sources = Loader.generate_files dest_dir ("Core" ^ files_suffix)
let () =
let () = Loader.write_constant_bindings_for namespace ~version sources const_to_skip in
let () = Loader.write_function_bindings_for namespace ~version sources functions in
let () = Loader.write_enum_and_flag_bindings_for namespace ~version dest_dir () in
let () = Loader.write_bindings_for namespace ~version dest_dir data_structures in
BG.Binding_utils.Sources.close sources
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GLib2/084a148faa4f18d0ddf78315d57c1d623aa9522c/generator/gen.ml | ocaml | * The namespace to be loaded: ie. the lib for which the bindings will be
* generated.
* Instead of generate all the data structures (and theirs related methods or
* constants), the idea is to choose what is needed.
* One can choose to skip the bindings of some constants because they are not
* needed or because you want to create manually the bindings in the "Core.ml"
* file.
* Like for the data_structures, you have to choose with function should have
* its bindings generated. | module BG = GI_bindings_generator
module Loader = BG.Loader
let namespace = "GLib"
let version = "2.0"
* A suffix for the filenames of the raw bindings of the Core part . For example ,
* all the constants and functions defined directly in the namespace are defined
* in a " Core " module and generated in " Core.ml " and " Core.mli " files . But , in
* in order to be able to tweak those automatically generated bindings , a
* suffix is added . Here , all the constants and functions of the namespaces
* will be found in the module Core_raw . Then in the lib / Core.ml file , I just
* load / open the Core_raw .
* all the constants and functions defined directly in the namespace are defined
* in a "Core" module and generated in "Core.ml" and "Core.mli" files. But, in
* in order to be able to tweak those automatically generated bindings, a
* suffix is added. Here, all the constants and functions of the namespaces
* will be found in the module Core_raw. Then in the lib/Core.ml file, I just
* load/open the Core_raw. *)
let files_suffix = "Raw"
let data_structures =
["Error"; "Rand"; "Date"; "DateTime"; "TimeVal"; "TimeZone";]
let const_to_skip = ["MAJOR_VERSION"; "MINOR_VERSION"; "MICRO_VERSION"]
let functions = ["random_double"; "random_double_range";
"random_int"; "random_int_range";
"get_current_time";
"filename_to_uri"; "get_charset";
"dir_make_tmp"]
let cwd = Sys.getcwd ()
let dest_dir = cwd ^ "/lib"
let sources = Loader.generate_files dest_dir ("Core" ^ files_suffix)
let () =
let () = Loader.write_constant_bindings_for namespace ~version sources const_to_skip in
let () = Loader.write_function_bindings_for namespace ~version sources functions in
let () = Loader.write_enum_and_flag_bindings_for namespace ~version dest_dir () in
let () = Loader.write_bindings_for namespace ~version dest_dir data_structures in
BG.Binding_utils.Sources.close sources
|
30981cf17e01c5d826ae1ad4d84c571dc1a16d03f654ff41c283d4098776098a | SquidDev/urn | matrix.lisp | (import test ())
(import math/numerics ())
(import math/matrix ())
(describe "The math library has matrices which"
(can "be compared"
(affirm (eq? (matrix 2 2 1 2 3 4) (matrix 2 2 1 2 3 4))
(neq? (matrix 2 2 1 2 3 4) (matrix 2 2 1 2 4 3))))
(can "be queried"
(with (m (matrix 2 2 1 2 3 4))
(affirm (eq? 1 (matrix-item m 1 1))
(eq? 2 (matrix-item m 1 2))
(eq? 3 (matrix-item m 2 1))
(eq? 4 (matrix-item m 2 2)))))
(it "has an identity"
(affirm (eq? (matrix 2 2 1 0 0 1) (identity 2))))
(can "be added"
(check [(number a1) (number a2)
(number b1) (number b2)]
(eq? (matrix 1 2 (+ a1 b1) (+ a2 b2))
(n+ (matrix 1 2 a1 a2) (matrix 1 2 b1 b2)))))
(can "be subtracted"
(check [(number a1) (number a2)
(number b1) (number b2)]
(eq? (matrix 1 2 (- a1 b1) (- a2 b2))
(n- (matrix 1 2 a1 a2) (matrix 1 2 b1 b2)))))
(can "be multiplied"
(check [(number a1) (number a2) (number a3) (number a4)
(number b1) (number b2) (number b3) (number b4)]
(eq? (matrix 2 2
(+ (* a1 b1) (n* a2 b3)) (n+ (* a1 b2) (n* a2 b4))
(+ (* a3 b1) (n* a4 b3)) (n+ (* a3 b2) (n* a4 b4)))
(n* (matrix 2 2 a1 a2 a3 a4)
(matrix 2 2 b1 b2 b3 b4)))))
(can "be multiplied with fixed matrices"
(let [(a (matrix 1 3 1 2 3))
(b (matrix 3 1 1 2 3))]
(affirm (eq? (matrix 1 1 14) (n* b a))
(eq? (matrix 3 3
1 2 3
2 4 6
3 6 9) (n* a b)))))
(can "be converted to row echelon form"
(affirm (eq? (matrix 3 2
1 1.25 1.5
0 1 2)
(echelon
(matrix 3 2
1 2 3
4 5 6)))))
(can "be converted to reduced row echelon form"
(affirm (eq? (matrix 3 2
1 0 -1
0 1 2)
(reduced-echelon
(matrix 3 2
1 2 3
4 5 6))))))
| null | https://raw.githubusercontent.com/SquidDev/urn/6e6717cf1376b0950e569e3771cb7e287aed291d/tests/lib/math/matrix.lisp | lisp | (import test ())
(import math/numerics ())
(import math/matrix ())
(describe "The math library has matrices which"
(can "be compared"
(affirm (eq? (matrix 2 2 1 2 3 4) (matrix 2 2 1 2 3 4))
(neq? (matrix 2 2 1 2 3 4) (matrix 2 2 1 2 4 3))))
(can "be queried"
(with (m (matrix 2 2 1 2 3 4))
(affirm (eq? 1 (matrix-item m 1 1))
(eq? 2 (matrix-item m 1 2))
(eq? 3 (matrix-item m 2 1))
(eq? 4 (matrix-item m 2 2)))))
(it "has an identity"
(affirm (eq? (matrix 2 2 1 0 0 1) (identity 2))))
(can "be added"
(check [(number a1) (number a2)
(number b1) (number b2)]
(eq? (matrix 1 2 (+ a1 b1) (+ a2 b2))
(n+ (matrix 1 2 a1 a2) (matrix 1 2 b1 b2)))))
(can "be subtracted"
(check [(number a1) (number a2)
(number b1) (number b2)]
(eq? (matrix 1 2 (- a1 b1) (- a2 b2))
(n- (matrix 1 2 a1 a2) (matrix 1 2 b1 b2)))))
(can "be multiplied"
(check [(number a1) (number a2) (number a3) (number a4)
(number b1) (number b2) (number b3) (number b4)]
(eq? (matrix 2 2
(+ (* a1 b1) (n* a2 b3)) (n+ (* a1 b2) (n* a2 b4))
(+ (* a3 b1) (n* a4 b3)) (n+ (* a3 b2) (n* a4 b4)))
(n* (matrix 2 2 a1 a2 a3 a4)
(matrix 2 2 b1 b2 b3 b4)))))
(can "be multiplied with fixed matrices"
(let [(a (matrix 1 3 1 2 3))
(b (matrix 3 1 1 2 3))]
(affirm (eq? (matrix 1 1 14) (n* b a))
(eq? (matrix 3 3
1 2 3
2 4 6
3 6 9) (n* a b)))))
(can "be converted to row echelon form"
(affirm (eq? (matrix 3 2
1 1.25 1.5
0 1 2)
(echelon
(matrix 3 2
1 2 3
4 5 6)))))
(can "be converted to reduced row echelon form"
(affirm (eq? (matrix 3 2
1 0 -1
0 1 2)
(reduced-echelon
(matrix 3 2
1 2 3
4 5 6))))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.