_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
ada6ab6818a8ff9aac461caf5a53bcb7ab50af4f4a6416fbcaa299a69121cc27
cachix/cachix
Orphans.hs
# OPTIONS_GHC -Wno - orphans # module Cachix.Client.Config.Orphans where import qualified Dhall import qualified Dhall.Core import Protolude hiding (toS) import Protolude.Conv import Servant.Auth.Client instance Dhall.FromDhall Token where autoWith _ = Dhall.strictText {Dhall.extract = ex} where ex (Dhall.Core.TextLit (Dhall.Core.Chunks [] t)) = pure (Token (toS t)) ex _ = panic "Unexpected Dhall value. Did it typecheck?" instance Dhall.ToDhall Token where injectWith _ = Dhall.Encoder { Dhall.embed = Dhall.Core.TextLit . Dhall.Core.Chunks [] . toS . getToken, Dhall.declared = Dhall.Core.Text }
null
https://raw.githubusercontent.com/cachix/cachix/4c9397689598a3f2ea6123ddc556a105fe7b4c9c/cachix/src/Cachix/Client/Config/Orphans.hs
haskell
# OPTIONS_GHC -Wno - orphans # module Cachix.Client.Config.Orphans where import qualified Dhall import qualified Dhall.Core import Protolude hiding (toS) import Protolude.Conv import Servant.Auth.Client instance Dhall.FromDhall Token where autoWith _ = Dhall.strictText {Dhall.extract = ex} where ex (Dhall.Core.TextLit (Dhall.Core.Chunks [] t)) = pure (Token (toS t)) ex _ = panic "Unexpected Dhall value. Did it typecheck?" instance Dhall.ToDhall Token where injectWith _ = Dhall.Encoder { Dhall.embed = Dhall.Core.TextLit . Dhall.Core.Chunks [] . toS . getToken, Dhall.declared = Dhall.Core.Text }
4f348fc0afce7824acd5bd938915914dadd97d087449d96f95727811f1ed0127
IBM/wcs-ocaml
context_spel.ml
* This file is part of the Watson Conversation Service OCaml API project . * * Copyright 2016 - 2017 IBM Corporation * * Licensed under the Apache License , Version 2.0 ( the " License " ) ; * you may not use this file except in compliance with the License . * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing , software * distributed under the License is distributed on an " AS IS " BASIS , * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . * See the License for the specific language governing permissions and * limitations under the License . * This file is part of the Watson Conversation Service OCaml API project. * * Copyright 2016-2017 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) (** Context utilities. *) open Wcs_t * { 6 . skip_user_input } let skip_user_input (b: bool) : json_spel = Json_spel.assoc [Context.skip_user_input_lbl, Json_spel.bool b] let set_skip_user_input (ctx: json_spel) (b: bool) : json_spel = Json_spel.set ctx Context.skip_user_input_lbl (`Bool b) let take_skip_user_input (ctx: json_spel) : json_spel * bool = begin match Json_spel.take ctx Context.skip_user_input_lbl with | ctx, Some (`Bool b) -> ctx, b | _ -> ctx, false end * { 6 . Actions } let actions (acts: action list) : json_spel = Json_spel.assoc [Context.actions_lbl, Json_spel.list (List.map Wcs.json_spel_of_action acts)] let actions_def (acts: action_def list) : json_spel = Json_spel.assoc [Context.actions_lbl, Json_spel.list (List.map Wcs.json_spel_of_action_def acts)] let json_spel_of_action (act : action) : json_spel = let json = Wcs.json_of_action act in let json_spel = Json_spel.of_json json in json_spel let action_of_json_spel (act : json_spel) : action = Wcs_j.action_of_string (Yojson.Basic.to_string (Json_spel.to_json act)) let set_actions ctx (acts: action list) : json_spel = let js_acts = List.map json_spel_of_action acts in Json_spel.set ctx Context.actions_lbl (`List js_acts) let take_actions (ctx: json_spel) : json_spel * action list option = begin match Json_spel.take ctx Context.actions_lbl with | ctx', Some (`List acts) -> begin try ctx', Some (List.map action_of_json_spel acts) with _ -> Log.warning "Context_spel" (Format.sprintf "illed formed actions:\n%s@." (Yojson.Basic.pretty_to_string (Json_spel.to_json (`List acts)))); ctx, None end | _, Some o -> Log.warning "Context_spel" (Format.sprintf "illed formed actions:\n%s@." (Yojson.Basic.pretty_to_string (Json_spel.to_json o))); ctx, None | _, None -> ctx, None end let push_action (ctx: json_spel) (act: action) : json_spel = begin match take_actions ctx with | ctx, None -> set_actions ctx [ act ] | ctx, Some acts -> set_actions ctx (acts @ [ act ]) end let pop_action (ctx: json_spel) : json_spel * action option = begin match take_actions ctx with | ctx', Some (act :: acts) -> set_actions ctx' acts, Some act | _ -> ctx, None end * { 6 . Continuation } let set_continuation (ctx: json_spel) (k: action) : json_spel = Json_spel.set ctx Context.continuation_lbl (json_spel_of_action k) let take_continuation (ctx: json_spel) : json_spel * action option = begin match Json_spel.take ctx Context.continuation_lbl with | ctx', Some act -> begin try ctx', Some (action_of_json_spel act) with _ -> Log.warning "Context_spel" (Format.sprintf "illed formed continuation:\n%s@." (Yojson.Basic.pretty_to_string (Json_spel.to_json act))); ctx, None end | _ -> ctx, None end let get_continuation (ctx: json_spel) : action option = let _, act = take_continuation ctx in act * { 6 . Return } let return (v: json_spel) : json_spel = Json_spel.assoc [Context.return_lbl, v] let set_return (ctx: json_spel) (x: json_spel) : json_spel = Json_spel.set ctx Context.return_lbl x let get_return (ctx: json_spel) : json_spel option = Json_spel.get ctx Context.return_lbl
null
https://raw.githubusercontent.com/IBM/wcs-ocaml/b237b7057f44caa09d36e466be015e2bc3173dd5/wcs-lib/context_spel.ml
ocaml
* Context utilities.
* This file is part of the Watson Conversation Service OCaml API project . * * Copyright 2016 - 2017 IBM Corporation * * Licensed under the Apache License , Version 2.0 ( the " License " ) ; * you may not use this file except in compliance with the License . * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing , software * distributed under the License is distributed on an " AS IS " BASIS , * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . * See the License for the specific language governing permissions and * limitations under the License . * This file is part of the Watson Conversation Service OCaml API project. * * Copyright 2016-2017 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) open Wcs_t * { 6 . skip_user_input } let skip_user_input (b: bool) : json_spel = Json_spel.assoc [Context.skip_user_input_lbl, Json_spel.bool b] let set_skip_user_input (ctx: json_spel) (b: bool) : json_spel = Json_spel.set ctx Context.skip_user_input_lbl (`Bool b) let take_skip_user_input (ctx: json_spel) : json_spel * bool = begin match Json_spel.take ctx Context.skip_user_input_lbl with | ctx, Some (`Bool b) -> ctx, b | _ -> ctx, false end * { 6 . Actions } let actions (acts: action list) : json_spel = Json_spel.assoc [Context.actions_lbl, Json_spel.list (List.map Wcs.json_spel_of_action acts)] let actions_def (acts: action_def list) : json_spel = Json_spel.assoc [Context.actions_lbl, Json_spel.list (List.map Wcs.json_spel_of_action_def acts)] let json_spel_of_action (act : action) : json_spel = let json = Wcs.json_of_action act in let json_spel = Json_spel.of_json json in json_spel let action_of_json_spel (act : json_spel) : action = Wcs_j.action_of_string (Yojson.Basic.to_string (Json_spel.to_json act)) let set_actions ctx (acts: action list) : json_spel = let js_acts = List.map json_spel_of_action acts in Json_spel.set ctx Context.actions_lbl (`List js_acts) let take_actions (ctx: json_spel) : json_spel * action list option = begin match Json_spel.take ctx Context.actions_lbl with | ctx', Some (`List acts) -> begin try ctx', Some (List.map action_of_json_spel acts) with _ -> Log.warning "Context_spel" (Format.sprintf "illed formed actions:\n%s@." (Yojson.Basic.pretty_to_string (Json_spel.to_json (`List acts)))); ctx, None end | _, Some o -> Log.warning "Context_spel" (Format.sprintf "illed formed actions:\n%s@." (Yojson.Basic.pretty_to_string (Json_spel.to_json o))); ctx, None | _, None -> ctx, None end let push_action (ctx: json_spel) (act: action) : json_spel = begin match take_actions ctx with | ctx, None -> set_actions ctx [ act ] | ctx, Some acts -> set_actions ctx (acts @ [ act ]) end let pop_action (ctx: json_spel) : json_spel * action option = begin match take_actions ctx with | ctx', Some (act :: acts) -> set_actions ctx' acts, Some act | _ -> ctx, None end * { 6 . Continuation } let set_continuation (ctx: json_spel) (k: action) : json_spel = Json_spel.set ctx Context.continuation_lbl (json_spel_of_action k) let take_continuation (ctx: json_spel) : json_spel * action option = begin match Json_spel.take ctx Context.continuation_lbl with | ctx', Some act -> begin try ctx', Some (action_of_json_spel act) with _ -> Log.warning "Context_spel" (Format.sprintf "illed formed continuation:\n%s@." (Yojson.Basic.pretty_to_string (Json_spel.to_json act))); ctx, None end | _ -> ctx, None end let get_continuation (ctx: json_spel) : action option = let _, act = take_continuation ctx in act * { 6 . Return } let return (v: json_spel) : json_spel = Json_spel.assoc [Context.return_lbl, v] let set_return (ctx: json_spel) (x: json_spel) : json_spel = Json_spel.set ctx Context.return_lbl x let get_return (ctx: json_spel) : json_spel option = Json_spel.get ctx Context.return_lbl
17a606cc75f6dfaa02878bdf12702a7489f2ab3b3823f95c481af48cd6ea5238
fukamachi/.lem
10-vi.lisp
(defpackage #:lem-my-init/modes/vi (:use #:cl #:lem #:lem-vi-mode)) (in-package #:lem-my-init/modes/vi) (lem-vi-mode:vi-mode) (define-key *minibuf-keymap* "C-w" 'lem-vi-mode.commands:vi-kill-last-word)
null
https://raw.githubusercontent.com/fukamachi/.lem/524f6f669fdc50a8fbddfbdc5d7e29ae945dacfd/modes/10-vi.lisp
lisp
(defpackage #:lem-my-init/modes/vi (:use #:cl #:lem #:lem-vi-mode)) (in-package #:lem-my-init/modes/vi) (lem-vi-mode:vi-mode) (define-key *minibuf-keymap* "C-w" 'lem-vi-mode.commands:vi-kill-last-word)
8109d80ae4c3c729009bf270b8dbb33be6ce239d9188679840c34b76fca033b9
tomjaguarpaw/haskell-opaleye
Operators.hs
{-# LANGUAGE Arrows #-} # LANGUAGE FlexibleContexts # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE FunctionalDependencies # # LANGUAGE DataKinds # We can probably disable ConstraintKinds and TypeSynonymInstances when we move to ... instead of PG .. module Opaleye.Operators ( -- * Restriction operators where_ , restrict , restrictExists , restrictNotExists -- * Numerical operators | Numeric ' Column ' / ' F.Field ' types are instances of ' ' and ' Fractional ' , so you can use the standard Haskell numerical -- operators (e.g.. '*', '/', '+', '-') on them and you can create them with numerical literals such as @3.14 : : ' F.Field ' ' T.SqlFloat8'@. , (+) , (-) , (*) , (/) , fromInteger , abs , negate , signum -- * Equality operators , (.==) , (./=) , (.===) , (./==) -- * Comparison operators , (.>) , (.<) , (.<=) , (.>=) -- * Numerical operators , quot_ , rem_ -- * Conditional operators , case_ , ifThenElse , ifThenElseMany -- * Logical operators , (.||) , (.&&) , not , ors -- * Text operators , (.++) , lower , upper , like , ilike , sqlLength -- * Containment operators , in_ , inSelect -- * JSON operators , SqlIsJson , SqlJsonIndex , PGJsonIndex , (.->) , (.->>) , (.#>) , (.#>>) , (.@>) , (.<@) , (.?) , (.?|) , (.?&) , JBOF.jsonBuildObject , JBOF.jsonBuildObjectField , JBOF.JSONBuildObjectFields * SqlArray operators , emptyArray , arrayAppend , arrayPrepend , arrayRemove , arrayRemoveNulls , singletonArray , index , arrayPosition , sqlElem -- * Range operators , overlap , liesWithin , upperBound , lowerBound , (.<<) , (.>>) , (.&<) , (.&>) , (.-|-) -- * Other operators , timestamptzAtTimeZone , dateOfTimestamp , now , IntervalNum , addInterval , minusInterval -- * Deprecated , keepWhen ) where import qualified Control.Arrow as A import qualified Data.Foldable as F hiding (null) import qualified Data.List.NonEmpty as NEL import Prelude hiding (not) import qualified Opaleye.Exists as E import qualified Opaleye.Field as F import Opaleye.Internal.Column (Field_(Column), Field, FieldNullable, Nullability(Nullable), unsafeCase_, unsafeIfThenElse, unsafeGt) import qualified Opaleye.Internal.Column as C import qualified Opaleye.Internal.JSONBuildObjectFields as JBOF import Opaleye.Internal.QueryArr (SelectArr(QueryArr), runSimpleQueryArr') import qualified Opaleye.Internal.PrimQuery as PQ import qualified Opaleye.Internal.Operators as O import Opaleye.Internal.Helpers ((.:)) import qualified Opaleye.Lateral as L import qualified Opaleye.Order as Ord import qualified Opaleye.Select as S import qualified Opaleye.SqlTypes as T import qualified Opaleye.Column as Column import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ import qualified Data.Profunctor.Product.Default as D | Keep only the rows of a query satisfying a given condition , using an SQL @WHERE@ clause . It is equivalent to the Haskell function @ where _ : : Bool - > [ ( ) ] where _ True = [ ( ) ] where _ False = [ ] @ SQL @WHERE@ clause. It is equivalent to the Haskell function @ where_ :: Bool -> [()] where_ True = [()] where_ False = [] @ -} where_ :: F.Field T.SqlBool -> S.Select () where_ = L.viaLateral restrict {-| You would typically use 'restrict' if you want to write your query using 'A.Arrow' notation. If you want to use monadic style then 'where_' will suit you better. -} restrict :: S.SelectArr (F.Field T.SqlBool) () restrict = O.restrict {-| Add a @WHERE EXISTS@ clause to the current query. -} restrictExists :: S.SelectArr a b -> S.SelectArr a () restrictExists criteria = QueryArr f where -- A where exists clause can always refer to columns defined by the query it references so needs no special treatment on LATERAL . f a = do (_, existsQ) <- runSimpleQueryArr' criteria a pure ((), PQ.aSemijoin PQ.Semi existsQ) | Add a @WHERE NOT clause to the current query . restrictNotExists :: S.SelectArr a b -> S.SelectArr a () restrictNotExists criteria = QueryArr f where -- A where exists clause can always refer to columns defined by the query it references so needs no special treatment on LATERAL . f a = do (_, existsQ) <- runSimpleQueryArr' criteria a pure ((), PQ.aSemijoin PQ.Anti existsQ) infix 4 .== (.==) :: Field a -> Field a -> F.Field T.SqlBool (.==) = C.binOp (HPQ.:==) infix 4 ./= (./=) :: Field a -> Field a -> F.Field T.SqlBool (./=) = C.binOp (HPQ.:<>) infix 4 .=== -- | A polymorphic equality operator that works for all types that you -- have run `makeAdaptorAndInstance` on. This may be unified with ` .== ` in a future version . (.===) :: D.Default O.EqPP fields fields => fields -> fields -> F.Field T.SqlBool (.===) = (O..==) infix 4 ./== -- | A polymorphic inequality operator that works for all types that -- you have run `makeAdaptorAndInstance` on. This may be unified with -- `./=` in a future version. (./==) :: D.Default O.EqPP fields fields => fields -> fields -> F.Field T.SqlBool (./==) = Opaleye.Operators.not .: (O..==) infix 4 .> (.>) :: Ord.SqlOrd a => Field a -> Field a -> F.Field T.SqlBool (.>) = unsafeGt infix 4 .< (.<) :: Ord.SqlOrd a => Field a -> Field a -> F.Field T.SqlBool (.<) = C.binOp (HPQ.:<) infix 4 .<= (.<=) :: Ord.SqlOrd a => Field a -> Field a -> F.Field T.SqlBool (.<=) = C.binOp (HPQ.:<=) infix 4 .>= (.>=) :: Ord.SqlOrd a => Field a -> Field a -> F.Field T.SqlBool (.>=) = C.binOp (HPQ.:>=) | Integral division , named after ' Prelude.quot ' . It maps to the @/@ operator in Postgres . quot_ :: C.SqlIntegral a => Field a -> Field a -> Field a quot_ = C.binOp (HPQ.:/) | The remainder of integral division , named after ' ' . It maps to ' MOD ' ( ' % ' ) in Postgres , confusingly described as -- "modulo (remainder)". rem_ :: C.SqlIntegral a => Field a -> Field a -> Field a rem_ = C.binOp HPQ.OpMod | Select the first case for which the condition is true . case_ :: [(F.Field T.SqlBool, Field_ n a)] -> Field_ n a -> Field_ n a case_ = unsafeCase_ | if\/then\/else . -- -- This may be replaced by 'ifThenElseMany' in a future version. ifThenElse :: F.Field T.SqlBool -> Field_ n a -> Field_ n a -> Field_ n a ifThenElse = unsafeIfThenElse -- | Polymorphic if\/then\/else. ifThenElseMany :: D.Default O.IfPP fields fields => F.Field T.SqlBool -> fields -> fields -> fields ifThenElseMany = O.ifExplict D.def infixr 2 .|| -- | Boolean or (.||) :: F.Field T.SqlBool -> F.Field T.SqlBool -> F.Field T.SqlBool (.||) = (O..||) infixr 3 .&& -- | Boolean and (.&&) :: F.Field T.SqlBool -> F.Field T.SqlBool -> F.Field T.SqlBool (.&&) = (O..&&) -- | Boolean not not :: F.Field T.SqlBool -> F.Field T.SqlBool not = O.not -- | True when any element of the container is true ors :: F.Foldable f => f (F.Field T.SqlBool) -> F.Field T.SqlBool ors = F.foldl' (.||) (T.sqlBool False) -- | Concatenate 'F.Field' 'T.SqlText' (.++) :: F.Field T.SqlText -> F.Field T.SqlText -> F.Field T.SqlText (.++) = C.binOp (HPQ.:||) -- | To lowercase lower :: F.Field T.SqlText -> F.Field T.SqlText lower = C.unOp HPQ.OpLower -- | To uppercase upper :: F.Field T.SqlText -> F.Field T.SqlText upper = C.unOp HPQ.OpUpper -- | Postgres @LIKE@ operator like :: F.Field T.SqlText -> F.Field T.SqlText -> F.Field T.SqlBool like = C.binOp HPQ.OpLike -- | Postgres @ILIKE@ operator ilike :: F.Field T.SqlText -> F.Field T.SqlText -> F.Field T.SqlBool ilike = C.binOp HPQ.OpILike sqlLength :: C.SqlString a => F.Field a -> F.Field T.SqlInt4 sqlLength (Column e) = Column (HPQ.FunExpr "length" [e]) -- | 'in_' is designed to be used in prefix form. -- -- 'in_' @validProducts@ @product@ checks whether @product@ is a valid -- product. 'in_' @validProducts@ is a function which checks whether -- a product is a valid product. in_ :: (Functor f, F.Foldable f) => f (Field a) -> Field a -> F.Field T.SqlBool in_ fcas (Column a) = case NEL.nonEmpty (F.toList fcas) of Nothing -> T.sqlBool False Just xs -> Column $ HPQ.BinExpr HPQ.OpIn a (HPQ.ListExpr (fmap C.unColumn xs)) | True if the first argument occurs amongst the rows of the second , -- false otherwise. -- This operation is equivalent to Postgres 's @IN@ operator . inSelect :: D.Default O.EqPP fields fields => fields -> S.Select fields -> S.Select (F.Field T.SqlBool) inSelect c q = E.exists (keepWhen (c .===) A.<<< q) -- | Class of Postgres types that represent json values. -- Used to overload functions and operators that work on both 'T.SqlJson' and 'T.SqlJsonb'. -- -- Warning: making additional instances of this class can lead to broken code! class SqlIsJson json instance SqlIsJson T.SqlJson instance SqlIsJson T.SqlJsonb -- | Class of Postgres types that can be used to index json values. -- -- Warning: making additional instances of this class can lead to broken code! class SqlJsonIndex a -- | Use 'SqlJsonIndex' instead. Will be deprecated in a future version. type PGJsonIndex = SqlJsonIndex instance SqlJsonIndex T.SqlInt4 instance SqlJsonIndex T.SqlInt8 instance SqlJsonIndex T.SqlText -- | Get JSON object field by key. infixl 8 .-> (.->) :: (SqlIsJson json, SqlJsonIndex k) => F.FieldNullable json -- ^ -> F.Field k -- ^ key or index -> F.FieldNullable json (.->) = C.binOp (HPQ.:->) -- | Get JSON object field as text. infixl 8 .->> (.->>) :: (SqlIsJson json, SqlJsonIndex k) => F.FieldNullable json -- ^ -> F.Field k -- ^ key or index -> F.FieldNullable T.SqlText (.->>) = C.binOp (HPQ.:->>) -- | Get JSON object at specified path. infixl 8 .#> (.#>) :: (SqlIsJson json) => F.FieldNullable json -- ^ -> Field (T.SqlArray T.SqlText) -- ^ path -> F.FieldNullable json (.#>) = C.binOp (HPQ.:#>) -- | Get JSON object at specified path as text. infixl 8 .#>> (.#>>) :: (SqlIsJson json) => F.FieldNullable json -- ^ -> Field (T.SqlArray T.SqlText) -- ^ path -> F.FieldNullable T.SqlText (.#>>) = C.binOp (HPQ.:#>>) -- | Does the left JSON value contain within it the right value? infix 4 .@> (.@>) :: F.Field T.SqlJsonb -> F.Field T.SqlJsonb -> F.Field T.SqlBool (.@>) = C.binOp (HPQ.:@>) -- | Is the left JSON value contained within the right value? infix 4 .<@ (.<@) :: F.Field T.SqlJsonb -> F.Field T.SqlJsonb -> F.Field T.SqlBool (.<@) = C.binOp (HPQ.:<@) -- | Does the key/element string exist within the JSON value? infix 4 .? (.?) :: F.Field T.SqlJsonb -> F.Field T.SqlText -> F.Field T.SqlBool (.?) = C.binOp (HPQ.:?) -- | Do any of these key/element strings exist? infix 4 .?| (.?|) :: F.Field T.SqlJsonb -> Field (T.SqlArray T.SqlText) -> F.Field T.SqlBool (.?|) = C.binOp (HPQ.:?|) -- | Do all of these key/element strings exist? infix 4 .?& (.?&) :: F.Field T.SqlJsonb -> Field (T.SqlArray T.SqlText) -> F.Field T.SqlBool (.?&) = C.binOp (HPQ.:?&) emptyArray :: T.IsSqlType a => Field (T.SqlArray_ n a) emptyArray = T.sqlArray id [] -- | Append two 'T.SqlArray's arrayAppend :: F.Field (T.SqlArray_ n a) -> F.Field (T.SqlArray_ n a) -> F.Field (T.SqlArray_ n a) arrayAppend = C.binOp (HPQ.:||) -- | Prepend an element to a 'T.SqlArray' arrayPrepend :: Field_ n a -> Field (T.SqlArray_ n a) -> Field (T.SqlArray_ n a) arrayPrepend (Column e) (Column es) = Column (HPQ.FunExpr "array_prepend" [e, es]) -- | Remove all instances of an element from a 'T.SqlArray' arrayRemove :: Field_ n a -> Field (T.SqlArray_ n a) -> Field (T.SqlArray_ n a) arrayRemove (Column e) (Column es) = Column (HPQ.FunExpr "array_remove" [es, e]) -- | Remove all 'NULL' values from a 'T.SqlArray' arrayRemoveNulls :: Field (T.SqlArray_ Nullable a) -> Field (T.SqlArray a) arrayRemoveNulls = Column.unsafeCoerceColumn . arrayRemove F.null singletonArray :: T.IsSqlType a => Field_ n a -> Field (T.SqlArray_ n a) singletonArray x = arrayPrepend x emptyArray index :: (C.SqlIntegral n) => Field (T.SqlArray_ n' a) -> Field n -> FieldNullable a index (Column a) (Column b) = Column (HPQ.ArrayIndex a b) -- | Postgres's @array_position@ arrayPosition :: F.Field (T.SqlArray_ n a) -- ^ Haystack -> F.Field_ n a -- ^ Needle -> F.FieldNullable T.SqlInt4 arrayPosition (Column fs) (Column f') = C.Column (HPQ.FunExpr "array_position" [fs , f']) -- | Whether the element (needle) exists in the array (haystack). N.B. this is implemented hackily using If you need it to be implemented using @= any@ then please open an issue . sqlElem :: F.Field_ n a -- ^ Needle -> F.Field (T.SqlArray_ n a) -- ^ Haystack -> F.Field T.SqlBool sqlElem f fs = (O.not . F.isNull . arrayPosition fs) f overlap :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool overlap = C.binOp (HPQ.:&&) liesWithin :: T.IsRangeType a => Field a -> Field (T.SqlRange a) -> F.Field T.SqlBool liesWithin = C.binOp (HPQ.:<@) -- | Access the upper bound of a range. For discrete range types it is the exclusive bound. upperBound :: T.IsRangeType a => Field (T.SqlRange a) -> FieldNullable a upperBound (Column range) = Column $ HPQ.FunExpr "upper" [range] -- | Access the lower bound of a range. For discrete range types it is the inclusive bound. lowerBound :: T.IsRangeType a => Field (T.SqlRange a) -> FieldNullable a lowerBound (Column range) = Column $ HPQ.FunExpr "lower" [range] infix 4 .<< (.<<) :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool (.<<) = C.binOp (HPQ.:<<) infix 4 .>> (.>>) :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool (.>>) = C.binOp (HPQ.:>>) infix 4 .&< (.&<) :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool (.&<) = C.binOp (HPQ.:&<) infix 4 .&> (.&>) :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool (.&>) = C.binOp (HPQ.:&>) infix 4 .-|- (.-|-) :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool (.-|-) = C.binOp (HPQ.:-|-) timestamptzAtTimeZone :: F.Field T.SqlTimestamptz -> F.Field T.SqlText -> F.Field T.SqlTimestamp timestamptzAtTimeZone = C.binOp HPQ.OpAtTimeZone dateOfTimestamp :: F.Field T.SqlTimestamp -> F.Field T.SqlDate dateOfTimestamp (Column e) = Column (HPQ.FunExpr "date" [e]) | @IntervalNum from to@ determines from which date or time types an interval -- can be added ('addInterval') or subtracted ('minusInterval`) and which is the -- resulting type. -- -- The instances should correspond to the interval + and - operations listed in: -- -- -datetime.html#OPERATORS-DATETIME-TABLE class IntervalNum from to | from -> to instance IntervalNum T.SqlDate T.SqlTimestamp instance IntervalNum T.SqlInterval T.SqlInterval instance IntervalNum T.SqlTimestamp T.SqlTimestamp instance IntervalNum T.SqlTimestamptz T.SqlTimestamptz instance IntervalNum T.SqlTime T.SqlTime addInterval :: IntervalNum from to => F.Field from -> F.Field T.SqlInterval -> F.Field to addInterval = C.binOp (HPQ.:+) minusInterval :: IntervalNum from to => F.Field from -> F.Field T.SqlInterval -> F.Field to minusInterval = C.binOp (HPQ.:-) # DEPRECATED keepWhen " Use ' where _ ' or ' restrict ' instead . Will be removed in version 0.10 . " # keepWhen :: (a -> F.Field T.SqlBool) -> S.SelectArr a a keepWhen p = proc a -> do restrict -< p a A.returnA -< a -- | Current date and time (start of current transaction) now :: F.Field T.SqlTimestamptz now = Column $ HPQ.FunExpr "now" []
null
https://raw.githubusercontent.com/tomjaguarpaw/haskell-opaleye/5c5e1dafe998d7ed713d1cc019bee87811093dea/src/Opaleye/Operators.hs
haskell
# LANGUAGE Arrows # # LANGUAGE ConstraintKinds # # LANGUAGE TypeSynonymInstances # * Restriction operators * Numerical operators operators (e.g.. '*', '/', '+', '-') on them and you can create * Equality operators * Comparison operators * Numerical operators * Conditional operators * Logical operators * Text operators * Containment operators * JSON operators * Range operators * Other operators * Deprecated | You would typically use 'restrict' if you want to write your query using 'A.Arrow' notation. If you want to use monadic style then 'where_' will suit you better. | Add a @WHERE EXISTS@ clause to the current query. A where exists clause can always refer to columns defined by the A where exists clause can always refer to columns defined by the | A polymorphic equality operator that works for all types that you have run `makeAdaptorAndInstance` on. This may be unified with | A polymorphic inequality operator that works for all types that you have run `makeAdaptorAndInstance` on. This may be unified with `./=` in a future version. "modulo (remainder)". This may be replaced by 'ifThenElseMany' in a future version. | Polymorphic if\/then\/else. | Boolean or | Boolean and | Boolean not | True when any element of the container is true | Concatenate 'F.Field' 'T.SqlText' | To lowercase | To uppercase | Postgres @LIKE@ operator | Postgres @ILIKE@ operator | 'in_' is designed to be used in prefix form. 'in_' @validProducts@ @product@ checks whether @product@ is a valid product. 'in_' @validProducts@ is a function which checks whether a product is a valid product. false otherwise. | Class of Postgres types that represent json values. Used to overload functions and operators that work on both 'T.SqlJson' and 'T.SqlJsonb'. Warning: making additional instances of this class can lead to broken code! | Class of Postgres types that can be used to index json values. Warning: making additional instances of this class can lead to broken code! | Use 'SqlJsonIndex' instead. Will be deprecated in a future version. | Get JSON object field by key. ^ ^ key or index | Get JSON object field as text. ^ ^ key or index | Get JSON object at specified path. ^ ^ path | Get JSON object at specified path as text. ^ ^ path | Does the left JSON value contain within it the right value? | Is the left JSON value contained within the right value? | Does the key/element string exist within the JSON value? | Do any of these key/element strings exist? | Do all of these key/element strings exist? | Append two 'T.SqlArray's | Prepend an element to a 'T.SqlArray' | Remove all instances of an element from a 'T.SqlArray' | Remove all 'NULL' values from a 'T.SqlArray' | Postgres's @array_position@ ^ Haystack ^ Needle | Whether the element (needle) exists in the array (haystack). ^ Needle ^ Haystack | Access the upper bound of a range. For discrete range types it is the exclusive bound. | Access the lower bound of a range. For discrete range types it is the inclusive bound. can be added ('addInterval') or subtracted ('minusInterval`) and which is the resulting type. The instances should correspond to the interval + and - operations listed in: -datetime.html#OPERATORS-DATETIME-TABLE | Current date and time (start of current transaction)
# LANGUAGE FlexibleContexts # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FunctionalDependencies # # LANGUAGE DataKinds # We can probably disable ConstraintKinds and TypeSynonymInstances when we move to ... instead of PG .. module Opaleye.Operators ( where_ , restrict , restrictExists , restrictNotExists | Numeric ' Column ' / ' F.Field ' types are instances of ' ' and ' Fractional ' , so you can use the standard Haskell numerical them with numerical literals such as @3.14 : : ' F.Field ' ' T.SqlFloat8'@. , (+) , (-) , (*) , (/) , fromInteger , abs , negate , signum , (.==) , (./=) , (.===) , (./==) , (.>) , (.<) , (.<=) , (.>=) , quot_ , rem_ , case_ , ifThenElse , ifThenElseMany , (.||) , (.&&) , not , ors , (.++) , lower , upper , like , ilike , sqlLength , in_ , inSelect , SqlIsJson , SqlJsonIndex , PGJsonIndex , (.->) , (.->>) , (.#>) , (.#>>) , (.@>) , (.<@) , (.?) , (.?|) , (.?&) , JBOF.jsonBuildObject , JBOF.jsonBuildObjectField , JBOF.JSONBuildObjectFields * SqlArray operators , emptyArray , arrayAppend , arrayPrepend , arrayRemove , arrayRemoveNulls , singletonArray , index , arrayPosition , sqlElem , overlap , liesWithin , upperBound , lowerBound , (.<<) , (.>>) , (.&<) , (.&>) , (.-|-) , timestamptzAtTimeZone , dateOfTimestamp , now , IntervalNum , addInterval , minusInterval , keepWhen ) where import qualified Control.Arrow as A import qualified Data.Foldable as F hiding (null) import qualified Data.List.NonEmpty as NEL import Prelude hiding (not) import qualified Opaleye.Exists as E import qualified Opaleye.Field as F import Opaleye.Internal.Column (Field_(Column), Field, FieldNullable, Nullability(Nullable), unsafeCase_, unsafeIfThenElse, unsafeGt) import qualified Opaleye.Internal.Column as C import qualified Opaleye.Internal.JSONBuildObjectFields as JBOF import Opaleye.Internal.QueryArr (SelectArr(QueryArr), runSimpleQueryArr') import qualified Opaleye.Internal.PrimQuery as PQ import qualified Opaleye.Internal.Operators as O import Opaleye.Internal.Helpers ((.:)) import qualified Opaleye.Lateral as L import qualified Opaleye.Order as Ord import qualified Opaleye.Select as S import qualified Opaleye.SqlTypes as T import qualified Opaleye.Column as Column import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ import qualified Data.Profunctor.Product.Default as D | Keep only the rows of a query satisfying a given condition , using an SQL @WHERE@ clause . It is equivalent to the Haskell function @ where _ : : Bool - > [ ( ) ] where _ True = [ ( ) ] where _ False = [ ] @ SQL @WHERE@ clause. It is equivalent to the Haskell function @ where_ :: Bool -> [()] where_ True = [()] where_ False = [] @ -} where_ :: F.Field T.SqlBool -> S.Select () where_ = L.viaLateral restrict restrict :: S.SelectArr (F.Field T.SqlBool) () restrict = O.restrict restrictExists :: S.SelectArr a b -> S.SelectArr a () restrictExists criteria = QueryArr f where query it references so needs no special treatment on LATERAL . f a = do (_, existsQ) <- runSimpleQueryArr' criteria a pure ((), PQ.aSemijoin PQ.Semi existsQ) | Add a @WHERE NOT clause to the current query . restrictNotExists :: S.SelectArr a b -> S.SelectArr a () restrictNotExists criteria = QueryArr f where query it references so needs no special treatment on LATERAL . f a = do (_, existsQ) <- runSimpleQueryArr' criteria a pure ((), PQ.aSemijoin PQ.Anti existsQ) infix 4 .== (.==) :: Field a -> Field a -> F.Field T.SqlBool (.==) = C.binOp (HPQ.:==) infix 4 ./= (./=) :: Field a -> Field a -> F.Field T.SqlBool (./=) = C.binOp (HPQ.:<>) infix 4 .=== ` .== ` in a future version . (.===) :: D.Default O.EqPP fields fields => fields -> fields -> F.Field T.SqlBool (.===) = (O..==) infix 4 ./== (./==) :: D.Default O.EqPP fields fields => fields -> fields -> F.Field T.SqlBool (./==) = Opaleye.Operators.not .: (O..==) infix 4 .> (.>) :: Ord.SqlOrd a => Field a -> Field a -> F.Field T.SqlBool (.>) = unsafeGt infix 4 .< (.<) :: Ord.SqlOrd a => Field a -> Field a -> F.Field T.SqlBool (.<) = C.binOp (HPQ.:<) infix 4 .<= (.<=) :: Ord.SqlOrd a => Field a -> Field a -> F.Field T.SqlBool (.<=) = C.binOp (HPQ.:<=) infix 4 .>= (.>=) :: Ord.SqlOrd a => Field a -> Field a -> F.Field T.SqlBool (.>=) = C.binOp (HPQ.:>=) | Integral division , named after ' Prelude.quot ' . It maps to the @/@ operator in Postgres . quot_ :: C.SqlIntegral a => Field a -> Field a -> Field a quot_ = C.binOp (HPQ.:/) | The remainder of integral division , named after ' ' . It maps to ' MOD ' ( ' % ' ) in Postgres , confusingly described as rem_ :: C.SqlIntegral a => Field a -> Field a -> Field a rem_ = C.binOp HPQ.OpMod | Select the first case for which the condition is true . case_ :: [(F.Field T.SqlBool, Field_ n a)] -> Field_ n a -> Field_ n a case_ = unsafeCase_ | if\/then\/else . ifThenElse :: F.Field T.SqlBool -> Field_ n a -> Field_ n a -> Field_ n a ifThenElse = unsafeIfThenElse ifThenElseMany :: D.Default O.IfPP fields fields => F.Field T.SqlBool -> fields -> fields -> fields ifThenElseMany = O.ifExplict D.def infixr 2 .|| (.||) :: F.Field T.SqlBool -> F.Field T.SqlBool -> F.Field T.SqlBool (.||) = (O..||) infixr 3 .&& (.&&) :: F.Field T.SqlBool -> F.Field T.SqlBool -> F.Field T.SqlBool (.&&) = (O..&&) not :: F.Field T.SqlBool -> F.Field T.SqlBool not = O.not ors :: F.Foldable f => f (F.Field T.SqlBool) -> F.Field T.SqlBool ors = F.foldl' (.||) (T.sqlBool False) (.++) :: F.Field T.SqlText -> F.Field T.SqlText -> F.Field T.SqlText (.++) = C.binOp (HPQ.:||) lower :: F.Field T.SqlText -> F.Field T.SqlText lower = C.unOp HPQ.OpLower upper :: F.Field T.SqlText -> F.Field T.SqlText upper = C.unOp HPQ.OpUpper like :: F.Field T.SqlText -> F.Field T.SqlText -> F.Field T.SqlBool like = C.binOp HPQ.OpLike ilike :: F.Field T.SqlText -> F.Field T.SqlText -> F.Field T.SqlBool ilike = C.binOp HPQ.OpILike sqlLength :: C.SqlString a => F.Field a -> F.Field T.SqlInt4 sqlLength (Column e) = Column (HPQ.FunExpr "length" [e]) in_ :: (Functor f, F.Foldable f) => f (Field a) -> Field a -> F.Field T.SqlBool in_ fcas (Column a) = case NEL.nonEmpty (F.toList fcas) of Nothing -> T.sqlBool False Just xs -> Column $ HPQ.BinExpr HPQ.OpIn a (HPQ.ListExpr (fmap C.unColumn xs)) | True if the first argument occurs amongst the rows of the second , This operation is equivalent to Postgres 's @IN@ operator . inSelect :: D.Default O.EqPP fields fields => fields -> S.Select fields -> S.Select (F.Field T.SqlBool) inSelect c q = E.exists (keepWhen (c .===) A.<<< q) class SqlIsJson json instance SqlIsJson T.SqlJson instance SqlIsJson T.SqlJsonb class SqlJsonIndex a type PGJsonIndex = SqlJsonIndex instance SqlJsonIndex T.SqlInt4 instance SqlJsonIndex T.SqlInt8 instance SqlJsonIndex T.SqlText infixl 8 .-> (.->) :: (SqlIsJson json, SqlJsonIndex k) -> F.FieldNullable json (.->) = C.binOp (HPQ.:->) infixl 8 .->> (.->>) :: (SqlIsJson json, SqlJsonIndex k) -> F.FieldNullable T.SqlText (.->>) = C.binOp (HPQ.:->>) infixl 8 .#> (.#>) :: (SqlIsJson json) -> F.FieldNullable json (.#>) = C.binOp (HPQ.:#>) infixl 8 .#>> (.#>>) :: (SqlIsJson json) -> F.FieldNullable T.SqlText (.#>>) = C.binOp (HPQ.:#>>) infix 4 .@> (.@>) :: F.Field T.SqlJsonb -> F.Field T.SqlJsonb -> F.Field T.SqlBool (.@>) = C.binOp (HPQ.:@>) infix 4 .<@ (.<@) :: F.Field T.SqlJsonb -> F.Field T.SqlJsonb -> F.Field T.SqlBool (.<@) = C.binOp (HPQ.:<@) infix 4 .? (.?) :: F.Field T.SqlJsonb -> F.Field T.SqlText -> F.Field T.SqlBool (.?) = C.binOp (HPQ.:?) infix 4 .?| (.?|) :: F.Field T.SqlJsonb -> Field (T.SqlArray T.SqlText) -> F.Field T.SqlBool (.?|) = C.binOp (HPQ.:?|) infix 4 .?& (.?&) :: F.Field T.SqlJsonb -> Field (T.SqlArray T.SqlText) -> F.Field T.SqlBool (.?&) = C.binOp (HPQ.:?&) emptyArray :: T.IsSqlType a => Field (T.SqlArray_ n a) emptyArray = T.sqlArray id [] arrayAppend :: F.Field (T.SqlArray_ n a) -> F.Field (T.SqlArray_ n a) -> F.Field (T.SqlArray_ n a) arrayAppend = C.binOp (HPQ.:||) arrayPrepend :: Field_ n a -> Field (T.SqlArray_ n a) -> Field (T.SqlArray_ n a) arrayPrepend (Column e) (Column es) = Column (HPQ.FunExpr "array_prepend" [e, es]) arrayRemove :: Field_ n a -> Field (T.SqlArray_ n a) -> Field (T.SqlArray_ n a) arrayRemove (Column e) (Column es) = Column (HPQ.FunExpr "array_remove" [es, e]) arrayRemoveNulls :: Field (T.SqlArray_ Nullable a) -> Field (T.SqlArray a) arrayRemoveNulls = Column.unsafeCoerceColumn . arrayRemove F.null singletonArray :: T.IsSqlType a => Field_ n a -> Field (T.SqlArray_ n a) singletonArray x = arrayPrepend x emptyArray index :: (C.SqlIntegral n) => Field (T.SqlArray_ n' a) -> Field n -> FieldNullable a index (Column a) (Column b) = Column (HPQ.ArrayIndex a b) -> F.FieldNullable T.SqlInt4 arrayPosition (Column fs) (Column f') = C.Column (HPQ.FunExpr "array_position" [fs , f']) N.B. this is implemented hackily using If you need it to be implemented using @= any@ then please open an issue . -> F.Field T.SqlBool sqlElem f fs = (O.not . F.isNull . arrayPosition fs) f overlap :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool overlap = C.binOp (HPQ.:&&) liesWithin :: T.IsRangeType a => Field a -> Field (T.SqlRange a) -> F.Field T.SqlBool liesWithin = C.binOp (HPQ.:<@) upperBound :: T.IsRangeType a => Field (T.SqlRange a) -> FieldNullable a upperBound (Column range) = Column $ HPQ.FunExpr "upper" [range] lowerBound :: T.IsRangeType a => Field (T.SqlRange a) -> FieldNullable a lowerBound (Column range) = Column $ HPQ.FunExpr "lower" [range] infix 4 .<< (.<<) :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool (.<<) = C.binOp (HPQ.:<<) infix 4 .>> (.>>) :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool (.>>) = C.binOp (HPQ.:>>) infix 4 .&< (.&<) :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool (.&<) = C.binOp (HPQ.:&<) infix 4 .&> (.&>) :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool (.&>) = C.binOp (HPQ.:&>) infix 4 .-|- (.-|-) :: Field (T.SqlRange a) -> Field (T.SqlRange a) -> F.Field T.SqlBool (.-|-) = C.binOp (HPQ.:-|-) timestamptzAtTimeZone :: F.Field T.SqlTimestamptz -> F.Field T.SqlText -> F.Field T.SqlTimestamp timestamptzAtTimeZone = C.binOp HPQ.OpAtTimeZone dateOfTimestamp :: F.Field T.SqlTimestamp -> F.Field T.SqlDate dateOfTimestamp (Column e) = Column (HPQ.FunExpr "date" [e]) | @IntervalNum from to@ determines from which date or time types an interval class IntervalNum from to | from -> to instance IntervalNum T.SqlDate T.SqlTimestamp instance IntervalNum T.SqlInterval T.SqlInterval instance IntervalNum T.SqlTimestamp T.SqlTimestamp instance IntervalNum T.SqlTimestamptz T.SqlTimestamptz instance IntervalNum T.SqlTime T.SqlTime addInterval :: IntervalNum from to => F.Field from -> F.Field T.SqlInterval -> F.Field to addInterval = C.binOp (HPQ.:+) minusInterval :: IntervalNum from to => F.Field from -> F.Field T.SqlInterval -> F.Field to minusInterval = C.binOp (HPQ.:-) # DEPRECATED keepWhen " Use ' where _ ' or ' restrict ' instead . Will be removed in version 0.10 . " # keepWhen :: (a -> F.Field T.SqlBool) -> S.SelectArr a a keepWhen p = proc a -> do restrict -< p a A.returnA -< a now :: F.Field T.SqlTimestamptz now = Column $ HPQ.FunExpr "now" []
d446425e0b8f29120007e8d271cc2df1e153b2bafade829af1975ab17914309e
janestreet/core
core_bin_prot.mli
open! Import include module type of Bin_prot module Writer : sig type 'a t = 'a Bin_prot.Type_class.writer = { size : 'a Size.sizer ; write : 'a Write.writer } val to_string : 'a t -> 'a -> string val to_bytes : 'a t -> 'a -> bytes end module Reader : sig type 'a t = 'a Bin_prot.Type_class.reader = { read : 'a Read.reader ; vtag_read : (int -> 'a) Read.reader } val of_string : 'a t -> string -> 'a val of_bytes : 'a t -> bytes -> 'a end
null
https://raw.githubusercontent.com/janestreet/core/b0be1daa71b662bd38ef2bb406f7b3e70d63d05f/core/src/core_bin_prot.mli
ocaml
open! Import include module type of Bin_prot module Writer : sig type 'a t = 'a Bin_prot.Type_class.writer = { size : 'a Size.sizer ; write : 'a Write.writer } val to_string : 'a t -> 'a -> string val to_bytes : 'a t -> 'a -> bytes end module Reader : sig type 'a t = 'a Bin_prot.Type_class.reader = { read : 'a Read.reader ; vtag_read : (int -> 'a) Read.reader } val of_string : 'a t -> string -> 'a val of_bytes : 'a t -> bytes -> 'a end
179eb9df39ccb67c477ce56a8f168bc900f746154034104929184fdec99fd2eb
aws-beam/aws-erlang
aws_connectcampaigns.erl
%% WARNING: DO NOT EDIT, AUTO-GENERATED CODE! See -beam/aws-codegen for more details . @doc Provide APIs to create and manage Amazon Connect Campaigns . -module(aws_connectcampaigns). -export([create_campaign/2, create_campaign/3, delete_campaign/3, delete_campaign/4, delete_connect_instance_config/3, delete_connect_instance_config/4, delete_instance_onboarding_job/3, delete_instance_onboarding_job/4, describe_campaign/2, describe_campaign/4, describe_campaign/5, get_campaign_state/2, get_campaign_state/4, get_campaign_state/5, get_campaign_state_batch/2, get_campaign_state_batch/3, get_connect_instance_config/2, get_connect_instance_config/4, get_connect_instance_config/5, get_instance_onboarding_job_status/2, get_instance_onboarding_job_status/4, get_instance_onboarding_job_status/5, list_campaigns/2, list_campaigns/3, list_tags_for_resource/2, list_tags_for_resource/4, list_tags_for_resource/5, pause_campaign/3, pause_campaign/4, put_dial_request_batch/3, put_dial_request_batch/4, resume_campaign/3, resume_campaign/4, start_campaign/3, start_campaign/4, start_instance_onboarding_job/3, start_instance_onboarding_job/4, stop_campaign/3, stop_campaign/4, tag_resource/3, tag_resource/4, untag_resource/3, untag_resource/4, update_campaign_dialer_config/3, update_campaign_dialer_config/4, update_campaign_name/3, update_campaign_name/4, update_campaign_outbound_call_config/3, update_campaign_outbound_call_config/4]). -include_lib("hackney/include/hackney_lib.hrl"). %%==================================================================== %% API %%==================================================================== @doc Creates a campaign for the specified Amazon Connect account . %% %% This API is idempotent. create_campaign(Client, Input) -> create_campaign(Client, Input, []). create_campaign(Client, Input0, Options0) -> Method = put, Path = ["/campaigns"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Deletes a campaign from the specified Amazon Connect account . delete_campaign(Client, Id, Input) -> delete_campaign(Client, Id, Input, []). delete_campaign(Client, Id, Input0, Options0) -> Method = delete, Path = ["/campaigns/", aws_util:encode_uri(Id), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Deletes a connect instance config from the specified AWS account. delete_connect_instance_config(Client, ConnectInstanceId, Input) -> delete_connect_instance_config(Client, ConnectInstanceId, Input, []). delete_connect_instance_config(Client, ConnectInstanceId, Input0, Options0) -> Method = delete, Path = ["/connect-instance/", aws_util:encode_uri(ConnectInstanceId), "/config"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Delete the Connect Campaigns onboarding job for the specified Amazon Connect instance . delete_instance_onboarding_job(Client, ConnectInstanceId, Input) -> delete_instance_onboarding_job(Client, ConnectInstanceId, Input, []). delete_instance_onboarding_job(Client, ConnectInstanceId, Input0, Options0) -> Method = delete, Path = ["/connect-instance/", aws_util:encode_uri(ConnectInstanceId), "/onboarding"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Describes the specific campaign. describe_campaign(Client, Id) when is_map(Client) -> describe_campaign(Client, Id, #{}, #{}). describe_campaign(Client, Id, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_campaign(Client, Id, QueryMap, HeadersMap, []). describe_campaign(Client, Id, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/campaigns/", aws_util:encode_uri(Id), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Get state of a campaign for the specified Amazon Connect account . get_campaign_state(Client, Id) when is_map(Client) -> get_campaign_state(Client, Id, #{}, #{}). get_campaign_state(Client, Id, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_campaign_state(Client, Id, QueryMap, HeadersMap, []). get_campaign_state(Client, Id, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/campaigns/", aws_util:encode_uri(Id), "/state"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Get state of campaigns for the specified Amazon Connect account . get_campaign_state_batch(Client, Input) -> get_campaign_state_batch(Client, Input, []). get_campaign_state_batch(Client, Input0, Options0) -> Method = post, Path = ["/campaigns-state"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Get the specific Connect instance config . get_connect_instance_config(Client, ConnectInstanceId) when is_map(Client) -> get_connect_instance_config(Client, ConnectInstanceId, #{}, #{}). get_connect_instance_config(Client, ConnectInstanceId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_connect_instance_config(Client, ConnectInstanceId, QueryMap, HeadersMap, []). get_connect_instance_config(Client, ConnectInstanceId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/connect-instance/", aws_util:encode_uri(ConnectInstanceId), "/config"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Get the specific instance onboarding job status. get_instance_onboarding_job_status(Client, ConnectInstanceId) when is_map(Client) -> get_instance_onboarding_job_status(Client, ConnectInstanceId, #{}, #{}). get_instance_onboarding_job_status(Client, ConnectInstanceId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_instance_onboarding_job_status(Client, ConnectInstanceId, QueryMap, HeadersMap, []). get_instance_onboarding_job_status(Client, ConnectInstanceId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/connect-instance/", aws_util:encode_uri(ConnectInstanceId), "/onboarding"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Provides summary information about the campaigns under the specified Amazon Connect account . list_campaigns(Client, Input) -> list_campaigns(Client, Input, []). list_campaigns(Client, Input0, Options0) -> Method = post, Path = ["/campaigns-summary"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc List tags for a resource. list_tags_for_resource(Client, Arn) when is_map(Client) -> list_tags_for_resource(Client, Arn, #{}, #{}). list_tags_for_resource(Client, Arn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_tags_for_resource(Client, Arn, QueryMap, HeadersMap, []). list_tags_for_resource(Client, Arn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/tags/", aws_util:encode_uri(Arn), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Pauses a campaign for the specified Amazon Connect account . pause_campaign(Client, Id, Input) -> pause_campaign(Client, Id, Input, []). pause_campaign(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/pause"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Creates dials requests for the specified campaign Amazon Connect %% account. %% %% This API is idempotent. put_dial_request_batch(Client, Id, Input) -> put_dial_request_batch(Client, Id, Input, []). put_dial_request_batch(Client, Id, Input0, Options0) -> Method = put, Path = ["/campaigns/", aws_util:encode_uri(Id), "/dial-requests"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Stops a campaign for the specified Amazon Connect account . resume_campaign(Client, Id, Input) -> resume_campaign(Client, Id, Input, []). resume_campaign(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/resume"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Starts a campaign for the specified Amazon Connect account . start_campaign(Client, Id, Input) -> start_campaign(Client, Id, Input, []). start_campaign(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/start"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Onboard the specific Amazon Connect instance to Connect Campaigns . start_instance_onboarding_job(Client, ConnectInstanceId, Input) -> start_instance_onboarding_job(Client, ConnectInstanceId, Input, []). start_instance_onboarding_job(Client, ConnectInstanceId, Input0, Options0) -> Method = put, Path = ["/connect-instance/", aws_util:encode_uri(ConnectInstanceId), "/onboarding"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Stops a campaign for the specified Amazon Connect account . stop_campaign(Client, Id, Input) -> stop_campaign(Client, Id, Input, []). stop_campaign(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/stop"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Tag a resource. tag_resource(Client, Arn, Input) -> tag_resource(Client, Arn, Input, []). tag_resource(Client, Arn, Input0, Options0) -> Method = post, Path = ["/tags/", aws_util:encode_uri(Arn), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Untag a resource . untag_resource(Client, Arn, Input) -> untag_resource(Client, Arn, Input, []). untag_resource(Client, Arn, Input0, Options0) -> Method = delete, Path = ["/tags/", aws_util:encode_uri(Arn), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"tagKeys">>, <<"tagKeys">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Updates the dialer config of a campaign. %% %% This API is idempotent. update_campaign_dialer_config(Client, Id, Input) -> update_campaign_dialer_config(Client, Id, Input, []). update_campaign_dialer_config(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/dialer-config"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Updates the name of a campaign. %% %% This API is idempotent. update_campaign_name(Client, Id, Input) -> update_campaign_name(Client, Id, Input, []). update_campaign_name(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/name"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Updates the outbound call config of a campaign. %% %% This API is idempotent. update_campaign_outbound_call_config(Client, Id, Input) -> update_campaign_outbound_call_config(Client, Id, Input, []). update_campaign_outbound_call_config(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/outbound-call-config"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %%==================================================================== Internal functions %%==================================================================== -spec request(aws_client:aws_client(), atom(), iolist(), list(), list(), map() | undefined, list(), pos_integer() | undefined) -> {ok, {integer(), list()}} | {ok, Result, {integer(), list(), hackney:client()}} | {error, Error, {integer(), list(), hackney:client()}} | {error, term()} when Result :: map(), Error :: map(). request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end, aws_request:request(RequestFun, Options). do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> Client1 = Client#{service => <<"connect-campaigns">>}, Host = build_host(<<"connect-campaigns">>, Client1), URL0 = build_url(Host, Path, Client1), URL = aws_request:add_query(URL0, Query), AdditionalHeaders1 = [ {<<"Host">>, Host} , {<<"Content-Type">>, <<"application/x-amz-json-1.1">>} ], Payload = case proplists:get_value(send_body_as_binary, Options) of true -> maps:get(<<"Body">>, Input, <<"">>); false -> encode_payload(Input) end, AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of true -> add_checksum_hash_header(AdditionalHeaders1, Payload); false -> AdditionalHeaders1 end, Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0), MethodBin = aws_request:method_to_binary(Method), SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload), Response = hackney:request(Method, URL, SignedHeaders, Payload, Options), DecodeBody = not proplists:get_value(receive_body_as_binary, Options), handle_response(Response, SuccessStatusCode, DecodeBody). add_checksum_hash_header(Headers, Body) -> [ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))} | Headers ]. handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> {ok, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) -> {error, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> case hackney:body(Client) of {ok, <<>>} when StatusCode =:= 200; StatusCode =:= SuccessStatusCode -> {ok, #{}, {StatusCode, ResponseHeaders, Client}}; {ok, Body} -> Result = case DecodeBody of true -> try jsx:decode(Body) catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; false -> #{<<"Body">> => Body} end, {ok, Result, {StatusCode, ResponseHeaders, Client}} end; handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody) when StatusCode =:= 503 -> Retriable error if retries are enabled {error, service_unavailable}; handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) -> {ok, Body} = hackney:body(Client), try DecodedError = jsx:decode(Body), {error, DecodedError, {StatusCode, ResponseHeaders, Client}} catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; handle_response({error, Reason}, _, _DecodeBody) -> {error, Reason}. build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) -> Endpoint; build_host(_EndpointPrefix, #{region := <<"local">>}) -> <<"localhost">>; build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) -> aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>). build_url(Host, Path0, Client) -> Proto = aws_client:proto(Client), Path = erlang:iolist_to_binary(Path0), Port = aws_client:port(Client), aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>). -spec encode_payload(undefined | map()) -> binary(). encode_payload(undefined) -> <<>>; encode_payload(Input) -> jsx:encode(Input).
null
https://raw.githubusercontent.com/aws-beam/aws-erlang/699287cee7dfc9dc8c08ced5f090dcc192c9cba8/src/aws_connectcampaigns.erl
erlang
WARNING: DO NOT EDIT, AUTO-GENERATED CODE! ==================================================================== API ==================================================================== This API is idempotent. @doc Deletes a connect instance config from the specified AWS account. @doc Describes the specific campaign. @doc Get the specific instance onboarding job status. @doc Provides summary information about the campaigns under the specified @doc List tags for a resource. account. This API is idempotent. @doc Tag a resource. @doc Updates the dialer config of a campaign. This API is idempotent. @doc Updates the name of a campaign. This API is idempotent. @doc Updates the outbound call config of a campaign. This API is idempotent. ==================================================================== ====================================================================
See -beam/aws-codegen for more details . @doc Provide APIs to create and manage Amazon Connect Campaigns . -module(aws_connectcampaigns). -export([create_campaign/2, create_campaign/3, delete_campaign/3, delete_campaign/4, delete_connect_instance_config/3, delete_connect_instance_config/4, delete_instance_onboarding_job/3, delete_instance_onboarding_job/4, describe_campaign/2, describe_campaign/4, describe_campaign/5, get_campaign_state/2, get_campaign_state/4, get_campaign_state/5, get_campaign_state_batch/2, get_campaign_state_batch/3, get_connect_instance_config/2, get_connect_instance_config/4, get_connect_instance_config/5, get_instance_onboarding_job_status/2, get_instance_onboarding_job_status/4, get_instance_onboarding_job_status/5, list_campaigns/2, list_campaigns/3, list_tags_for_resource/2, list_tags_for_resource/4, list_tags_for_resource/5, pause_campaign/3, pause_campaign/4, put_dial_request_batch/3, put_dial_request_batch/4, resume_campaign/3, resume_campaign/4, start_campaign/3, start_campaign/4, start_instance_onboarding_job/3, start_instance_onboarding_job/4, stop_campaign/3, stop_campaign/4, tag_resource/3, tag_resource/4, untag_resource/3, untag_resource/4, update_campaign_dialer_config/3, update_campaign_dialer_config/4, update_campaign_name/3, update_campaign_name/4, update_campaign_outbound_call_config/3, update_campaign_outbound_call_config/4]). -include_lib("hackney/include/hackney_lib.hrl"). @doc Creates a campaign for the specified Amazon Connect account . create_campaign(Client, Input) -> create_campaign(Client, Input, []). create_campaign(Client, Input0, Options0) -> Method = put, Path = ["/campaigns"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Deletes a campaign from the specified Amazon Connect account . delete_campaign(Client, Id, Input) -> delete_campaign(Client, Id, Input, []). delete_campaign(Client, Id, Input0, Options0) -> Method = delete, Path = ["/campaigns/", aws_util:encode_uri(Id), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). delete_connect_instance_config(Client, ConnectInstanceId, Input) -> delete_connect_instance_config(Client, ConnectInstanceId, Input, []). delete_connect_instance_config(Client, ConnectInstanceId, Input0, Options0) -> Method = delete, Path = ["/connect-instance/", aws_util:encode_uri(ConnectInstanceId), "/config"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Delete the Connect Campaigns onboarding job for the specified Amazon Connect instance . delete_instance_onboarding_job(Client, ConnectInstanceId, Input) -> delete_instance_onboarding_job(Client, ConnectInstanceId, Input, []). delete_instance_onboarding_job(Client, ConnectInstanceId, Input0, Options0) -> Method = delete, Path = ["/connect-instance/", aws_util:encode_uri(ConnectInstanceId), "/onboarding"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). describe_campaign(Client, Id) when is_map(Client) -> describe_campaign(Client, Id, #{}, #{}). describe_campaign(Client, Id, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_campaign(Client, Id, QueryMap, HeadersMap, []). describe_campaign(Client, Id, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/campaigns/", aws_util:encode_uri(Id), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Get state of a campaign for the specified Amazon Connect account . get_campaign_state(Client, Id) when is_map(Client) -> get_campaign_state(Client, Id, #{}, #{}). get_campaign_state(Client, Id, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_campaign_state(Client, Id, QueryMap, HeadersMap, []). get_campaign_state(Client, Id, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/campaigns/", aws_util:encode_uri(Id), "/state"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Get state of campaigns for the specified Amazon Connect account . get_campaign_state_batch(Client, Input) -> get_campaign_state_batch(Client, Input, []). get_campaign_state_batch(Client, Input0, Options0) -> Method = post, Path = ["/campaigns-state"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Get the specific Connect instance config . get_connect_instance_config(Client, ConnectInstanceId) when is_map(Client) -> get_connect_instance_config(Client, ConnectInstanceId, #{}, #{}). get_connect_instance_config(Client, ConnectInstanceId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_connect_instance_config(Client, ConnectInstanceId, QueryMap, HeadersMap, []). get_connect_instance_config(Client, ConnectInstanceId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/connect-instance/", aws_util:encode_uri(ConnectInstanceId), "/config"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). get_instance_onboarding_job_status(Client, ConnectInstanceId) when is_map(Client) -> get_instance_onboarding_job_status(Client, ConnectInstanceId, #{}, #{}). get_instance_onboarding_job_status(Client, ConnectInstanceId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> get_instance_onboarding_job_status(Client, ConnectInstanceId, QueryMap, HeadersMap, []). get_instance_onboarding_job_status(Client, ConnectInstanceId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/connect-instance/", aws_util:encode_uri(ConnectInstanceId), "/onboarding"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). Amazon Connect account . list_campaigns(Client, Input) -> list_campaigns(Client, Input, []). list_campaigns(Client, Input0, Options0) -> Method = post, Path = ["/campaigns-summary"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). list_tags_for_resource(Client, Arn) when is_map(Client) -> list_tags_for_resource(Client, Arn, #{}, #{}). list_tags_for_resource(Client, Arn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_tags_for_resource(Client, Arn, QueryMap, HeadersMap, []). list_tags_for_resource(Client, Arn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/tags/", aws_util:encode_uri(Arn), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Pauses a campaign for the specified Amazon Connect account . pause_campaign(Client, Id, Input) -> pause_campaign(Client, Id, Input, []). pause_campaign(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/pause"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Creates dials requests for the specified campaign Amazon Connect put_dial_request_batch(Client, Id, Input) -> put_dial_request_batch(Client, Id, Input, []). put_dial_request_batch(Client, Id, Input0, Options0) -> Method = put, Path = ["/campaigns/", aws_util:encode_uri(Id), "/dial-requests"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Stops a campaign for the specified Amazon Connect account . resume_campaign(Client, Id, Input) -> resume_campaign(Client, Id, Input, []). resume_campaign(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/resume"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Starts a campaign for the specified Amazon Connect account . start_campaign(Client, Id, Input) -> start_campaign(Client, Id, Input, []). start_campaign(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/start"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Onboard the specific Amazon Connect instance to Connect Campaigns . start_instance_onboarding_job(Client, ConnectInstanceId, Input) -> start_instance_onboarding_job(Client, ConnectInstanceId, Input, []). start_instance_onboarding_job(Client, ConnectInstanceId, Input0, Options0) -> Method = put, Path = ["/connect-instance/", aws_util:encode_uri(ConnectInstanceId), "/onboarding"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Stops a campaign for the specified Amazon Connect account . stop_campaign(Client, Id, Input) -> stop_campaign(Client, Id, Input, []). stop_campaign(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/stop"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). tag_resource(Client, Arn, Input) -> tag_resource(Client, Arn, Input, []). tag_resource(Client, Arn, Input0, Options0) -> Method = post, Path = ["/tags/", aws_util:encode_uri(Arn), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Untag a resource . untag_resource(Client, Arn, Input) -> untag_resource(Client, Arn, Input, []). untag_resource(Client, Arn, Input0, Options0) -> Method = delete, Path = ["/tags/", aws_util:encode_uri(Arn), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"tagKeys">>, <<"tagKeys">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). update_campaign_dialer_config(Client, Id, Input) -> update_campaign_dialer_config(Client, Id, Input, []). update_campaign_dialer_config(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/dialer-config"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). update_campaign_name(Client, Id, Input) -> update_campaign_name(Client, Id, Input, []). update_campaign_name(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/name"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). update_campaign_outbound_call_config(Client, Id, Input) -> update_campaign_outbound_call_config(Client, Id, Input, []). update_campaign_outbound_call_config(Client, Id, Input0, Options0) -> Method = post, Path = ["/campaigns/", aws_util:encode_uri(Id), "/outbound-call-config"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Internal functions -spec request(aws_client:aws_client(), atom(), iolist(), list(), list(), map() | undefined, list(), pos_integer() | undefined) -> {ok, {integer(), list()}} | {ok, Result, {integer(), list(), hackney:client()}} | {error, Error, {integer(), list(), hackney:client()}} | {error, term()} when Result :: map(), Error :: map(). request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end, aws_request:request(RequestFun, Options). do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> Client1 = Client#{service => <<"connect-campaigns">>}, Host = build_host(<<"connect-campaigns">>, Client1), URL0 = build_url(Host, Path, Client1), URL = aws_request:add_query(URL0, Query), AdditionalHeaders1 = [ {<<"Host">>, Host} , {<<"Content-Type">>, <<"application/x-amz-json-1.1">>} ], Payload = case proplists:get_value(send_body_as_binary, Options) of true -> maps:get(<<"Body">>, Input, <<"">>); false -> encode_payload(Input) end, AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of true -> add_checksum_hash_header(AdditionalHeaders1, Payload); false -> AdditionalHeaders1 end, Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0), MethodBin = aws_request:method_to_binary(Method), SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload), Response = hackney:request(Method, URL, SignedHeaders, Payload, Options), DecodeBody = not proplists:get_value(receive_body_as_binary, Options), handle_response(Response, SuccessStatusCode, DecodeBody). add_checksum_hash_header(Headers, Body) -> [ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))} | Headers ]. handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> {ok, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) -> {error, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> case hackney:body(Client) of {ok, <<>>} when StatusCode =:= 200; StatusCode =:= SuccessStatusCode -> {ok, #{}, {StatusCode, ResponseHeaders, Client}}; {ok, Body} -> Result = case DecodeBody of true -> try jsx:decode(Body) catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; false -> #{<<"Body">> => Body} end, {ok, Result, {StatusCode, ResponseHeaders, Client}} end; handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody) when StatusCode =:= 503 -> Retriable error if retries are enabled {error, service_unavailable}; handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) -> {ok, Body} = hackney:body(Client), try DecodedError = jsx:decode(Body), {error, DecodedError, {StatusCode, ResponseHeaders, Client}} catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; handle_response({error, Reason}, _, _DecodeBody) -> {error, Reason}. build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) -> Endpoint; build_host(_EndpointPrefix, #{region := <<"local">>}) -> <<"localhost">>; build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) -> aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>). build_url(Host, Path0, Client) -> Proto = aws_client:proto(Client), Path = erlang:iolist_to_binary(Path0), Port = aws_client:port(Client), aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>). -spec encode_payload(undefined | map()) -> binary(). encode_payload(undefined) -> <<>>; encode_payload(Input) -> jsx:encode(Input).
ff286d9e594718fce92fb4a459de7f604df69dcbc823e56fad5013fb39da40b9
ghc/packages-Cabal
cabal.test.hs
import Test.Cabal.Prelude main = cabalTest $ do cabal "v2-build" ["p"]
null
https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/InternalLibraries/cabal.test.hs
haskell
import Test.Cabal.Prelude main = cabalTest $ do cabal "v2-build" ["p"]
6a949f16a23bd75529d7de5a59ed7c7cc6eed37245c198fda2e3257e99cee68b
pflanze/chj-schemelib
memcmp-test.scm
Copyright 2018 by < > ;;; This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License ( GPL ) as published by the Free Software Foundation , either version 2 of the License , or ;;; (at your option) any later version. (require easy memcmp test) (TEST > (memcmp:substring=? "foo" 0 "bar" 0 0) #t > (memcmp:substring=? "foo" 0 "bar" 0 1) #f > (memcmp:substring=? "foo" 0 "far" 0 1) #t > (memcmp:substring=? "foo" 0 "far" 0 2) #f > (memcmp:substring=? "foo" 1 "oof" 0 2) #t > (memcmp:substring=? "foo" 1 "oof" 0 1) #t > (memcmp:substring=? "foo" 2 "oof" 0 1) #t > (memcmp:substring=? "foo" 2 "oof" 1 1) #t > (memcmp:substring=? "foo" 2 "oof" 2 1) #f > (memcmp:substring=? "foof" 3 "oof" 2 1) #t > (memcmp:substring=? "foof" 3 "oof" 2 2) since len 2 goes past the strings so the requested region is n't ;; covered; XX should it return an error value instead? False but ;; error, ever ? #f > (memcmp:substring=? "foofa" 1 "oof" 0 3) #t > (memcmp:substring=? "foofa" 1 "oof" 0 4) #f > (memcmp:substring=? "foofa" 2 "oofx" 1 2) #t > (memcmp:substring=? "foofa" 2 "oofx" 1 3) #f) (TEST > (%try (memcmp:substring=? "foofa" 2 "oofx" 1 "")) (exception text: "memcmp:substring=?: need string, natural0 (start), string, natural0 (start), natural0 (len): \"foofa\" 2 \"oofx\" 1 \"\"\n") > (%try (memcmp:substring=? "foofa" 2 "oofx" 1 -1)) (exception text: "memcmp:substring=?: need string, natural0 (start), string, natural0 (start), natural0 (len): \"foofa\" 2 \"oofx\" 1 -1\n") > (%try (memcmp:substring=? "foofa" 2 "oofx" 1. 1)) (exception text: "memcmp:substring=?: need string, natural0 (start), string, natural0 (start), natural0 (len): \"foofa\" 2 \"oofx\" 1. 1\n"))
null
https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/memcmp-test.scm
scheme
This file is free software; you can redistribute it and/or modify (at your option) any later version. covered; XX should it return an error value instead? False but error, ever ?
Copyright 2018 by < > it under the terms of the GNU General Public License ( GPL ) as published by the Free Software Foundation , either version 2 of the License , or (require easy memcmp test) (TEST > (memcmp:substring=? "foo" 0 "bar" 0 0) #t > (memcmp:substring=? "foo" 0 "bar" 0 1) #f > (memcmp:substring=? "foo" 0 "far" 0 1) #t > (memcmp:substring=? "foo" 0 "far" 0 2) #f > (memcmp:substring=? "foo" 1 "oof" 0 2) #t > (memcmp:substring=? "foo" 1 "oof" 0 1) #t > (memcmp:substring=? "foo" 2 "oof" 0 1) #t > (memcmp:substring=? "foo" 2 "oof" 1 1) #t > (memcmp:substring=? "foo" 2 "oof" 2 1) #f > (memcmp:substring=? "foof" 3 "oof" 2 1) #t > (memcmp:substring=? "foof" 3 "oof" 2 2) since len 2 goes past the strings so the requested region is n't #f > (memcmp:substring=? "foofa" 1 "oof" 0 3) #t > (memcmp:substring=? "foofa" 1 "oof" 0 4) #f > (memcmp:substring=? "foofa" 2 "oofx" 1 2) #t > (memcmp:substring=? "foofa" 2 "oofx" 1 3) #f) (TEST > (%try (memcmp:substring=? "foofa" 2 "oofx" 1 "")) (exception text: "memcmp:substring=?: need string, natural0 (start), string, natural0 (start), natural0 (len): \"foofa\" 2 \"oofx\" 1 \"\"\n") > (%try (memcmp:substring=? "foofa" 2 "oofx" 1 -1)) (exception text: "memcmp:substring=?: need string, natural0 (start), string, natural0 (start), natural0 (len): \"foofa\" 2 \"oofx\" 1 -1\n") > (%try (memcmp:substring=? "foofa" 2 "oofx" 1. 1)) (exception text: "memcmp:substring=?: need string, natural0 (start), string, natural0 (start), natural0 (len): \"foofa\" 2 \"oofx\" 1. 1\n"))
482aa288b7f7142c346fe4bf63183dc34e46f15292c39cee3986cb70ca897488
melange-re/melange
js_record_map.ml
open J let [@inline] unknown _ x = x let [@inline] option sub self = fun v -> match v with | None -> None | Some v -> Some (sub self v) let rec list sub self = fun x -> match x with | [] -> [] | x::xs -> let v = sub self x in v :: list sub self xs type iter = { ident : ident fn; module_id : module_id fn; vident : vident fn; exception_ident : exception_ident fn; for_ident : for_ident fn; expression : expression fn; statement : statement fn; variable_declaration : variable_declaration fn; block : block fn; program : program fn } and 'a fn = iter -> 'a -> 'a let label : label fn = unknown let ident : ident fn = unknown let module_id : module_id fn = fun _self { id = _x0;kind = _x1} -> begin let _x0 = _self.ident _self _x0 in {id = _x0;kind = _x1} end let required_modules : required_modules fn = fun _self arg -> list _self.module_id _self arg let vident : vident fn = fun _self -> function | Id ( _x0) -> begin let _x0 = _self.ident _self _x0 in Id ( _x0) end |Qualified ( _x0,_x1) -> begin let _x0 = _self.module_id _self _x0 in Qualified ( _x0,_x1) end let exception_ident : exception_ident fn = (fun _self arg -> _self.ident _self arg) let for_ident : for_ident fn = (fun _self arg -> _self.ident _self arg) let for_direction : for_direction fn = unknown let property_map : property_map fn = fun _self arg -> list ((fun _self (_x0,_x1) -> begin let _x1 = _self.expression _self _x1 in (_x0,_x1) end)) _self arg let length_object : length_object fn = unknown let expression_desc : expression_desc fn = fun _self -> function | Length ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = length_object _self _x1 in Length ( _x0,_x1) end |Char_of_int ( _x0) -> begin let _x0 = _self.expression _self _x0 in Char_of_int ( _x0) end |Char_to_int ( _x0) -> begin let _x0 = _self.expression _self _x0 in Char_to_int ( _x0) end |Is_null_or_undefined ( _x0) -> begin let _x0 = _self.expression _self _x0 in Is_null_or_undefined ( _x0) end |String_append ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in String_append ( _x0,_x1) end |Bool _ as v -> v |Typeof ( _x0) -> begin let _x0 = _self.expression _self _x0 in Typeof ( _x0) end |Js_not ( _x0) -> begin let _x0 = _self.expression _self _x0 in Js_not ( _x0) end |Seq ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in Seq ( _x0,_x1) end |Cond ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in let _x2 = _self.expression _self _x2 in Cond ( _x0,_x1,_x2) end |Bin ( _x0,_x1,_x2) -> begin let _x1 = _self.expression _self _x1 in let _x2 = _self.expression _self _x2 in Bin ( _x0,_x1,_x2) end |FlatCall ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in FlatCall ( _x0,_x1) end |Call ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in let _x1 = list _self.expression _self _x1 in Call ( _x0,_x1,_x2) end |String_index ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in String_index ( _x0,_x1) end |Array_index ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in Array_index ( _x0,_x1) end |Static_index ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in Static_index ( _x0,_x1,_x2) end |New ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = option (fun _self arg -> list _self.expression _self arg) _self _x1 in New ( _x0,_x1) end |Var ( _x0) -> begin let _x0 = _self.vident _self _x0 in Var ( _x0) end |Fun ( _x0,_x1,_x2,_x3,_x4) -> begin let _x1 = list _self.ident _self _x1 in let _x2 = _self.block _self _x2 in Fun ( _x0,_x1,_x2,_x3,_x4) end |Str _ as v -> v |Unicode _ as v -> v |Raw_js_code _ as v -> v |Array ( _x0,_x1) -> begin let _x0 = list _self.expression _self _x0 in Array ( _x0,_x1) end |Optional_block ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in Optional_block ( _x0,_x1) end |Caml_block ( _x0,_x1,_x2,_x3) -> begin let _x0 = list _self.expression _self _x0 in let _x2 = _self.expression _self _x2 in Caml_block ( _x0,_x1,_x2,_x3) end |Caml_block_tag ( _x0) -> begin let _x0 = _self.expression _self _x0 in Caml_block_tag ( _x0) end |Number _ as v -> v |Object ( _x0) -> begin let _x0 = property_map _self _x0 in Object ( _x0) end |Undefined as v -> v |Null as v -> v let for_ident_expression : for_ident_expression fn = (fun _self arg -> _self.expression _self arg) let finish_ident_expression : finish_ident_expression fn = (fun _self arg -> _self.expression _self arg) let case_clause : case_clause fn = fun _self { switch_body = _x0;should_break = _x1;comment = _x2} -> begin let _x0 = _self.block _self _x0 in {switch_body = _x0;should_break = _x1;comment = _x2} end let string_clause : string_clause fn = (fun _self (_x0,_x1) -> begin let _x1 = case_clause _self _x1 in (_x0,_x1) end) let int_clause : int_clause fn = (fun _self (_x0,_x1) -> begin let _x1 = case_clause _self _x1 in (_x0,_x1) end) let statement_desc : statement_desc fn = fun _self -> function | Block ( _x0) -> begin let _x0 = _self.block _self _x0 in Block ( _x0) end |Variable ( _x0) -> begin let _x0 = _self.variable_declaration _self _x0 in Variable ( _x0) end |Exp ( _x0) -> begin let _x0 = _self.expression _self _x0 in Exp ( _x0) end |If ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.block _self _x1 in let _x2 = _self.block _self _x2 in If ( _x0,_x1,_x2) end |While ( _x0,_x1,_x2,_x3) -> begin let _x0 = option label _self _x0 in let _x1 = _self.expression _self _x1 in let _x2 = _self.block _self _x2 in While ( _x0,_x1,_x2,_x3) end |ForRange ( _x0,_x1,_x2,_x3,_x4,_x5) -> begin let _x0 = option for_ident_expression _self _x0 in let _x1 = finish_ident_expression _self _x1 in let _x2 = _self.for_ident _self _x2 in let _x3 = for_direction _self _x3 in let _x4 = _self.block _self _x4 in ForRange ( _x0,_x1,_x2,_x3,_x4,_x5) end |Continue ( _x0) -> begin let _x0 = label _self _x0 in Continue ( _x0) end |Break as v -> v |Return ( _x0) -> begin let _x0 = _self.expression _self _x0 in Return ( _x0) end |Int_switch ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in let _x1 = list int_clause _self _x1 in let _x2 = option _self.block _self _x2 in Int_switch ( _x0,_x1,_x2) end |String_switch ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in let _x1 = list string_clause _self _x1 in let _x2 = option _self.block _self _x2 in String_switch ( _x0,_x1,_x2) end |Throw ( _x0) -> begin let _x0 = _self.expression _self _x0 in Throw ( _x0) end |Try ( _x0,_x1,_x2) -> begin let _x0 = _self.block _self _x0 in let _x1 = option ((fun _self (_x0,_x1) -> begin let _x0 = _self.exception_ident _self _x0 in let _x1 = _self.block _self _x1 in (_x0,_x1) end)) _self _x1 in let _x2 = option _self.block _self _x2 in Try ( _x0,_x1,_x2) end |Debugger as v -> v let expression : expression fn = fun _self { expression_desc = _x0;comment = _x1;loc = _x2} -> begin let _x0 = expression_desc _self _x0 in {expression_desc = _x0;comment = _x1;loc = _x2} end let statement : statement fn = fun _self { statement_desc = _x0;comment = _x1} -> begin let _x0 = statement_desc _self _x0 in {statement_desc = _x0;comment = _x1} end let variable_declaration : variable_declaration fn = fun _self { ident = _x0;value = _x1;property = _x2;ident_info = _x3} -> begin let _x0 = _self.ident _self _x0 in let _x1 = option _self.expression _self _x1 in {ident = _x0;value = _x1;property = _x2;ident_info = _x3} end let block : block fn = fun _self arg -> list _self.statement _self arg let program : program fn = fun _self { block = _x0;exports = _x1;export_set = _x2} -> begin let _x0 = _self.block _self _x0 in {block = _x0;exports = _x1;export_set = _x2} end let deps_program : deps_program fn = fun _self { program = _x0;modules = _x1;side_effect = _x2} -> begin let _x0 = _self.program _self _x0 in let _x1 = required_modules _self _x1 in {program = _x0;modules = _x1;side_effect = _x2} end let super : iter = { ident; module_id; vident; exception_ident; for_ident; expression; statement; variable_declaration; block; program }
null
https://raw.githubusercontent.com/melange-re/melange/24083b39f10d8df40a786d890d7530b514ba70a4/jscomp/core/js_record_map.ml
ocaml
open J let [@inline] unknown _ x = x let [@inline] option sub self = fun v -> match v with | None -> None | Some v -> Some (sub self v) let rec list sub self = fun x -> match x with | [] -> [] | x::xs -> let v = sub self x in v :: list sub self xs type iter = { ident : ident fn; module_id : module_id fn; vident : vident fn; exception_ident : exception_ident fn; for_ident : for_ident fn; expression : expression fn; statement : statement fn; variable_declaration : variable_declaration fn; block : block fn; program : program fn } and 'a fn = iter -> 'a -> 'a let label : label fn = unknown let ident : ident fn = unknown let module_id : module_id fn = fun _self { id = _x0;kind = _x1} -> begin let _x0 = _self.ident _self _x0 in {id = _x0;kind = _x1} end let required_modules : required_modules fn = fun _self arg -> list _self.module_id _self arg let vident : vident fn = fun _self -> function | Id ( _x0) -> begin let _x0 = _self.ident _self _x0 in Id ( _x0) end |Qualified ( _x0,_x1) -> begin let _x0 = _self.module_id _self _x0 in Qualified ( _x0,_x1) end let exception_ident : exception_ident fn = (fun _self arg -> _self.ident _self arg) let for_ident : for_ident fn = (fun _self arg -> _self.ident _self arg) let for_direction : for_direction fn = unknown let property_map : property_map fn = fun _self arg -> list ((fun _self (_x0,_x1) -> begin let _x1 = _self.expression _self _x1 in (_x0,_x1) end)) _self arg let length_object : length_object fn = unknown let expression_desc : expression_desc fn = fun _self -> function | Length ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = length_object _self _x1 in Length ( _x0,_x1) end |Char_of_int ( _x0) -> begin let _x0 = _self.expression _self _x0 in Char_of_int ( _x0) end |Char_to_int ( _x0) -> begin let _x0 = _self.expression _self _x0 in Char_to_int ( _x0) end |Is_null_or_undefined ( _x0) -> begin let _x0 = _self.expression _self _x0 in Is_null_or_undefined ( _x0) end |String_append ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in String_append ( _x0,_x1) end |Bool _ as v -> v |Typeof ( _x0) -> begin let _x0 = _self.expression _self _x0 in Typeof ( _x0) end |Js_not ( _x0) -> begin let _x0 = _self.expression _self _x0 in Js_not ( _x0) end |Seq ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in Seq ( _x0,_x1) end |Cond ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in let _x2 = _self.expression _self _x2 in Cond ( _x0,_x1,_x2) end |Bin ( _x0,_x1,_x2) -> begin let _x1 = _self.expression _self _x1 in let _x2 = _self.expression _self _x2 in Bin ( _x0,_x1,_x2) end |FlatCall ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in FlatCall ( _x0,_x1) end |Call ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in let _x1 = list _self.expression _self _x1 in Call ( _x0,_x1,_x2) end |String_index ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in String_index ( _x0,_x1) end |Array_index ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.expression _self _x1 in Array_index ( _x0,_x1) end |Static_index ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in Static_index ( _x0,_x1,_x2) end |New ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in let _x1 = option (fun _self arg -> list _self.expression _self arg) _self _x1 in New ( _x0,_x1) end |Var ( _x0) -> begin let _x0 = _self.vident _self _x0 in Var ( _x0) end |Fun ( _x0,_x1,_x2,_x3,_x4) -> begin let _x1 = list _self.ident _self _x1 in let _x2 = _self.block _self _x2 in Fun ( _x0,_x1,_x2,_x3,_x4) end |Str _ as v -> v |Unicode _ as v -> v |Raw_js_code _ as v -> v |Array ( _x0,_x1) -> begin let _x0 = list _self.expression _self _x0 in Array ( _x0,_x1) end |Optional_block ( _x0,_x1) -> begin let _x0 = _self.expression _self _x0 in Optional_block ( _x0,_x1) end |Caml_block ( _x0,_x1,_x2,_x3) -> begin let _x0 = list _self.expression _self _x0 in let _x2 = _self.expression _self _x2 in Caml_block ( _x0,_x1,_x2,_x3) end |Caml_block_tag ( _x0) -> begin let _x0 = _self.expression _self _x0 in Caml_block_tag ( _x0) end |Number _ as v -> v |Object ( _x0) -> begin let _x0 = property_map _self _x0 in Object ( _x0) end |Undefined as v -> v |Null as v -> v let for_ident_expression : for_ident_expression fn = (fun _self arg -> _self.expression _self arg) let finish_ident_expression : finish_ident_expression fn = (fun _self arg -> _self.expression _self arg) let case_clause : case_clause fn = fun _self { switch_body = _x0;should_break = _x1;comment = _x2} -> begin let _x0 = _self.block _self _x0 in {switch_body = _x0;should_break = _x1;comment = _x2} end let string_clause : string_clause fn = (fun _self (_x0,_x1) -> begin let _x1 = case_clause _self _x1 in (_x0,_x1) end) let int_clause : int_clause fn = (fun _self (_x0,_x1) -> begin let _x1 = case_clause _self _x1 in (_x0,_x1) end) let statement_desc : statement_desc fn = fun _self -> function | Block ( _x0) -> begin let _x0 = _self.block _self _x0 in Block ( _x0) end |Variable ( _x0) -> begin let _x0 = _self.variable_declaration _self _x0 in Variable ( _x0) end |Exp ( _x0) -> begin let _x0 = _self.expression _self _x0 in Exp ( _x0) end |If ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in let _x1 = _self.block _self _x1 in let _x2 = _self.block _self _x2 in If ( _x0,_x1,_x2) end |While ( _x0,_x1,_x2,_x3) -> begin let _x0 = option label _self _x0 in let _x1 = _self.expression _self _x1 in let _x2 = _self.block _self _x2 in While ( _x0,_x1,_x2,_x3) end |ForRange ( _x0,_x1,_x2,_x3,_x4,_x5) -> begin let _x0 = option for_ident_expression _self _x0 in let _x1 = finish_ident_expression _self _x1 in let _x2 = _self.for_ident _self _x2 in let _x3 = for_direction _self _x3 in let _x4 = _self.block _self _x4 in ForRange ( _x0,_x1,_x2,_x3,_x4,_x5) end |Continue ( _x0) -> begin let _x0 = label _self _x0 in Continue ( _x0) end |Break as v -> v |Return ( _x0) -> begin let _x0 = _self.expression _self _x0 in Return ( _x0) end |Int_switch ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in let _x1 = list int_clause _self _x1 in let _x2 = option _self.block _self _x2 in Int_switch ( _x0,_x1,_x2) end |String_switch ( _x0,_x1,_x2) -> begin let _x0 = _self.expression _self _x0 in let _x1 = list string_clause _self _x1 in let _x2 = option _self.block _self _x2 in String_switch ( _x0,_x1,_x2) end |Throw ( _x0) -> begin let _x0 = _self.expression _self _x0 in Throw ( _x0) end |Try ( _x0,_x1,_x2) -> begin let _x0 = _self.block _self _x0 in let _x1 = option ((fun _self (_x0,_x1) -> begin let _x0 = _self.exception_ident _self _x0 in let _x1 = _self.block _self _x1 in (_x0,_x1) end)) _self _x1 in let _x2 = option _self.block _self _x2 in Try ( _x0,_x1,_x2) end |Debugger as v -> v let expression : expression fn = fun _self { expression_desc = _x0;comment = _x1;loc = _x2} -> begin let _x0 = expression_desc _self _x0 in {expression_desc = _x0;comment = _x1;loc = _x2} end let statement : statement fn = fun _self { statement_desc = _x0;comment = _x1} -> begin let _x0 = statement_desc _self _x0 in {statement_desc = _x0;comment = _x1} end let variable_declaration : variable_declaration fn = fun _self { ident = _x0;value = _x1;property = _x2;ident_info = _x3} -> begin let _x0 = _self.ident _self _x0 in let _x1 = option _self.expression _self _x1 in {ident = _x0;value = _x1;property = _x2;ident_info = _x3} end let block : block fn = fun _self arg -> list _self.statement _self arg let program : program fn = fun _self { block = _x0;exports = _x1;export_set = _x2} -> begin let _x0 = _self.block _self _x0 in {block = _x0;exports = _x1;export_set = _x2} end let deps_program : deps_program fn = fun _self { program = _x0;modules = _x1;side_effect = _x2} -> begin let _x0 = _self.program _self _x0 in let _x1 = required_modules _self _x1 in {program = _x0;modules = _x1;side_effect = _x2} end let super : iter = { ident; module_id; vident; exception_ident; for_ident; expression; statement; variable_declaration; block; program }
33f77ad23cc3595fd06dd29758ee000fd550f6beb8cebeeba46602ff27272c85
caisah/sicp-exercises-and-examples
ex.3.69.scm
Write a procedure triples that takes three infinite streams s , t , and u , and produces the stream of triples ( si , tj , uk ) such that i < = j < = k. Use triples to generate the stream of all Pythagorean triples of positive integers , ie , the triples ( i , j , k ) ;; such that i <= j, and i^2 + j^2 = k^2. (define (interleave s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (interleave s2 (stream-cdr s1))))) (define (pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (pairs (stream-cdr s) (stream-cdr t))))) (define (triples s t u) (cons-stream (list (stream-car s) (stream-car t) (stream-car u)) (interleave (stream-map (lambda (x) (cons (stream-car s) x)) (stream-cdr (pairs t u))) (triples (stream-cdr s) (stream-cdr t) (stream-cdr u))))) (define (phythagorean-numbers) (define (square x) (* x x)) (define numbers (triples integers integers integers)) (stream-filter (lambda (x) (= (square (caddr x)) (+ (square (car x)) (square (cadr x))))) numbers))
null
https://raw.githubusercontent.com/caisah/sicp-exercises-and-examples/605c698d7495aa3474c2b6edcd1312cb16c5b5cb/3.5.3-exploiting_the_stream_paradigm/ex.3.69.scm
scheme
such that i <= j, and i^2 + j^2 = k^2.
Write a procedure triples that takes three infinite streams s , t , and u , and produces the stream of triples ( si , tj , uk ) such that i < = j < = k. Use triples to generate the stream of all Pythagorean triples of positive integers , ie , the triples ( i , j , k ) (define (interleave s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (interleave s2 (stream-cdr s1))))) (define (pairs s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (pairs (stream-cdr s) (stream-cdr t))))) (define (triples s t u) (cons-stream (list (stream-car s) (stream-car t) (stream-car u)) (interleave (stream-map (lambda (x) (cons (stream-car s) x)) (stream-cdr (pairs t u))) (triples (stream-cdr s) (stream-cdr t) (stream-cdr u))))) (define (phythagorean-numbers) (define (square x) (* x x)) (define numbers (triples integers integers integers)) (stream-filter (lambda (x) (= (square (caddr x)) (+ (square (car x)) (square (cadr x))))) numbers))
813f954da27d5c0de5680a5a4eab05307a5d0e5159ef2c9515c9761e17f05d79
skanev/playground
27.scm
SICP exercise 3.27 ; ; Memoization (also called tabulation) is a technique that enables a procedure ; to record, in a local table, values that have previously been computed. This ; technique can make a vast difference in the performance of a program. A memoized procedure a table in which values of previous calls are ; stored using as keys the arguments that produced the values. When the memoized procedure is asked to compute a value , it first checks the table to ; see if the value is already there and, if so, just returns that value. ; Otherwise, it compute sthe new value in the ordinary way and stores this in ; the table. As an example of memoization, recall from section 1.2.2 the ; exponential process for computing Fibonacci numbers: ; ; (define (fib n) ; (cond ((=n 0) 0) ( (= n 1 ) 1 ) ; (else (+ (fib (- n 1)) ; (fib (- n 2)))))) ; ; The memoized version of the same procedure is ; ; (define memo-fib ; (memoize (lambda (n) ; (cond ((= n 0) 0) ( (= n 1 ) 1 ) ; (else (+ (memo-fib (- n 1)) ; (memo-fib (- n 2)))))))) ; ; where the memoizer is defined as ; ; (define (memoize f) ; (let ((table (make-table))) ; (lambda (x) ; (let ((previously-computed-result (lookup x table))) ; (or previously-computed-result ; (let ((result (f x))) ; (insert! x result table) ; result)))))) ; ; Draw an environment diagram to analyze the computation (memo-fib 3). Explain ; why memo-fib computes the nth Fibonacci number in a number of steps ; proportional to n. Would the scheme still work if we had simply defined ; memo-fib to be (memoize fib)? ; God, I hate environment diagrams. Here's how the environment looks before ; computing (memo-fib 3). ; ; globals: ; +-------------------------------------------------------------------------+ ; | memoize: <procedure> | ; | memo-fib: <procedure> | ; +--|----------------------------------------------------------------------+ ; | ^ | | ; | +----------------+ ; | | f: <procedure> --------> <lambda> ; | +----------------+ params: n ; | ^ body: (cond ((= n 0) 0) | | ... ; | +----------------+ ; | | table: <table> --------> (*table) ; | +----------------+ ; | ^ | | ; +------> <lambda> ; parameters: x ; body: (let ((... ; ; When we call (memo-fib 3) it does a table lookup, fails and then goes to calculate [ 1 ] ( + ( memo - fib 2 ) ( memo - fib 1 ) ) . Let 's assume left - to - right ; evaluation. It procedures to evaluate (memo-fib 2) which fails the table lookup and then results to [ 2 ] ( + ( memo - fib 1 ) ( memo - fib 0 ) ) . Both fail the ; lookup, but at least they return immediatelly and the results are written in the table . This is how the environment looks when [ 2 ] completes : ; ; globals: ; +-------------------------------------------------------------------------+ ; | memoize: <procedure> | ; | memo-fib: <procedure> | ; +--|----------------------------------------------------------------------+ ; | ^ | | ; | +----------------+ ; | | f: <procedure> --------> <lambda> ; | +----------------+ params: n ; | ^ body: (cond ((= n 0) 0) | | ... ; | +----------------+ | | table : < table > -------- > ( * table ( 1 . 1 ) ; | +----------------+ (0 . 0)) ; | ^ ^ ; | | | ; +----|-> <lambda> ; | parameters: x ; | body: (let ((... ; | ; +------------------------------------+ [ 1 ] | [ 2 ] | ; +--------------------------------+ +--------------------------------+ | x : 3 | | x : 2 | | previously - computed - result : # f | | previously - computed - result : # f | ; +--------------------------------+ +--------------------------------+ ; ; When (f x) completes, the result is written in the table and the function ; returns it. This is how the environment looks after (make-fib 2) has ; returned: ; ; globals: ; +-------------------------------------------------------------------------+ ; | memoize: <procedure> | ; | memo-fib: <procedure> | ; +--|----------------------------------------------------------------------+ ; | ^ | | ; | +----------------+ ; | | f: <procedure> --------> <lambda> ; | +----------------+ params: n ; | ^ body: (cond ((= n 0) 0) | | ... ; | +----------------+ | | table : < table > -------- > ( * table ( 2 . 2 ) | + ----------------+ ( 1 . 1 ) ; | ^ ^ (0 . 0)) ; | | | ; +----|-> <lambda> ; | parameters: x ; | body: (let ((... [ 1 ] | ; +--------------------------------+ | x : 3 | ; | previously-computed-result: #f | ; +--------------------------------+ ; Now the second part of [ 1 ] computes , which is ( memo - fib 1 ) . This time it is found in the table and instead of calling f , the lookup just returns 1 . The addition is carried out and the final result , 3 , is written in the table and ; then returned. In the end, we have the following environment: ; ; globals: ; +-------------------------------------------------------------------------+ ; | memoize: <procedure> | ; | memo-fib: <procedure> | ; +--|----------------------------------------------------------------------+ ; | ^ | | ; | +----------------+ ; | | f: <procedure> --------> <lambda> ; | +----------------+ params: n ; | ^ body: (cond ((= n 0) 0) | | ... ; | +----------------+ | | table : < table > -------- > ( * table ( 3 . 3 ) | + ----------------+ ( 2 . 2 ) | ^ ( 1 . 1 ) ; | | (0 . 0)) ; +------> <lambda> ; parameters: x ; body: (let ((... ; ; You can note, that (memo-fib 1) invoked f only once. Even if it had to be calculated once in [ 1 ] and once in [ 2 ] . Furthermore , note that if we call ; (memo-fib 3) now, f would not get invoked at all. That's why the steps are ; proportional to n. ; ; This scheme would not work if we did: ; ; (define memo-fib (memoize fib)) ; Or more accuratelly , it would work half - way . The problem is that fib calls ; recursively itself, instead of memo-fib. Thus, intermediate values are not ; calculated and the time is still exponential. The only benefit is that if we ; call memo-fib with the same argument twice, it will reuse the result from the first calculation .
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/03/27.scm
scheme
Memoization (also called tabulation) is a technique that enables a procedure to record, in a local table, values that have previously been computed. This technique can make a vast difference in the performance of a program. A stored using as keys the arguments that produced the values. When the see if the value is already there and, if so, just returns that value. Otherwise, it compute sthe new value in the ordinary way and stores this in the table. As an example of memoization, recall from section 1.2.2 the exponential process for computing Fibonacci numbers: (define (fib n) (cond ((=n 0) 0) (else (+ (fib (- n 1)) (fib (- n 2)))))) The memoized version of the same procedure is (define memo-fib (memoize (lambda (n) (cond ((= n 0) 0) (else (+ (memo-fib (- n 1)) (memo-fib (- n 2)))))))) where the memoizer is defined as (define (memoize f) (let ((table (make-table))) (lambda (x) (let ((previously-computed-result (lookup x table))) (or previously-computed-result (let ((result (f x))) (insert! x result table) result)))))) Draw an environment diagram to analyze the computation (memo-fib 3). Explain why memo-fib computes the nth Fibonacci number in a number of steps proportional to n. Would the scheme still work if we had simply defined memo-fib to be (memoize fib)? God, I hate environment diagrams. Here's how the environment looks before computing (memo-fib 3). globals: +-------------------------------------------------------------------------+ | memoize: <procedure> | | memo-fib: <procedure> | +--|----------------------------------------------------------------------+ | ^ | +----------------+ | | f: <procedure> --------> <lambda> | +----------------+ params: n | ^ body: (cond ((= n 0) 0) | +----------------+ | | table: <table> --------> (*table) | +----------------+ | ^ +------> <lambda> parameters: x body: (let ((... When we call (memo-fib 3) it does a table lookup, fails and then goes to evaluation. It procedures to evaluate (memo-fib 2) which fails the table lookup, but at least they return immediatelly and the results are written in globals: +-------------------------------------------------------------------------+ | memoize: <procedure> | | memo-fib: <procedure> | +--|----------------------------------------------------------------------+ | ^ | +----------------+ | | f: <procedure> --------> <lambda> | +----------------+ params: n | ^ body: (cond ((= n 0) 0) | +----------------+ | +----------------+ (0 . 0)) | ^ ^ | | | +----|-> <lambda> | parameters: x | body: (let ((... | +------------------------------------+ +--------------------------------+ +--------------------------------+ +--------------------------------+ +--------------------------------+ When (f x) completes, the result is written in the table and the function returns it. This is how the environment looks after (make-fib 2) has returned: globals: +-------------------------------------------------------------------------+ | memoize: <procedure> | | memo-fib: <procedure> | +--|----------------------------------------------------------------------+ | ^ | +----------------+ | | f: <procedure> --------> <lambda> | +----------------+ params: n | ^ body: (cond ((= n 0) 0) | +----------------+ | ^ ^ (0 . 0)) | | | +----|-> <lambda> | parameters: x | body: (let ((... +--------------------------------+ | previously-computed-result: #f | +--------------------------------+ then returned. In the end, we have the following environment: globals: +-------------------------------------------------------------------------+ | memoize: <procedure> | | memo-fib: <procedure> | +--|----------------------------------------------------------------------+ | ^ | +----------------+ | | f: <procedure> --------> <lambda> | +----------------+ params: n | ^ body: (cond ((= n 0) 0) | +----------------+ | | (0 . 0)) +------> <lambda> parameters: x body: (let ((... You can note, that (memo-fib 1) invoked f only once. Even if it had to be (memo-fib 3) now, f would not get invoked at all. That's why the steps are proportional to n. This scheme would not work if we did: (define memo-fib (memoize fib)) recursively itself, instead of memo-fib. Thus, intermediate values are not calculated and the time is still exponential. The only benefit is that if we call memo-fib with the same argument twice, it will reuse the result from
SICP exercise 3.27 memoized procedure a table in which values of previous calls are memoized procedure is asked to compute a value , it first checks the table to ( (= n 1 ) 1 ) ( (= n 1 ) 1 ) | | | | ... | | calculate [ 1 ] ( + ( memo - fib 2 ) ( memo - fib 1 ) ) . Let 's assume left - to - right lookup and then results to [ 2 ] ( + ( memo - fib 1 ) ( memo - fib 0 ) ) . Both fail the the table . This is how the environment looks when [ 2 ] completes : | | | | ... | | table : < table > -------- > ( * table ( 1 . 1 ) [ 1 ] | [ 2 ] | | x : 3 | | x : 2 | | previously - computed - result : # f | | previously - computed - result : # f | | | | | ... | | table : < table > -------- > ( * table ( 2 . 2 ) | + ----------------+ ( 1 . 1 ) [ 1 ] | | x : 3 | Now the second part of [ 1 ] computes , which is ( memo - fib 1 ) . This time it is found in the table and instead of calling f , the lookup just returns 1 . The addition is carried out and the final result , 3 , is written in the table and | | | | ... | | table : < table > -------- > ( * table ( 3 . 3 ) | + ----------------+ ( 2 . 2 ) | ^ ( 1 . 1 ) calculated once in [ 1 ] and once in [ 2 ] . Furthermore , note that if we call Or more accuratelly , it would work half - way . The problem is that fib calls the first calculation .
a0a45bc1f73e65d1c5772a20b8a56306489075560dfc14ae78ff34e21bd2f034
StarGazerM/ppa-in-code
du-chain.rkt
;; Define-Use chains ;; link the label to where use it < > 2020 Syracuse #lang racket (require "tiny-lang.rkt" "flow.rkt" "live-variable.rkt") ;; find all path from src to dst (define (find-all-path s* src dst) (define flow-set (flow s*)) (define (next-label lc) (for/fold ([res '()]) ([edge (in-list flow-set)]) (if (equal? (first edge) lc) (cons (second edge) res) res))) (define (helper l pre) (define nexts (next-label l)) (cond [(equal? l dst) `(,(reverse (cons dst pre)))] [(empty? nexts) '()] [else (apply append (map (λ (n) (helper n (cons l pre))) nexts))])) (helper src '())) ;; definition clear path of a varible is the dataflow path do not contain assignment to that variable (define (clear-path? s* x l l-p) (define paths (find-all-path s* l l-p)) (cond [(empty? paths) #f] [(use? s* x l-p) (andmap (λ (p) (andmap (λ (li) (not (def? s* x li))) (take p (sub1 (length p))))) paths)] [else #f])) ;; originally only take x and l (define (use? s* x l) (define bl (find-block-by-label s* l)) (member x (set->list (gen-LV bl)))) (define (def? s* x l) (define bl (find-block-by-label s* l)) (member x (set->list (kill-LV bl)))) ;; ud,du : Var* × Lab* → P(Lab*) (define (ud s* x l-p) (define all-lab (labels s*)) (define l-set (filter (λ (l) (let ([l-pps (for/fold ([res '()]) ([edge (in-list (flow s*))]) (if (equal? (first edge) l) (cons (second edge) res) res))]) (and (def? s* x l) (ormap (λ (l-pp) (clear-path? s* x l-pp l-p)) l-pps)))) all-lab)) ;; if x is not defined inside current S* but not modified in S* (if (clear-path? s* x (init-flow s*) l-p) (set-add l-set '?) l-set)) #;(define (du s* x l) (define flow-set (flow s*)) (define all-lab (labels s*)) (define l-pps (for/fold ([res '()]) ([edge (in-list (flow s*))]) (if (equal? (first edge) l) (cons (second edge) res) res))) (cond [(equal? l '?) (filter (λ (l-p) (clear-path? s* x (init-flow s*) l-p)) all-lab)] [(not (def? s* x l)) '()] [else (filter (λ () ) all-lab)])) (define (du s* x l) (define flow-set (flow s*)) (define all-lab (labels s*)) (for/fold ([res '()]) ([l-p (in-list all-lab)]) (set-union res (ud s* x l-p)))) in this example block 1 can be removed since it no used before reassign code motion can be performed on block 6 , because only used in assign ;; earlier (define example2-12 '((1 = x 0) (2 = x 3) (if (3 (== z x)) (4 = z 0) (5 = z x)) (6 = y x) (7 = x (+ y z)))) du-chain.rkt > ( z 3 ) ;; '(?) du-chain.rkt > ( z 4 ) ;; '() du-chain.rkt > ( z 7 ) ' ( 4 5 ) du-chain.rkt > ( y 1 ) ;; '() du-chain.rkt > ( y 7 ) ' ( 6 ) du-chain.rkt > ( x 3 ) ' ( 2 ) du-chain.rkt > ( x 5 ) ' ( 2 ) du-chain.rkt > ( x 6 ) ' ( 2 ) ;; du-chain.rkt>
null
https://raw.githubusercontent.com/StarGazerM/ppa-in-code/0c04c50e64118a9468f24427bca11280775c9d74/dataflow/du-chain.rkt
racket
Define-Use chains link the label to where use it find all path from src to dst definition clear path of a varible is the dataflow path do not contain assignment to that variable originally only take x and l ud,du : Var* × Lab* → P(Lab*) if x is not defined inside current S* but not modified in S* (define (du s* x l) earlier '(?) '() '() du-chain.rkt>
< > 2020 Syracuse #lang racket (require "tiny-lang.rkt" "flow.rkt" "live-variable.rkt") (define (find-all-path s* src dst) (define flow-set (flow s*)) (define (next-label lc) (for/fold ([res '()]) ([edge (in-list flow-set)]) (if (equal? (first edge) lc) (cons (second edge) res) res))) (define (helper l pre) (define nexts (next-label l)) (cond [(equal? l dst) `(,(reverse (cons dst pre)))] [(empty? nexts) '()] [else (apply append (map (λ (n) (helper n (cons l pre))) nexts))])) (helper src '())) (define (clear-path? s* x l l-p) (define paths (find-all-path s* l l-p)) (cond [(empty? paths) #f] [(use? s* x l-p) (andmap (λ (p) (andmap (λ (li) (not (def? s* x li))) (take p (sub1 (length p))))) paths)] [else #f])) (define (use? s* x l) (define bl (find-block-by-label s* l)) (member x (set->list (gen-LV bl)))) (define (def? s* x l) (define bl (find-block-by-label s* l)) (member x (set->list (kill-LV bl)))) (define (ud s* x l-p) (define all-lab (labels s*)) (define l-set (filter (λ (l) (let ([l-pps (for/fold ([res '()]) ([edge (in-list (flow s*))]) (if (equal? (first edge) l) (cons (second edge) res) res))]) (and (def? s* x l) (ormap (λ (l-pp) (clear-path? s* x l-pp l-p)) l-pps)))) all-lab)) (if (clear-path? s* x (init-flow s*) l-p) (set-add l-set '?) l-set)) (define flow-set (flow s*)) (define all-lab (labels s*)) (define l-pps (for/fold ([res '()]) ([edge (in-list (flow s*))]) (if (equal? (first edge) l) (cons (second edge) res) res))) (cond [(equal? l '?) (filter (λ (l-p) (clear-path? s* x (init-flow s*) l-p)) all-lab)] [(not (def? s* x l)) '()] [else (filter (λ () ) all-lab)])) (define (du s* x l) (define flow-set (flow s*)) (define all-lab (labels s*)) (for/fold ([res '()]) ([l-p (in-list all-lab)]) (set-union res (ud s* x l-p)))) in this example block 1 can be removed since it no used before reassign code motion can be performed on block 6 , because only used in assign (define example2-12 '((1 = x 0) (2 = x 3) (if (3 (== z x)) (4 = z 0) (5 = z x)) (6 = y x) (7 = x (+ y z)))) du-chain.rkt > ( z 3 ) du-chain.rkt > ( z 4 ) du-chain.rkt > ( z 7 ) ' ( 4 5 ) du-chain.rkt > ( y 1 ) du-chain.rkt > ( y 7 ) ' ( 6 ) du-chain.rkt > ( x 3 ) ' ( 2 ) du-chain.rkt > ( x 5 ) ' ( 2 ) du-chain.rkt > ( x 6 ) ' ( 2 )
3d8866eea2a43c247a1c216d2b8fa33a6c3cfd05d60e91d0ecb827b010c98d61
bgusach/exercises-htdp2e
ex-141.rkt
#lang htdp/bsl ; List-of-string -> String concatenate all strings in l into one long string (check-expect (cat '()) "") (check-expect (cat (cons "a" (cons "b" '()))) "ab") (check-expect (cat (cons "ab" (cons "cd" (cons "ef" '())))) "abcdef") (define (cat l) (cond [(empty? l) ""] [else (string-append (first l) (cat (rest l)))] )) (require test-engine/racket-tests) (test)
null
https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/ex-141.rkt
racket
List-of-string -> String
#lang htdp/bsl concatenate all strings in l into one long string (check-expect (cat '()) "") (check-expect (cat (cons "a" (cons "b" '()))) "ab") (check-expect (cat (cons "ab" (cons "cd" (cons "ef" '())))) "abcdef") (define (cat l) (cond [(empty? l) ""] [else (string-append (first l) (cat (rest l)))] )) (require test-engine/racket-tests) (test)
a20dbcb8e61ac04d1fb1c2e1b03bbd491173a49c67cee6b634c5620d872968c2
Paczesiowa/hsenv
String.hs
module Util.String (padTo) where padTo :: String -> Int -> String padTo s n | length s < n = take n $ s ++ repeat ' ' | otherwise = s
null
https://raw.githubusercontent.com/Paczesiowa/hsenv/b904436e10bde707a7838661a5ec30de430ca2b9/src/Util/String.hs
haskell
module Util.String (padTo) where padTo :: String -> Int -> String padTo s n | length s < n = take n $ s ++ repeat ' ' | otherwise = s
a167b92f540b86bf225bc2bfe6f3d488377ae91b1202df085ab51de00c957fda
maxtuno/tooloud
project.clj
(defproject tooloud "0.1.0-SNAPSHOT" :description "Overtone Dubstep Template" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.5.0-alpha3"] [overtone "0.8.0-SNAPSHOT"]])
null
https://raw.githubusercontent.com/maxtuno/tooloud/136cdb516066879565280167e914c37e3d731466/project.clj
clojure
(defproject tooloud "0.1.0-SNAPSHOT" :description "Overtone Dubstep Template" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.5.0-alpha3"] [overtone "0.8.0-SNAPSHOT"]])
9edbd32f606e21c2d9284b9ebe68003140944e609c834b2dd90d139e4c566065
buntine/Simply-Scheme-Exercises
19-5.scm
Rewrite the true - for - all ? procedure from Exercise 8.10 . Do not use every , ; keep, or accumulate ; Not sure if I've cheated here. I reimplemented keep, but it's recursive. (define (keep2 pred sent) (if (word? sent) (combine pred sent word "") (combine pred sent se '()))) (define (combine pred sent combiner null-value) (cond ((empty? sent) null-value) ((pred (first sent)) (combiner (first sent) (combine pred (butfirst sent) combiner null-value))) (else (combine pred (butfirst sent) combiner null-value)))) (define (true-for-all? pred sent) (= (count sent) (count (keep2 pred sent))))
null
https://raw.githubusercontent.com/buntine/Simply-Scheme-Exercises/c6cbf0bd60d6385b506b8df94c348ac5edc7f646/19-implementing-higher-order-functions/19-5.scm
scheme
keep, or accumulate Not sure if I've cheated here. I reimplemented keep, but it's recursive.
Rewrite the true - for - all ? procedure from Exercise 8.10 . Do not use every , (define (keep2 pred sent) (if (word? sent) (combine pred sent word "") (combine pred sent se '()))) (define (combine pred sent combiner null-value) (cond ((empty? sent) null-value) ((pred (first sent)) (combiner (first sent) (combine pred (butfirst sent) combiner null-value))) (else (combine pred (butfirst sent) combiner null-value)))) (define (true-for-all? pred sent) (= (count sent) (count (keep2 pred sent))))
80d89f194d8201dacb71152dfd27aab05b9999075b3f9b20b4ae99410e926d8c
tolysz/ghcjs-stack
Validate.hs
module Distribution.Client.Dependency.Modular.Validate (validateTree) where -- Validation of the tree. -- -- The task here is to make sure all constraints hold. After validation, any -- assignment returned by exploration of the tree should be a complete valid -- assignment, i.e., actually constitute a solution. import Control.Applicative import Control.Monad.Reader hiding (sequence) import Data.List as L import Data.Map as M import Data.Set as S import Data.Traversable import Prelude hiding (sequence) import Language.Haskell.Extension (Extension, Language) import Distribution.Compiler (CompilerInfo(..)) import Distribution.Client.Dependency.Modular.Assignment import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Index import Distribution.Client.Dependency.Modular.Package import qualified Distribution.Client.Dependency.Modular.PSQ as P import Distribution.Client.Dependency.Modular.Tree import Distribution.Client.Dependency.Modular.Version (VR) import Distribution.Client.ComponentDeps (Component) import Distribution.Client.PkgConfigDb (PkgConfigDb, pkgConfigPkgIsPresent) -- In practice, most constraints are implication constraints (IF we have made -- a number of choices, THEN we also have to ensure that). We call constraints -- that for which the preconditions are fulfilled ACTIVE. We maintain a set -- of currently active constraints that we pass down the node. -- -- We aim at detecting inconsistent states as early as possible. -- Whenever we make a choice , there are two things that need to happen : -- ( 1 ) We must check that the choice is consistent with the currently -- active constraints. -- ( 2 ) The choice increases the set of active constraints . For the new -- active constraints, we must check that they are consistent with -- the current state. -- We can actually merge ( 1 ) and ( 2 ) by saying the the current choice is -- a new active constraint, fixing the choice. -- -- If a test fails, we have detected an inconsistent state. We can -- disable the current subtree and do not have to traverse it any further. -- -- We need a good way to represent the current state, i.e., the current -- set of active constraints. Since the main situation where we have to search in it is ( 1 ) , it seems best to store the state by package : for -- every package, we store which versions are still allowed. If for any -- package, we have inconsistent active constraints, we can also stop. This is a particular way to read task ( 2 ): -- ( 2 , weak ) We only check if the new constraints are consistent with -- the choices we've already made, and add them to the active set. -- ( 2 , strong ) We check if the new constraints are consistent with the -- choices we've already made, and the constraints we already have. -- -- It currently seems as if we're implementing the weak variant. However, -- when used together with 'preferEasyGoalChoices', we will find an -- inconsistent state in the very next step. -- -- What do we do about flags? -- -- Like for packages, we store the flag choices we have already made. Now , regarding ( 1 ) , we only have to test whether we 've decided the current flag before . Regarding ( 2 ) , the interesting bit is in discovering -- the new active constraints. To this end, we look up the constraints for -- the package the flag belongs to, and traverse its flagged dependencies. -- Wherever we find the flag in question, we start recording dependencies -- underneath as new active dependencies. If we encounter other flags, we -- check if we've chosen them already and either proceed or stop. -- | The state needed during validation. data ValidateState = VS { supportedExt :: Extension -> Bool, supportedLang :: Language -> Bool, presentPkgs :: PN -> VR -> Bool, index :: Index, saved :: Map QPN (FlaggedDeps Component QPN), -- saved, scoped, dependencies pa :: PreAssignment, qualifyOptions :: QualifyOptions } type Validate = Reader ValidateState validate :: Tree QGoalReason -> Validate (Tree QGoalReason) validate = cata go where go :: TreeF QGoalReason (Validate (Tree QGoalReason)) -> Validate (Tree QGoalReason) go (PChoiceF qpn gr ts) = PChoice qpn gr <$> sequence (P.mapWithKey (goP qpn) ts) go (FChoiceF qfn gr b m ts) = do -- Flag choices may occur repeatedly (because they can introduce new constraints -- in various places). However, subsequent choices must be consistent. We thereby -- collapse repeated flag choice nodes. PA _ pfa _ <- asks pa -- obtain current flag-preassignment case M.lookup qfn pfa of Just rb -> -- flag has already been assigned; collapse choice to the correct branch case P.lookup rb ts of Just t -> goF qfn rb t Nothing -> return $ Fail (varToConflictSet (F qfn)) (MalformedFlagChoice qfn) Nothing -> -- flag choice is new, follow both branches FChoice qfn gr b m <$> sequence (P.mapWithKey (goF qfn) ts) go (SChoiceF qsn gr b ts) = do -- Optional stanza choices are very similar to flag choices. PA _ _ psa <- asks pa -- obtain current stanza-preassignment case M.lookup qsn psa of Just rb -> -- stanza choice has already been made; collapse choice to the correct branch case P.lookup rb ts of Just t -> goS qsn rb t Nothing -> return $ Fail (varToConflictSet (S qsn)) (MalformedStanzaChoice qsn) Nothing -> -- stanza choice is new, follow both branches SChoice qsn gr b <$> sequence (P.mapWithKey (goS qsn) ts) -- We don't need to do anything for goal choices or failure nodes. go (GoalChoiceF ts) = GoalChoice <$> sequence ts go (DoneF rdm ) = pure (Done rdm) go (FailF c fr ) = pure (Fail c fr) -- What to do for package nodes ... goP :: QPN -> POption -> Validate (Tree QGoalReason) -> Validate (Tree QGoalReason) goP qpn@(Q _pp pn) (POption i _) r = do PA ppa pfa psa <- asks pa -- obtain current preassignment extSupported <- asks supportedExt -- obtain the supported extensions langSupported <- asks supportedLang -- obtain the supported languages pkgPresent <- asks presentPkgs -- obtain the present pkg-config pkgs idx <- asks index -- obtain the index svd <- asks saved -- obtain saved dependencies qo <- asks qualifyOptions -- obtain dependencies and index-dictated exclusions introduced by the choice let (PInfo deps _ mfr) = idx ! pn ! i -- qualify the deps in the current scope let qdeps = qualifyDeps qo qpn deps -- the new active constraints are given by the instance we have chosen, -- plus the dependency information we have for that instance let newactives = Dep qpn (Fixed i (P qpn)) : L.map (resetVar (P qpn)) (extractDeps pfa psa qdeps) -- We now try to extend the partial assignment with the new active constraints. let mnppa = extend extSupported langSupported pkgPresent (P qpn) ppa newactives -- In case we continue, we save the scoped dependencies let nsvd = M.insert qpn qdeps svd case mfr of Just fr -> -- The index marks this as an invalid choice. We can stop. return (Fail (varToConflictSet (P qpn)) fr) _ -> case mnppa of Left (c, d) -> -- We have an inconsistency. We can stop. return (Fail c (Conflicting d)) Right nppa -> -- We have an updated partial assignment for the recursive validation. local (\ s -> s { pa = PA nppa pfa psa, saved = nsvd }) r -- What to do for flag nodes ... goF :: QFN -> Bool -> Validate (Tree QGoalReason) -> Validate (Tree QGoalReason) goF qfn@(FN (PI qpn _i) _f) b r = do PA ppa pfa psa <- asks pa -- obtain current preassignment extSupported <- asks supportedExt -- obtain the supported extensions langSupported <- asks supportedLang -- obtain the supported languages pkgPresent <- asks presentPkgs -- obtain the present pkg-config pkgs svd <- asks saved -- obtain saved dependencies -- Note that there should be saved dependencies for the package in question, -- because while building, we do not choose flags before we see the packages -- that define them. let qdeps = svd ! qpn -- We take the *saved* dependencies, because these have been qualified in the -- correct scope. -- -- Extend the flag assignment let npfa = M.insert qfn b pfa -- We now try to get the new active dependencies we might learn about because -- we have chosen a new flag. let newactives = extractNewDeps (F qfn) b npfa psa qdeps -- As in the package case, we try to extend the partial assignment. case extend extSupported langSupported pkgPresent (F qfn) ppa newactives of Left (c, d) -> return (Fail c (Conflicting d)) -- inconsistency found Right nppa -> local (\ s -> s { pa = PA nppa npfa psa }) r -- What to do for stanza nodes (similar to flag nodes) ... goS :: QSN -> Bool -> Validate (Tree QGoalReason) -> Validate (Tree QGoalReason) goS qsn@(SN (PI qpn _i) _f) b r = do PA ppa pfa psa <- asks pa -- obtain current preassignment extSupported <- asks supportedExt -- obtain the supported extensions langSupported <- asks supportedLang -- obtain the supported languages pkgPresent <- asks presentPkgs -- obtain the present pkg-config pkgs svd <- asks saved -- obtain saved dependencies -- Note that there should be saved dependencies for the package in question, -- because while building, we do not choose flags before we see the packages -- that define them. let qdeps = svd ! qpn -- We take the *saved* dependencies, because these have been qualified in the -- correct scope. -- -- Extend the flag assignment let npsa = M.insert qsn b psa -- We now try to get the new active dependencies we might learn about because -- we have chosen a new flag. let newactives = extractNewDeps (S qsn) b pfa npsa qdeps -- As in the package case, we try to extend the partial assignment. case extend extSupported langSupported pkgPresent (S qsn) ppa newactives of Left (c, d) -> return (Fail c (Conflicting d)) -- inconsistency found Right nppa -> local (\ s -> s { pa = PA nppa pfa npsa }) r -- | We try to extract as many concrete dependencies from the given flagged -- dependencies as possible. We make use of all the flag knowledge we have -- already acquired. extractDeps :: FAssignment -> SAssignment -> FlaggedDeps comp QPN -> [Dep QPN] extractDeps fa sa deps = do d <- deps case d of Simple sd _ -> return sd Flagged qfn _ td fd -> case M.lookup qfn fa of Nothing -> mzero Just True -> extractDeps fa sa td Just False -> extractDeps fa sa fd Stanza qsn td -> case M.lookup qsn sa of Nothing -> mzero Just True -> extractDeps fa sa td Just False -> [] -- | We try to find new dependencies that become available due to the given -- flag or stanza choice. We therefore look for the choice in question, and then call -- 'extractDeps' for everything underneath. extractNewDeps :: Var QPN -> Bool -> FAssignment -> SAssignment -> FlaggedDeps comp QPN -> [Dep QPN] extractNewDeps v b fa sa = go where go :: FlaggedDeps comp QPN -> [Dep QPN] -- Type annotation necessary (polymorphic recursion) go deps = do d <- deps case d of Simple _ _ -> mzero Flagged qfn' _ td fd | v == F qfn' -> L.map (resetVar v) $ if b then extractDeps fa sa td else extractDeps fa sa fd | otherwise -> case M.lookup qfn' fa of Nothing -> mzero Just True -> go td Just False -> go fd Stanza qsn' td | v == S qsn' -> L.map (resetVar v) $ if b then extractDeps fa sa td else [] | otherwise -> case M.lookup qsn' sa of Nothing -> mzero Just True -> go td Just False -> [] -- | Interface. validateTree :: CompilerInfo -> Index -> PkgConfigDb -> Tree QGoalReason -> Tree QGoalReason validateTree cinfo idx pkgConfigDb t = runReader (validate t) VS { supportedExt = maybe (const True) -- if compiler has no list of extensions, we assume everything is supported (\ es -> let s = S.fromList es in \ x -> S.member x s) (compilerInfoExtensions cinfo) , supportedLang = maybe (const True) use list lookup because language list is small and no instance (compilerInfoLanguages cinfo) , presentPkgs = pkgConfigPkgIsPresent pkgConfigDb , index = idx , saved = M.empty , pa = PA M.empty M.empty M.empty , qualifyOptions = defaultQualifyOptions idx }
null
https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal/cabal-install/Distribution/Client/Dependency/Modular/Validate.hs
haskell
Validation of the tree. The task here is to make sure all constraints hold. After validation, any assignment returned by exploration of the tree should be a complete valid assignment, i.e., actually constitute a solution. In practice, most constraints are implication constraints (IF we have made a number of choices, THEN we also have to ensure that). We call constraints that for which the preconditions are fulfilled ACTIVE. We maintain a set of currently active constraints that we pass down the node. We aim at detecting inconsistent states as early as possible. active constraints. active constraints, we must check that they are consistent with the current state. a new active constraint, fixing the choice. If a test fails, we have detected an inconsistent state. We can disable the current subtree and do not have to traverse it any further. We need a good way to represent the current state, i.e., the current set of active constraints. Since the main situation where we have to every package, we store which versions are still allowed. If for any package, we have inconsistent active constraints, we can also stop. the choices we've already made, and add them to the active set. choices we've already made, and the constraints we already have. It currently seems as if we're implementing the weak variant. However, when used together with 'preferEasyGoalChoices', we will find an inconsistent state in the very next step. What do we do about flags? Like for packages, we store the flag choices we have already made. the new active constraints. To this end, we look up the constraints for the package the flag belongs to, and traverse its flagged dependencies. Wherever we find the flag in question, we start recording dependencies underneath as new active dependencies. If we encounter other flags, we check if we've chosen them already and either proceed or stop. | The state needed during validation. saved, scoped, dependencies Flag choices may occur repeatedly (because they can introduce new constraints in various places). However, subsequent choices must be consistent. We thereby collapse repeated flag choice nodes. obtain current flag-preassignment flag has already been assigned; collapse choice to the correct branch flag choice is new, follow both branches Optional stanza choices are very similar to flag choices. obtain current stanza-preassignment stanza choice has already been made; collapse choice to the correct branch stanza choice is new, follow both branches We don't need to do anything for goal choices or failure nodes. What to do for package nodes ... obtain current preassignment obtain the supported extensions obtain the supported languages obtain the present pkg-config pkgs obtain the index obtain saved dependencies obtain dependencies and index-dictated exclusions introduced by the choice qualify the deps in the current scope the new active constraints are given by the instance we have chosen, plus the dependency information we have for that instance We now try to extend the partial assignment with the new active constraints. In case we continue, we save the scoped dependencies The index marks this as an invalid choice. We can stop. We have an inconsistency. We can stop. We have an updated partial assignment for the recursive validation. What to do for flag nodes ... obtain current preassignment obtain the supported extensions obtain the supported languages obtain the present pkg-config pkgs obtain saved dependencies Note that there should be saved dependencies for the package in question, because while building, we do not choose flags before we see the packages that define them. We take the *saved* dependencies, because these have been qualified in the correct scope. Extend the flag assignment We now try to get the new active dependencies we might learn about because we have chosen a new flag. As in the package case, we try to extend the partial assignment. inconsistency found What to do for stanza nodes (similar to flag nodes) ... obtain current preassignment obtain the supported extensions obtain the supported languages obtain the present pkg-config pkgs obtain saved dependencies Note that there should be saved dependencies for the package in question, because while building, we do not choose flags before we see the packages that define them. We take the *saved* dependencies, because these have been qualified in the correct scope. Extend the flag assignment We now try to get the new active dependencies we might learn about because we have chosen a new flag. As in the package case, we try to extend the partial assignment. inconsistency found | We try to extract as many concrete dependencies from the given flagged dependencies as possible. We make use of all the flag knowledge we have already acquired. | We try to find new dependencies that become available due to the given flag or stanza choice. We therefore look for the choice in question, and then call 'extractDeps' for everything underneath. Type annotation necessary (polymorphic recursion) | Interface. if compiler has no list of extensions, we assume everything is supported
module Distribution.Client.Dependency.Modular.Validate (validateTree) where import Control.Applicative import Control.Monad.Reader hiding (sequence) import Data.List as L import Data.Map as M import Data.Set as S import Data.Traversable import Prelude hiding (sequence) import Language.Haskell.Extension (Extension, Language) import Distribution.Compiler (CompilerInfo(..)) import Distribution.Client.Dependency.Modular.Assignment import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Index import Distribution.Client.Dependency.Modular.Package import qualified Distribution.Client.Dependency.Modular.PSQ as P import Distribution.Client.Dependency.Modular.Tree import Distribution.Client.Dependency.Modular.Version (VR) import Distribution.Client.ComponentDeps (Component) import Distribution.Client.PkgConfigDb (PkgConfigDb, pkgConfigPkgIsPresent) Whenever we make a choice , there are two things that need to happen : ( 1 ) We must check that the choice is consistent with the currently ( 2 ) The choice increases the set of active constraints . For the new We can actually merge ( 1 ) and ( 2 ) by saying the the current choice is search in it is ( 1 ) , it seems best to store the state by package : for This is a particular way to read task ( 2 ): ( 2 , weak ) We only check if the new constraints are consistent with ( 2 , strong ) We check if the new constraints are consistent with the Now , regarding ( 1 ) , we only have to test whether we 've decided the current flag before . Regarding ( 2 ) , the interesting bit is in discovering data ValidateState = VS { supportedExt :: Extension -> Bool, supportedLang :: Language -> Bool, presentPkgs :: PN -> VR -> Bool, index :: Index, pa :: PreAssignment, qualifyOptions :: QualifyOptions } type Validate = Reader ValidateState validate :: Tree QGoalReason -> Validate (Tree QGoalReason) validate = cata go where go :: TreeF QGoalReason (Validate (Tree QGoalReason)) -> Validate (Tree QGoalReason) go (PChoiceF qpn gr ts) = PChoice qpn gr <$> sequence (P.mapWithKey (goP qpn) ts) go (FChoiceF qfn gr b m ts) = do case M.lookup qfn pfa of case P.lookup rb ts of Just t -> goF qfn rb t Nothing -> return $ Fail (varToConflictSet (F qfn)) (MalformedFlagChoice qfn) FChoice qfn gr b m <$> sequence (P.mapWithKey (goF qfn) ts) go (SChoiceF qsn gr b ts) = do case M.lookup qsn psa of case P.lookup rb ts of Just t -> goS qsn rb t Nothing -> return $ Fail (varToConflictSet (S qsn)) (MalformedStanzaChoice qsn) SChoice qsn gr b <$> sequence (P.mapWithKey (goS qsn) ts) go (GoalChoiceF ts) = GoalChoice <$> sequence ts go (DoneF rdm ) = pure (Done rdm) go (FailF c fr ) = pure (Fail c fr) goP :: QPN -> POption -> Validate (Tree QGoalReason) -> Validate (Tree QGoalReason) goP qpn@(Q _pp pn) (POption i _) r = do qo <- asks qualifyOptions let (PInfo deps _ mfr) = idx ! pn ! i let qdeps = qualifyDeps qo qpn deps let newactives = Dep qpn (Fixed i (P qpn)) : L.map (resetVar (P qpn)) (extractDeps pfa psa qdeps) let mnppa = extend extSupported langSupported pkgPresent (P qpn) ppa newactives let nsvd = M.insert qpn qdeps svd case mfr of return (Fail (varToConflictSet (P qpn)) fr) _ -> case mnppa of return (Fail c (Conflicting d)) local (\ s -> s { pa = PA nppa pfa psa, saved = nsvd }) r goF :: QFN -> Bool -> Validate (Tree QGoalReason) -> Validate (Tree QGoalReason) goF qfn@(FN (PI qpn _i) _f) b r = do let qdeps = svd ! qpn let npfa = M.insert qfn b pfa let newactives = extractNewDeps (F qfn) b npfa psa qdeps case extend extSupported langSupported pkgPresent (F qfn) ppa newactives of Right nppa -> local (\ s -> s { pa = PA nppa npfa psa }) r goS :: QSN -> Bool -> Validate (Tree QGoalReason) -> Validate (Tree QGoalReason) goS qsn@(SN (PI qpn _i) _f) b r = do let qdeps = svd ! qpn let npsa = M.insert qsn b psa let newactives = extractNewDeps (S qsn) b pfa npsa qdeps case extend extSupported langSupported pkgPresent (S qsn) ppa newactives of Right nppa -> local (\ s -> s { pa = PA nppa pfa npsa }) r extractDeps :: FAssignment -> SAssignment -> FlaggedDeps comp QPN -> [Dep QPN] extractDeps fa sa deps = do d <- deps case d of Simple sd _ -> return sd Flagged qfn _ td fd -> case M.lookup qfn fa of Nothing -> mzero Just True -> extractDeps fa sa td Just False -> extractDeps fa sa fd Stanza qsn td -> case M.lookup qsn sa of Nothing -> mzero Just True -> extractDeps fa sa td Just False -> [] extractNewDeps :: Var QPN -> Bool -> FAssignment -> SAssignment -> FlaggedDeps comp QPN -> [Dep QPN] extractNewDeps v b fa sa = go where go deps = do d <- deps case d of Simple _ _ -> mzero Flagged qfn' _ td fd | v == F qfn' -> L.map (resetVar v) $ if b then extractDeps fa sa td else extractDeps fa sa fd | otherwise -> case M.lookup qfn' fa of Nothing -> mzero Just True -> go td Just False -> go fd Stanza qsn' td | v == S qsn' -> L.map (resetVar v) $ if b then extractDeps fa sa td else [] | otherwise -> case M.lookup qsn' sa of Nothing -> mzero Just True -> go td Just False -> [] validateTree :: CompilerInfo -> Index -> PkgConfigDb -> Tree QGoalReason -> Tree QGoalReason validateTree cinfo idx pkgConfigDb t = runReader (validate t) VS { (\ es -> let s = S.fromList es in \ x -> S.member x s) (compilerInfoExtensions cinfo) , supportedLang = maybe (const True) use list lookup because language list is small and no instance (compilerInfoLanguages cinfo) , presentPkgs = pkgConfigPkgIsPresent pkgConfigDb , index = idx , saved = M.empty , pa = PA M.empty M.empty M.empty , qualifyOptions = defaultQualifyOptions idx }
d3df2fd36c12d1d02db6922fbfcfffb74beb84a5ff86d1c68289c18c5f390852
matterhorn-chat/matterhorn
Core.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveAnyClass #-} module Matterhorn.Types.Core ( Name(..) , ChannelListEntry(..) , ChannelListEntryType(..) , ChannelSelectMatch(..) , LinkTarget(..) , MessageId(..) , messageIdPostId , ChannelListGroupLabel(..) , channelListGroupNames , MessageSelectState(..) , HelpScreen(..) ) where import Prelude () import Matterhorn.Prelude import qualified Brick import Data.Hashable ( Hashable ) import qualified Data.Text as T import Data.UUID ( UUID ) import GHC.Generics ( Generic ) import Network.Mattermost.Types import Matterhorn.Types.RichText ( URL, TeamURLName ) -- | This 'Name' type is the type used in 'brick' to identify various -- parts of the interface. data Name = MessageInterfaceMessages Name -- ^ The rendering of messages for the specified message interface -- (by editor name) | MessageInput ChannelId -- ^ The message editor for the specified channel's main message -- interface | MessageInputPrompt Name -- ^ A wrapper name for reporting the extent of a message editor's -- prompt. The specified name is the name of the editor whose prompt -- extent is being reported. | ChannelListViewport TeamId -- ^ The name of the channel list viewport for the specified team. | HelpViewport -- ^ The name of the viewport for the help interface. | PostList -- ^ The tag for messages rendered in the post list window. | HelpContent HelpScreen -- ^ The cache key constructor for caching help screen content. | CompletionList Name -- ^ The name of the list of completion alternatives in the -- specified editor's autocomplete pop-up. | JoinChannelList TeamId ^ The name of the channel list in the " " window . | UrlList Name -- ^ The name of a URL listing for the specified message interface's -- editor name. | MessagePreviewViewport Name -- ^ The name of the message interface editor's preview area. | ThemeListSearchInput TeamId -- ^ The list of themes in the "/theme" window for the specified -- team. | UserListSearchInput TeamId -- ^ The editor name for the user search input in the specified -- team's user list window. | JoinChannelListSearchInput TeamId -- ^ The editor name for the search input in the specified team's " " window . | UserListSearchResults TeamId -- ^ The list name for the specified team's user list window search -- results. | ThemeListSearchResults TeamId -- ^ The list name for the specified team's theme list window search -- results. | ViewMessageArea TeamId -- ^ The viewport for the specified team's single-message view -- window. | ViewMessageReactionsArea TeamId -- ^ The viewport for the specified team's single-message view -- window's reaction tab. | ChannelSidebar TeamId -- ^ The cache key for the specified team's channel list viewport -- contents. | ChannelSelectInput TeamId -- ^ The editor name for the specified team's channel selection mode -- editor. | AttachmentList ChannelId -- ^ The name of the attachment list for the specified channel's -- message interface. | AttachmentFileBrowser ChannelId | ReactionEmojiList TeamId -- ^ The name of the list of emoji to choose from for reactions for -- the specified team. | ReactionEmojiListInput TeamId -- ^ The name of the search editor for the specified team's emoji -- search window. | TabbedWindowTabBar TeamId -- ^ The name of the specified team's tabbed window tab bar -- viewport. | MuteToggleField TeamId -- ^ The name of the channel preferences mute form field. | ChannelMentionsField TeamId -- ^ The name of the channel preferences mentions form field. | DesktopNotificationsField TeamId (WithDefault NotifyOption) -- ^ The name of the channel preferences desktop notifications form -- field. | PushNotificationsField TeamId (WithDefault NotifyOption) -- ^ The name of the channel preferences push notifications form -- field. | ChannelTopicEditor TeamId -- ^ The specified team's channel topic window editor. | ChannelTopicSaveButton TeamId -- ^ The specified team's channel topic window save button. | ChannelTopicCancelButton TeamId -- ^ The specified team's channel topic window canel button. | ChannelTopicEditorPreview TeamId -- ^ The specified team's channel topic window preview area -- viewport. | ThreadMessageInput ChannelId -- ^ The message editor for the specified channel's thread view. | ThreadEditorAttachmentList ChannelId -- ^ The list name for the specified channel's thread message -- interface's attachment list. | ChannelTopic ChannelId -- ^ The mouse click area tag for a rendered channel topic. | TeamList -- ^ The viewport name for the team list. | ClickableChannelSelectEntry ChannelSelectMatch -- ^ The name of a clickable channel select entry in the channel -- select match list. | ClickableChannelListEntry ChannelId -- ^ The name of a clickable entry in the channel list. | ClickableTeamListEntry TeamId -- ^ The name of a clickable entry in the team list. | ClickableURL (Maybe MessageId) Name Int LinkTarget ^ The name of a clickable URL rendered in RichText . If provided , -- the message ID is the ID of the message in which the URL appears. -- The integer is the URL index in the rich text block for unique -- identification. | ClickableReaction PostId Name Text (Set UserId) ^ The name of a clickable reaction rendered in RichText when it -- is part of a message. | ClickableAttachmentInMessage Name FileId -- ^ The name of a clickable attachment. | ClickableUsername (Maybe MessageId) Name Int Text ^ The name of a clickable username rendered in RichText . The -- message ID and integer sequence number uniquely identify the -- clickable region. | ClickableURLListEntry Int LinkTarget -- ^ The name of a clickable URL list entry. The integer is the list -- index. | ClickableChannelListGroupHeading ChannelListGroupLabel -- ^ The name of a clickable channel list group heading. | ClickableReactionEmojiListWindowEntry (Bool, T.Text) -- ^ The name of a clickable reaction emoji list entry. | AttachmentPathEditor Name -- ^ The name of the specified message interface's attachment -- browser path editor. | AttachmentPathSaveButton Name -- ^ The name of the specified message interface's attachment -- browser save button. | AttachmentPathCancelButton Name -- ^ The name of the specified message interface's attachment -- browser cancel button. | RenderedMessage MessageId -- ^ The cache key for the rendering of the specified message. | SelectedChannelListEntry TeamId -- ^ The name of the specified team's currently selected channel -- list entry, used to bring the entry into view in its viewport. | VScrollBar Brick.ClickableScrollbarElement Name -- ^ The name of the scroll bar elements for the specified viewport -- name. deriving (Eq, Show, Ord) -- | A match in channel selection mode. data ChannelSelectMatch = ChannelSelectMatch { nameBefore :: Text -- ^ The content of the match before the user's -- matching input. , nameMatched :: Text -- ^ The potion of the name that matched the -- user's input. , nameAfter :: Text -- ^ The portion of the name that came after the -- user's matching input. , matchFull :: Text -- ^ The full string for this entry so it doesn't -- have to be reassembled from the parts above. , matchEntry :: ChannelListEntry -- ^ The original entry data corresponding to the -- text match. } deriving (Eq, Show, Ord) -- | The type of channel list entries. data ChannelListEntry = ChannelListEntry { channelListEntryChannelId :: ChannelId , channelListEntryType :: ChannelListEntryType , channelListEntryUnread :: Bool , channelListEntrySortValue :: T.Text , channelListEntryFavorite :: Bool , channelListEntryMuted :: Bool } deriving (Eq, Show, Ord) data ChannelListEntryType = CLChannel ^ A non - DM entry | CLUserDM UserId ^ A single - user DM entry | CLGroupDM ^ A multi - user DM entry deriving (Eq, Show, Ord) | The ' HelpScreen ' type represents the set of possible ' Help ' screens -- we have to choose from. data HelpScreen = MainHelp | ScriptHelp | ThemeHelp | SyntaxHighlightHelp | KeybindingHelp deriving (Eq, Show, Ord) data LinkTarget = LinkURL URL | LinkFileId FileId | LinkPermalink TeamURLName PostId deriving (Eq, Show, Ord) data MessageId = MessagePostId PostId | MessageUUID UUID deriving (Eq, Read, Ord, Show, Generic, Hashable) messageIdPostId :: MessageId -> Maybe PostId messageIdPostId (MessagePostId p) = Just p messageIdPostId _ = Nothing data ChannelListGroupLabel = ChannelGroupPublicChannels | ChannelGroupPrivateChannels | ChannelGroupFavoriteChannels | ChannelGroupDirectMessages deriving (Eq, Ord, Show) channelListGroupNames :: [(T.Text, ChannelListGroupLabel)] channelListGroupNames = [ ("public", ChannelGroupPublicChannels) , ("private", ChannelGroupPrivateChannels) , ("favorite", ChannelGroupFavoriteChannels) , ("direct", ChannelGroupDirectMessages) ] -- | The state of message selection mode. data MessageSelectState = MessageSelectState { selectMessageId :: Maybe MessageId }
null
https://raw.githubusercontent.com/matterhorn-chat/matterhorn/19a73ce833a8a8de3616cf884c03e9f08a4db0a7/src/Matterhorn/Types/Core.hs
haskell
# LANGUAGE DeriveAnyClass # | This 'Name' type is the type used in 'brick' to identify various parts of the interface. ^ The rendering of messages for the specified message interface (by editor name) ^ The message editor for the specified channel's main message interface ^ A wrapper name for reporting the extent of a message editor's prompt. The specified name is the name of the editor whose prompt extent is being reported. ^ The name of the channel list viewport for the specified team. ^ The name of the viewport for the help interface. ^ The tag for messages rendered in the post list window. ^ The cache key constructor for caching help screen content. ^ The name of the list of completion alternatives in the specified editor's autocomplete pop-up. ^ The name of a URL listing for the specified message interface's editor name. ^ The name of the message interface editor's preview area. ^ The list of themes in the "/theme" window for the specified team. ^ The editor name for the user search input in the specified team's user list window. ^ The editor name for the search input in the specified team's ^ The list name for the specified team's user list window search results. ^ The list name for the specified team's theme list window search results. ^ The viewport for the specified team's single-message view window. ^ The viewport for the specified team's single-message view window's reaction tab. ^ The cache key for the specified team's channel list viewport contents. ^ The editor name for the specified team's channel selection mode editor. ^ The name of the attachment list for the specified channel's message interface. ^ The name of the list of emoji to choose from for reactions for the specified team. ^ The name of the search editor for the specified team's emoji search window. ^ The name of the specified team's tabbed window tab bar viewport. ^ The name of the channel preferences mute form field. ^ The name of the channel preferences mentions form field. ^ The name of the channel preferences desktop notifications form field. ^ The name of the channel preferences push notifications form field. ^ The specified team's channel topic window editor. ^ The specified team's channel topic window save button. ^ The specified team's channel topic window canel button. ^ The specified team's channel topic window preview area viewport. ^ The message editor for the specified channel's thread view. ^ The list name for the specified channel's thread message interface's attachment list. ^ The mouse click area tag for a rendered channel topic. ^ The viewport name for the team list. ^ The name of a clickable channel select entry in the channel select match list. ^ The name of a clickable entry in the channel list. ^ The name of a clickable entry in the team list. the message ID is the ID of the message in which the URL appears. The integer is the URL index in the rich text block for unique identification. is part of a message. ^ The name of a clickable attachment. message ID and integer sequence number uniquely identify the clickable region. ^ The name of a clickable URL list entry. The integer is the list index. ^ The name of a clickable channel list group heading. ^ The name of a clickable reaction emoji list entry. ^ The name of the specified message interface's attachment browser path editor. ^ The name of the specified message interface's attachment browser save button. ^ The name of the specified message interface's attachment browser cancel button. ^ The cache key for the rendering of the specified message. ^ The name of the specified team's currently selected channel list entry, used to bring the entry into view in its viewport. ^ The name of the scroll bar elements for the specified viewport name. | A match in channel selection mode. ^ The content of the match before the user's matching input. ^ The potion of the name that matched the user's input. ^ The portion of the name that came after the user's matching input. ^ The full string for this entry so it doesn't have to be reassembled from the parts above. ^ The original entry data corresponding to the text match. | The type of channel list entries. we have to choose from. | The state of message selection mode.
# LANGUAGE DeriveGeneric # module Matterhorn.Types.Core ( Name(..) , ChannelListEntry(..) , ChannelListEntryType(..) , ChannelSelectMatch(..) , LinkTarget(..) , MessageId(..) , messageIdPostId , ChannelListGroupLabel(..) , channelListGroupNames , MessageSelectState(..) , HelpScreen(..) ) where import Prelude () import Matterhorn.Prelude import qualified Brick import Data.Hashable ( Hashable ) import qualified Data.Text as T import Data.UUID ( UUID ) import GHC.Generics ( Generic ) import Network.Mattermost.Types import Matterhorn.Types.RichText ( URL, TeamURLName ) data Name = MessageInterfaceMessages Name | MessageInput ChannelId | MessageInputPrompt Name | ChannelListViewport TeamId | HelpViewport | PostList | HelpContent HelpScreen | CompletionList Name | JoinChannelList TeamId ^ The name of the channel list in the " " window . | UrlList Name | MessagePreviewViewport Name | ThemeListSearchInput TeamId | UserListSearchInput TeamId | JoinChannelListSearchInput TeamId " " window . | UserListSearchResults TeamId | ThemeListSearchResults TeamId | ViewMessageArea TeamId | ViewMessageReactionsArea TeamId | ChannelSidebar TeamId | ChannelSelectInput TeamId | AttachmentList ChannelId | AttachmentFileBrowser ChannelId | ReactionEmojiList TeamId | ReactionEmojiListInput TeamId | TabbedWindowTabBar TeamId | MuteToggleField TeamId | ChannelMentionsField TeamId | DesktopNotificationsField TeamId (WithDefault NotifyOption) | PushNotificationsField TeamId (WithDefault NotifyOption) | ChannelTopicEditor TeamId | ChannelTopicSaveButton TeamId | ChannelTopicCancelButton TeamId | ChannelTopicEditorPreview TeamId | ThreadMessageInput ChannelId | ThreadEditorAttachmentList ChannelId | ChannelTopic ChannelId | TeamList | ClickableChannelSelectEntry ChannelSelectMatch | ClickableChannelListEntry ChannelId | ClickableTeamListEntry TeamId | ClickableURL (Maybe MessageId) Name Int LinkTarget ^ The name of a clickable URL rendered in RichText . If provided , | ClickableReaction PostId Name Text (Set UserId) ^ The name of a clickable reaction rendered in RichText when it | ClickableAttachmentInMessage Name FileId | ClickableUsername (Maybe MessageId) Name Int Text ^ The name of a clickable username rendered in RichText . The | ClickableURLListEntry Int LinkTarget | ClickableChannelListGroupHeading ChannelListGroupLabel | ClickableReactionEmojiListWindowEntry (Bool, T.Text) | AttachmentPathEditor Name | AttachmentPathSaveButton Name | AttachmentPathCancelButton Name | RenderedMessage MessageId | SelectedChannelListEntry TeamId | VScrollBar Brick.ClickableScrollbarElement Name deriving (Eq, Show, Ord) data ChannelSelectMatch = ChannelSelectMatch { nameBefore :: Text , nameMatched :: Text , nameAfter :: Text , matchFull :: Text , matchEntry :: ChannelListEntry } deriving (Eq, Show, Ord) data ChannelListEntry = ChannelListEntry { channelListEntryChannelId :: ChannelId , channelListEntryType :: ChannelListEntryType , channelListEntryUnread :: Bool , channelListEntrySortValue :: T.Text , channelListEntryFavorite :: Bool , channelListEntryMuted :: Bool } deriving (Eq, Show, Ord) data ChannelListEntryType = CLChannel ^ A non - DM entry | CLUserDM UserId ^ A single - user DM entry | CLGroupDM ^ A multi - user DM entry deriving (Eq, Show, Ord) | The ' HelpScreen ' type represents the set of possible ' Help ' screens data HelpScreen = MainHelp | ScriptHelp | ThemeHelp | SyntaxHighlightHelp | KeybindingHelp deriving (Eq, Show, Ord) data LinkTarget = LinkURL URL | LinkFileId FileId | LinkPermalink TeamURLName PostId deriving (Eq, Show, Ord) data MessageId = MessagePostId PostId | MessageUUID UUID deriving (Eq, Read, Ord, Show, Generic, Hashable) messageIdPostId :: MessageId -> Maybe PostId messageIdPostId (MessagePostId p) = Just p messageIdPostId _ = Nothing data ChannelListGroupLabel = ChannelGroupPublicChannels | ChannelGroupPrivateChannels | ChannelGroupFavoriteChannels | ChannelGroupDirectMessages deriving (Eq, Ord, Show) channelListGroupNames :: [(T.Text, ChannelListGroupLabel)] channelListGroupNames = [ ("public", ChannelGroupPublicChannels) , ("private", ChannelGroupPrivateChannels) , ("favorite", ChannelGroupFavoriteChannels) , ("direct", ChannelGroupDirectMessages) ] data MessageSelectState = MessageSelectState { selectMessageId :: Maybe MessageId }
b6336ca9ac64daa139cdcb792063d9877a0521c0c6ebd685a57a8d57b98d3f71
startalkIM/ejabberd
p1_prof.erl
%%%------------------------------------------------------------------- %%% File : p1_prof.erl Author : < > Description : Handy wrapper around eprof and %%% Created : 23 Jan 2010 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2019 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . %%% %%%------------------------------------------------------------------- -module(p1_prof). %% API -export([eprof_start/0, eprof_stop/0, eprof_start/1, fprof_apply/3, fprof_start/0, fprof_start/1, fprof_stop/0, fprof_analyze/0, queue/0, queue/1, memory/0, memory/1, reds/0, reds/1, trace/1, help/0, q/0, m/0, r/0, q/1, m/1, r/1, locks/0, locks/1]). -define(TRACE_FILE, "/tmp/fprof.trace"). -define(ANALYSIS_FILE, "/tmp/fprof.analysis"). %%==================================================================== %% API %%==================================================================== eprof_start() -> eprof_start(get_procs()). eprof_start(Duration) when is_integer(Duration) -> eprof_start(get_procs()), timer:sleep(timer:seconds(Duration)), eprof_stop(); eprof_start([]) -> {error, no_procs_found}; eprof_start(Procs) -> eprof:start(), eprof:start_profiling(Procs). fprof_apply(M, F, A) -> fprof:apply(M, F, A, [{file, ?TRACE_FILE}]), fprof_analyze(). fprof_start() -> fprof_start(0). fprof_start(Duration) -> case get_procs() of [] -> {error, no_procs_found}; Procs -> case fprof:trace([start, {procs, Procs}, {file, ?TRACE_FILE}]) of ok -> io:format("Profiling started, writing trace data to ~s~n", [?TRACE_FILE]), if Duration > 0 -> timer:sleep(Duration*1000), fprof:trace([stop]), fprof:stop(); true-> ok end; Err -> io:format("Couldn't start profiling: ~p~n", [Err]), Err end end. fprof_stop() -> fprof:trace([stop]), case fprof:profile([{file, ?TRACE_FILE}]) of ok -> case fprof:analyse([totals, no_details, {sort, own}, no_callers, {dest, ?ANALYSIS_FILE}]) of ok -> fprof:stop(), format_fprof_analyze(); Err -> io:format("Couldn't analyze: ~p~n", [Err]), Err end; Err -> io:format("Couldn't compile a trace into profile data: ~p~n", [Err]), Err end. fprof_analyze() -> fprof_stop(). eprof_stop() -> eprof:stop_profiling(), eprof:analyze(total). help() -> M = ?MODULE, io:format("Brief help:~n" "~p:queue(N) - show top N pids sorted by queue length~n" "~p:queue() - shorthand for ~p:queue(10)~n" "~p:memory(N) - show top N pids sorted by memory usage~n" "~p:memory() - shorthand for ~p:memory(10)~n" "~p:reds(N) - show top N pids sorted by reductions~n" "~p:reds() - shorthand for ~p:reds(10)~n" "~p:q(N)|~p:q() - same as ~p:queue(N)|~p:queue()~n" "~p:m(N)|~p:m() - same as ~p:memory(N)|~p:memory()~n" "~p:r(N)|~p:r() - same as ~p:reds(N)|~p:reds()~n" "~p:trace(Pid) - trace Pid; to stop tracing close " "Erlang shell with Ctrl+C~n" "~p:eprof_start() - start eprof on all available pids; " "DO NOT use on production system!~n" "~p:eprof_stop() - stop eprof and print result~n" "~p:fprof_start() - start fprof on all available pids; " "DO NOT use on production system!~n" "~p:fprof_stop() - stop eprof and print formatted result~n" "~p:fprof_start(N) - start and run fprof for N seconds; " "use ~p:fprof_analyze() to analyze collected statistics and " "print formatted result; use on production system with CARE~n" "~p:fprof_analyze() - analyze previously collected statistics " "using ~p:fprof_start(N) and print formatted result~n" "~p:help() - print this help~n", lists:duplicate(31, M)). q() -> queue(). q(N) -> queue(N). m() -> memory(). m(N) -> memory(N). r() -> reds(). r(N) -> reds(N). queue() -> queue(10). memory() -> memory(10). reds() -> reds(10). queue(N) -> dump(N, lists:reverse(lists:ukeysort(1, all_pids(queue)))). memory(N) -> dump(N, lists:reverse(lists:ukeysort(3, all_pids(memory)))). reds(N) -> dump(N, lists:reverse(lists:ukeysort(4, all_pids(reductions)))). trace(Pid) -> erlang:trace(Pid, true, [send, 'receive']), trace_loop(). trace_loop() -> receive M -> io:format("~p~n", [M]), trace_loop() end. %%==================================================================== Internal functions %%==================================================================== get_procs() -> processes(). format_fprof_analyze() -> case file:consult(?ANALYSIS_FILE) of {ok, [_, [{totals, _, _, TotalOWN}] | Rest]} -> OWNs = lists:flatmap( fun({MFA, _, _, OWN}) -> Percent = OWN*100/TotalOWN, case round(Percent) of 0 -> []; _ -> [{mfa_to_list(MFA), Percent}] end end, Rest), ACCs = collect_accs(Rest), MaxACC = find_max(ACCs), MaxOWN = find_max(OWNs), io:format("=== Sorted by OWN:~n"), lists:foreach( fun({MFA, Per}) -> L = length(MFA), S = lists:duplicate(MaxOWN - L + 2, $ ), io:format("~s~s~.2f%~n", [MFA, S, Per]) end, lists:reverse(lists:keysort(2, OWNs))), io:format("~n=== Sorted by ACC:~n"), lists:foreach( fun({MFA, Per}) -> L = length(MFA), S = lists:duplicate(MaxACC - L + 2, $ ), io:format("~s~s~.2f%~n", [MFA, S, Per]) end, lists:reverse(lists:keysort(2, ACCs))); Err -> Err end. mfa_to_list({M, F, A}) -> atom_to_list(M) ++ ":" ++ atom_to_list(F) ++ "/" ++ integer_to_list(A); mfa_to_list(F) when is_atom(F) -> atom_to_list(F). find_max(List) -> find_max(List, 0). find_max([{V, _}|Tail], Acc) -> find_max(Tail, lists:max([length(V), Acc])); find_max([], Acc) -> Acc. collect_accs(List) -> List1 = lists:filter( fun({MFA, _, _, _}) -> case MFA of {sys, _, _} -> false; suspend -> false; {gen_fsm, _, _} -> false; {p1_fsm, _, _} -> false; {gen, _, _} -> false; {gen_server, _, _} -> false; {proc_lib, _, _} -> false; _ -> true end end, List), TotalACC = lists:sum([A || {_, _, A, _} <- List1]), lists:flatmap( fun({MFA, _, ACC, _}) -> Percent = ACC*100/TotalACC, case round(Percent) of 0 -> []; _ -> [{mfa_to_list(MFA), Percent}] end end, List1). all_pids(Type) -> lists:foldl( fun(P, Acc) when P == self() -> %% exclude ourself from statistics Acc; (P, Acc) -> case catch process_info( P, [message_queue_len, memory, reductions, dictionary, current_function, registered_name]) of [{_, Len}, {_, Memory}, {_, Reds}, {_, Dict}, {_, CurFun}, {_, RegName}] -> IntQLen = case lists:keysearch('$internal_queue_len', 1, Dict) of {value, {_, N}} -> N; _ -> 0 end, if Type == queue andalso Len == 0 andalso IntQLen == 0 -> Acc; true -> MaxLen = lists:max([Len, IntQLen]), [{MaxLen, Len, Memory, Reds, Dict, CurFun, P, RegName}|Acc] end; _ -> Acc end end, [], processes()). dump(N, Rs) -> lists:foreach( fun({_, MsgQLen, Memory, Reds, Dict, CurFun, Pid, RegName}) -> PidStr = pid_to_list(Pid), [_, Maj, Min] = string:tokens( string:substr( PidStr, 2, length(PidStr) - 2), "."), io:format("** pid(0,~s,~s)~n" "** registered name: ~p~n" "** memory: ~p~n" "** reductions: ~p~n" "** message queue len: ~p~n" "** current_function: ~p~n" "** dictionary: ~p~n~n", [Maj, Min, RegName, Memory, Reds, MsgQLen, CurFun, Dict]) end, nthhead(N, Rs)). nthhead(N, L) -> lists:reverse(nthhead(N, L, [])). nthhead(0, _L, Acc) -> Acc; nthhead(N, [H|T], Acc) -> nthhead(N-1, T, [H|Acc]); nthhead(_N, [], Acc) -> Acc. output in the console counts of locks , optionally waiting for few seconds before collect locks() -> locks(5). locks(Time) -> lcnt:rt_opt({copy_save, true}), lcnt:start(), lcnt:clear(), timer:sleep(Time*1000), lcnt:collect(), lcnt:conflicts(), lcnt:stop(), lcnt:rt_opt({copy_save, false}), ok.
null
https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/deps/p1_utils/src/p1_prof.erl
erlang
------------------------------------------------------------------- File : p1_prof.erl This program is free software; you can redistribute it and/or License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------- API ==================================================================== API ==================================================================== ==================================================================== ==================================================================== exclude ourself from statistics
Author : < > Description : Handy wrapper around eprof and Created : 23 Jan 2010 by < > ejabberd , Copyright ( C ) 2002 - 2019 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . -module(p1_prof). -export([eprof_start/0, eprof_stop/0, eprof_start/1, fprof_apply/3, fprof_start/0, fprof_start/1, fprof_stop/0, fprof_analyze/0, queue/0, queue/1, memory/0, memory/1, reds/0, reds/1, trace/1, help/0, q/0, m/0, r/0, q/1, m/1, r/1, locks/0, locks/1]). -define(TRACE_FILE, "/tmp/fprof.trace"). -define(ANALYSIS_FILE, "/tmp/fprof.analysis"). eprof_start() -> eprof_start(get_procs()). eprof_start(Duration) when is_integer(Duration) -> eprof_start(get_procs()), timer:sleep(timer:seconds(Duration)), eprof_stop(); eprof_start([]) -> {error, no_procs_found}; eprof_start(Procs) -> eprof:start(), eprof:start_profiling(Procs). fprof_apply(M, F, A) -> fprof:apply(M, F, A, [{file, ?TRACE_FILE}]), fprof_analyze(). fprof_start() -> fprof_start(0). fprof_start(Duration) -> case get_procs() of [] -> {error, no_procs_found}; Procs -> case fprof:trace([start, {procs, Procs}, {file, ?TRACE_FILE}]) of ok -> io:format("Profiling started, writing trace data to ~s~n", [?TRACE_FILE]), if Duration > 0 -> timer:sleep(Duration*1000), fprof:trace([stop]), fprof:stop(); true-> ok end; Err -> io:format("Couldn't start profiling: ~p~n", [Err]), Err end end. fprof_stop() -> fprof:trace([stop]), case fprof:profile([{file, ?TRACE_FILE}]) of ok -> case fprof:analyse([totals, no_details, {sort, own}, no_callers, {dest, ?ANALYSIS_FILE}]) of ok -> fprof:stop(), format_fprof_analyze(); Err -> io:format("Couldn't analyze: ~p~n", [Err]), Err end; Err -> io:format("Couldn't compile a trace into profile data: ~p~n", [Err]), Err end. fprof_analyze() -> fprof_stop(). eprof_stop() -> eprof:stop_profiling(), eprof:analyze(total). help() -> M = ?MODULE, io:format("Brief help:~n" "~p:queue(N) - show top N pids sorted by queue length~n" "~p:queue() - shorthand for ~p:queue(10)~n" "~p:memory(N) - show top N pids sorted by memory usage~n" "~p:memory() - shorthand for ~p:memory(10)~n" "~p:reds(N) - show top N pids sorted by reductions~n" "~p:reds() - shorthand for ~p:reds(10)~n" "~p:q(N)|~p:q() - same as ~p:queue(N)|~p:queue()~n" "~p:m(N)|~p:m() - same as ~p:memory(N)|~p:memory()~n" "~p:r(N)|~p:r() - same as ~p:reds(N)|~p:reds()~n" "~p:trace(Pid) - trace Pid; to stop tracing close " "Erlang shell with Ctrl+C~n" "~p:eprof_start() - start eprof on all available pids; " "DO NOT use on production system!~n" "~p:eprof_stop() - stop eprof and print result~n" "~p:fprof_start() - start fprof on all available pids; " "DO NOT use on production system!~n" "~p:fprof_stop() - stop eprof and print formatted result~n" "~p:fprof_start(N) - start and run fprof for N seconds; " "use ~p:fprof_analyze() to analyze collected statistics and " "print formatted result; use on production system with CARE~n" "~p:fprof_analyze() - analyze previously collected statistics " "using ~p:fprof_start(N) and print formatted result~n" "~p:help() - print this help~n", lists:duplicate(31, M)). q() -> queue(). q(N) -> queue(N). m() -> memory(). m(N) -> memory(N). r() -> reds(). r(N) -> reds(N). queue() -> queue(10). memory() -> memory(10). reds() -> reds(10). queue(N) -> dump(N, lists:reverse(lists:ukeysort(1, all_pids(queue)))). memory(N) -> dump(N, lists:reverse(lists:ukeysort(3, all_pids(memory)))). reds(N) -> dump(N, lists:reverse(lists:ukeysort(4, all_pids(reductions)))). trace(Pid) -> erlang:trace(Pid, true, [send, 'receive']), trace_loop(). trace_loop() -> receive M -> io:format("~p~n", [M]), trace_loop() end. Internal functions get_procs() -> processes(). format_fprof_analyze() -> case file:consult(?ANALYSIS_FILE) of {ok, [_, [{totals, _, _, TotalOWN}] | Rest]} -> OWNs = lists:flatmap( fun({MFA, _, _, OWN}) -> Percent = OWN*100/TotalOWN, case round(Percent) of 0 -> []; _ -> [{mfa_to_list(MFA), Percent}] end end, Rest), ACCs = collect_accs(Rest), MaxACC = find_max(ACCs), MaxOWN = find_max(OWNs), io:format("=== Sorted by OWN:~n"), lists:foreach( fun({MFA, Per}) -> L = length(MFA), S = lists:duplicate(MaxOWN - L + 2, $ ), io:format("~s~s~.2f%~n", [MFA, S, Per]) end, lists:reverse(lists:keysort(2, OWNs))), io:format("~n=== Sorted by ACC:~n"), lists:foreach( fun({MFA, Per}) -> L = length(MFA), S = lists:duplicate(MaxACC - L + 2, $ ), io:format("~s~s~.2f%~n", [MFA, S, Per]) end, lists:reverse(lists:keysort(2, ACCs))); Err -> Err end. mfa_to_list({M, F, A}) -> atom_to_list(M) ++ ":" ++ atom_to_list(F) ++ "/" ++ integer_to_list(A); mfa_to_list(F) when is_atom(F) -> atom_to_list(F). find_max(List) -> find_max(List, 0). find_max([{V, _}|Tail], Acc) -> find_max(Tail, lists:max([length(V), Acc])); find_max([], Acc) -> Acc. collect_accs(List) -> List1 = lists:filter( fun({MFA, _, _, _}) -> case MFA of {sys, _, _} -> false; suspend -> false; {gen_fsm, _, _} -> false; {p1_fsm, _, _} -> false; {gen, _, _} -> false; {gen_server, _, _} -> false; {proc_lib, _, _} -> false; _ -> true end end, List), TotalACC = lists:sum([A || {_, _, A, _} <- List1]), lists:flatmap( fun({MFA, _, ACC, _}) -> Percent = ACC*100/TotalACC, case round(Percent) of 0 -> []; _ -> [{mfa_to_list(MFA), Percent}] end end, List1). all_pids(Type) -> lists:foldl( fun(P, Acc) when P == self() -> Acc; (P, Acc) -> case catch process_info( P, [message_queue_len, memory, reductions, dictionary, current_function, registered_name]) of [{_, Len}, {_, Memory}, {_, Reds}, {_, Dict}, {_, CurFun}, {_, RegName}] -> IntQLen = case lists:keysearch('$internal_queue_len', 1, Dict) of {value, {_, N}} -> N; _ -> 0 end, if Type == queue andalso Len == 0 andalso IntQLen == 0 -> Acc; true -> MaxLen = lists:max([Len, IntQLen]), [{MaxLen, Len, Memory, Reds, Dict, CurFun, P, RegName}|Acc] end; _ -> Acc end end, [], processes()). dump(N, Rs) -> lists:foreach( fun({_, MsgQLen, Memory, Reds, Dict, CurFun, Pid, RegName}) -> PidStr = pid_to_list(Pid), [_, Maj, Min] = string:tokens( string:substr( PidStr, 2, length(PidStr) - 2), "."), io:format("** pid(0,~s,~s)~n" "** registered name: ~p~n" "** memory: ~p~n" "** reductions: ~p~n" "** message queue len: ~p~n" "** current_function: ~p~n" "** dictionary: ~p~n~n", [Maj, Min, RegName, Memory, Reds, MsgQLen, CurFun, Dict]) end, nthhead(N, Rs)). nthhead(N, L) -> lists:reverse(nthhead(N, L, [])). nthhead(0, _L, Acc) -> Acc; nthhead(N, [H|T], Acc) -> nthhead(N-1, T, [H|Acc]); nthhead(_N, [], Acc) -> Acc. output in the console counts of locks , optionally waiting for few seconds before collect locks() -> locks(5). locks(Time) -> lcnt:rt_opt({copy_save, true}), lcnt:start(), lcnt:clear(), timer:sleep(Time*1000), lcnt:collect(), lcnt:conflicts(), lcnt:stop(), lcnt:rt_opt({copy_save, false}), ok.
5e4737b103d17903e3e44e49b4a3ffde614c6b58f1c929588eb9f74d6e7c19eb
dym/movitz
conditions.lisp
;;;;------------------------------------------------------------------ ;;;; Copyright ( C ) 2001 - 2005 , Department of Computer Science , University of Tromso , Norway . ;;;; ;;;; For distribution policy, see the accompanying file COPYING. ;;;; ;;;; Filename: conditions.lisp ;;;; Description: Author : < > ;;;; Created at: Wed Nov 20 15:47:04 2002 ;;;; $ I d : conditions.lisp , v 1.29 2009 - 07 - 19 18:54:32 ffjeld Exp $ ;;;; ;;;;------------------------------------------------------------------ (require :muerte/basic-macros) (provide :muerte/conditions) (in-package muerte) (defparameter *break-on-signals* nil) (defparameter *debugger-function* nil) (defvar *debugger-dynamic-context* nil) (defparameter *debugger-invoked-stack-frame* nil) (defvar *debugger-condition*) (defmacro define-condition (name parent-types slot-specs &rest options) `(progn (defclass ,name ,(or parent-types '(condition)) ,slot-specs (:metaclass read-only-class)) ,@(let ((reporter (cadr (assoc :report options)))) (when reporter `((defmethod print-object ((condition ,name) stream) (if *print-escape* (call-next-method) (funcall (function ,reporter) condition stream)) condition)))) ',name)) (define-condition condition (standard-object) ((format-control :initarg :format-control :initform nil :reader condition-format-control) (format-arguments :initarg :format-arguments :initform nil :reader condition-format-arguments)) (:report (lambda (condition stream) (if (or *print-escape* (not (condition-format-control condition))) (call-next-method) (apply #'format stream (condition-format-control condition) (condition-format-arguments condition)))))) (define-condition simple-condition (condition) ((format-control :reader simple-condition-format-control) (format-arguments :reader simple-condition-format-arguments))) (define-condition serious-condition () ()) (define-condition error (serious-condition) ()) (define-condition storage-condition (serious-condition) ()) (define-condition warning () ()) (define-condition style-warning () ()) (define-condition simple-error (simple-condition error) ()) (define-condition simple-warning (simple-condition warning) ()) (define-condition parse-error (error) ()) (define-condition cell-error (error) ((name :initarg :name :reader cell-error-name)) (:report (lambda (c s) (format s "Error accessing cell ~S." (cell-error-name c))))) (define-condition undefined-function (cell-error) () (:report (lambda (c s) (format s "Undefined function ~S." (cell-error-name c))))) (define-condition undefined-function-call (undefined-function) ((arguments :initarg :arguments :reader undefined-function-call-arguments)) (:report (lambda (c s) (format s "Undefined function ~S called with arguments ~:S." (cell-error-name c) (undefined-function-call-arguments c))))) (define-condition unbound-variable (cell-error) () (:report (lambda (c s) (format s "Unbound variable ~S." (cell-error-name c))))) (define-condition unbound-slot (cell-error) ((instance :initarg :instance :reader unbound-slot-instance)) (:report (lambda (c s) (format s "The slot ~S is unbound in the object ~S." (cell-error-name c) (unbound-slot-instance c))))) (define-condition print-not-readable (error) ((object :initarg :object :reader print-not-readable-object)) (:report (lambda (c s) (format s "Cannot print ~S readably." (print-not-readable-object c))))) (define-condition program-error (error) ()) (defun simple-program-error (format-control &rest format-arguments) (error 'program-error :format-control format-control :format-argumetns format-arguments)) (define-condition type-error (error) ((expected-type :initarg :expected-type :reader type-error-expected-type) (datum :initarg :datum :reader type-error-datum)) (:report (lambda (c s) (format s "The object ~Z `~S' is not of type ~S." (type-error-datum c) (type-error-datum c) (type-error-expected-type c))))) (define-condition simple-type-error (simple-condition type-error) ()) (define-condition etypecase-error (type-error) () (:report (lambda (c s) (format s "The object '~S' fell through an etypecase where the legal types were ~S." (type-error-datum c) (type-error-expected-type c))))) (defun etypecase-error (datum expecteds) (error 'etypecase-error :datum datum :expected-type (cons 'or expecteds))) (define-condition ecase-error (type-error) () (:report (lambda (c s) (format s "The object '~S' fell through an ecase where the legal cases were ~S." (type-error-datum c) (type-error-expected-type c))))) (defun ecase-error (datum expecteds) (error 'ecase-error :datum datum :expected-type (cons 'member expecteds))) (define-condition control-error (error) ()) (define-condition throw-error (control-error) ((tag :initarg :tag :reader throw-error-tag)) (:report (lambda (c s) (format s "Cannot throw to tag `~S'." (throw-error-tag c))))) (define-condition wrong-argument-count (program-error) ((function :initarg :function :reader condition-function) (argument-count :initarg :argument-count :reader condition-argument-count)) (:report (lambda (c s) (format s "Function ~S ~:A received ~:[an incorrect number of~;~:*~D~] arguments." (funobj-name (condition-function c)) (funobj-lambda-list (condition-function c)) (condition-argument-count c))))) (define-condition index-out-of-range (error) ((index :initarg :index :reader condition-index) (range :initarg :range :reader condition-range)) (:report (lambda (c s) (format s "Index ~D is beyond range 0-~D." (condition-index c) (condition-range c))))) (define-condition stream-error (error) ((stream :initarg :stream :reader stream-error-stream))) (define-condition reader-error (parse-error stream-error) ()) (define-condition end-of-file (stream-error) () (:report (lambda (c s) (format s "End of file encountered on ~W." (stream-error-stream c))))) (define-condition arithmetic-error (error) ((operation :initarg :operation :initform nil :reader arithmetic-error-operation) (operands :initarg :operands :initform nil :reader arithmetic-error-operands))) (define-condition division-by-zero (arithmetic-error) () (:report (lambda (c s) (declare (ignore c)) (format s "Division by zero.")))) (define-condition package-error (error) ((package :initarg :package :initform nil :reader package-error-package))) (define-condition file-error (error) ((pathname :initarg :pathname :initform nil :reader file-error-pathname))) (defun make-condition (type &rest slot-initializations) (declare (dynamic-extent slot-initializations)) (apply 'make-instance type slot-initializations)) (defun warn (datum &rest arguments) (declare (dynamic-extent arguments)) (cond ((not (eq t (get 'clos-bootstrap 'have-bootstrapped))) (fresh-line) (write-string "Warning: ") (apply 'format t datum arguments) (fresh-line)) (t (with-simple-restart (muffle-warning "Muffle warning.") (let ((c (signal-simple 'simple-warning datum arguments)) (*standard-output* *error-output*)) (typecase datum (string (fresh-line) (write-string "Warning: ") (apply 'format t datum arguments) (terpri)) (t (format t "~&Warning: ~A" (or c (coerce-to-condition 'simple-warning datum arguments))))))))) nil) (defun coerce-to-condition (default-type datum args) ;; (declare (dynamic-extent args)) (etypecase datum (condition datum) (symbol (apply 'make-condition datum args)) (string (make-condition default-type :format-control datum :format-arguments (copy-list args))))) (defun signal-simple (default-type datum args) "Signal the condition denoted by a condition designator. Will only make-instance a condition when it is required. Return the condition object, if there was one." (let* ((class (etypecase datum (symbol (or (find-class datum nil) (error "No condition class named ~S." datum))) (string (find-class default-type)) (condition (class-of datum)))) (cpl (class-precedence-list class)) (condition nil) (bos-type *break-on-signals*)) (with-simple-restart (continue "Ignore *break-on-signals*.") (let ((*break-on-signals* nil)) ; avoid recursive error if *b-o-s* is faulty. (when (typecase bos-type (null nil) (symbol (let ((bos-class (find-class bos-type nil))) (if (not bos-class) (typep (class-prototype-value class) bos-type) (member bos-class cpl)))) (list (typep (class-prototype-value class) bos-type)) (t (member bos-type cpl))) (break "Signalling ~S" datum)))) (macrolet ((invoke-handler (handler) `(funcall ,handler (or condition (setf condition (coerce-to-condition default-type datum args)))))) (let ((*active-condition-handlers* *active-condition-handlers*)) (do () ((null *active-condition-handlers*)) (let ((handlers (pop *active-condition-handlers*))) (dolist (handler handlers) (let ((handler-type (car handler))) (typecase handler-type (symbol (let ((handler-class (find-class handler-type nil))) (when (if (not handler-class) (typep (class-prototype-value class) handler-type) (progn (setf (car handler) handler-class) ; XXX memoize this find-class.. (member handler-class cpl))) (invoke-handler (cdr handler))))) (cons (when (typep (class-prototype-value class) handler-type) (invoke-handler (cdr handler)))) (null) (t (when (member handler-type cpl) (invoke-handler (cdr handler))))))))))) (or condition (when (typep datum condition) datum)))) (defun signal (datum &rest args) (declare (dynamic-extent args)) (signal-simple 'simple-condition datum args) nil) (defun invoke-debugger (condition) (when *debugger-hook* (let ((hook *debugger-hook*) (*debugger-hook* nil)) (funcall hook condition hook))) #+ignore (unless *debugger-function* (setf *debugger-function* #'muerte.init::my-debugger)) (cond ((not *debugger-function*) (let ((*never-use-print-object* t)) (backtrace :spartan t :conflate nil)) (format t "~&No debugger in *debugger-function*...") (dotimes (i 100000) (write-string "")) (format t "Trying to continue or abort.") (invoke-restart (or (find-restart 'continue) (find-restart 'abort) (format t "~%Condition for debugger: ~Z" condition) (format t "~%No abort restart is active. Halting CPU.") (halt-cpu)))) (t (let ((*debugger-invoked-stack-frame* (stack-frame-uplink nil (current-stack-frame)))) (funcall *debugger-function* condition)))) (format *debug-io* "~&Debugger ~@[on ~S ]returned!~%Trying to abort...~%" condition) (let ((r (find-restart 'abort))) (when r (invoke-restart r)) (format *debug-io* "~&Aborting failed. Halting CPU.") (halt-cpu))) (defun invoke-debugger-on-designator (&rest designator) (declare (dynamic-extent designator)) (if (or (eq 'break (car designator)) (and *error-no-condition-for-debugger* (symbolp (car designator))) do n't let an error trigger CLOS bootstrapping . (not (eq t (get 'clos-bootstrap 'have-bootstrapped)))) (invoke-debugger designator) (invoke-debugger (coerce-to-condition (car designator) (cadr designator) (cddr designator))))) (defun break (&optional format-control &rest format-arguments) (declare (dynamic-extent format-arguments)) (with-simple-restart (continue "Return from break~:[.~;~:*: ~?~]" format-control format-arguments) ;; (format *debug-io* "~&Break: ~?" format-control format-arguments) (let ((*debugger-hook* nil)) (apply 'invoke-debugger-on-designator 'break (or format-control "Break was invoked.") format-arguments))) nil) (define-condition newline () ()) (define-condition floating-point-inexact (arithmetic-error) ()) (define-condition floating-point-invalid-operation (arithmetic-error) ()) (define-condition floating-point-overflow (arithmetic-error) ()) (define-condition floating-point-underflow (arithmetic-error) ())
null
https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/losp/muerte/conditions.lisp
lisp
------------------------------------------------------------------ For distribution policy, see the accompanying file COPYING. Filename: conditions.lisp Description: Created at: Wed Nov 20 15:47:04 2002 ------------------------------------------------------------------ (declare (dynamic-extent args)) avoid recursive error if *b-o-s* is faulty. XXX memoize this find-class.. (format *debug-io* "~&Break: ~?" format-control format-arguments)
Copyright ( C ) 2001 - 2005 , Department of Computer Science , University of Tromso , Norway . Author : < > $ I d : conditions.lisp , v 1.29 2009 - 07 - 19 18:54:32 ffjeld Exp $ (require :muerte/basic-macros) (provide :muerte/conditions) (in-package muerte) (defparameter *break-on-signals* nil) (defparameter *debugger-function* nil) (defvar *debugger-dynamic-context* nil) (defparameter *debugger-invoked-stack-frame* nil) (defvar *debugger-condition*) (defmacro define-condition (name parent-types slot-specs &rest options) `(progn (defclass ,name ,(or parent-types '(condition)) ,slot-specs (:metaclass read-only-class)) ,@(let ((reporter (cadr (assoc :report options)))) (when reporter `((defmethod print-object ((condition ,name) stream) (if *print-escape* (call-next-method) (funcall (function ,reporter) condition stream)) condition)))) ',name)) (define-condition condition (standard-object) ((format-control :initarg :format-control :initform nil :reader condition-format-control) (format-arguments :initarg :format-arguments :initform nil :reader condition-format-arguments)) (:report (lambda (condition stream) (if (or *print-escape* (not (condition-format-control condition))) (call-next-method) (apply #'format stream (condition-format-control condition) (condition-format-arguments condition)))))) (define-condition simple-condition (condition) ((format-control :reader simple-condition-format-control) (format-arguments :reader simple-condition-format-arguments))) (define-condition serious-condition () ()) (define-condition error (serious-condition) ()) (define-condition storage-condition (serious-condition) ()) (define-condition warning () ()) (define-condition style-warning () ()) (define-condition simple-error (simple-condition error) ()) (define-condition simple-warning (simple-condition warning) ()) (define-condition parse-error (error) ()) (define-condition cell-error (error) ((name :initarg :name :reader cell-error-name)) (:report (lambda (c s) (format s "Error accessing cell ~S." (cell-error-name c))))) (define-condition undefined-function (cell-error) () (:report (lambda (c s) (format s "Undefined function ~S." (cell-error-name c))))) (define-condition undefined-function-call (undefined-function) ((arguments :initarg :arguments :reader undefined-function-call-arguments)) (:report (lambda (c s) (format s "Undefined function ~S called with arguments ~:S." (cell-error-name c) (undefined-function-call-arguments c))))) (define-condition unbound-variable (cell-error) () (:report (lambda (c s) (format s "Unbound variable ~S." (cell-error-name c))))) (define-condition unbound-slot (cell-error) ((instance :initarg :instance :reader unbound-slot-instance)) (:report (lambda (c s) (format s "The slot ~S is unbound in the object ~S." (cell-error-name c) (unbound-slot-instance c))))) (define-condition print-not-readable (error) ((object :initarg :object :reader print-not-readable-object)) (:report (lambda (c s) (format s "Cannot print ~S readably." (print-not-readable-object c))))) (define-condition program-error (error) ()) (defun simple-program-error (format-control &rest format-arguments) (error 'program-error :format-control format-control :format-argumetns format-arguments)) (define-condition type-error (error) ((expected-type :initarg :expected-type :reader type-error-expected-type) (datum :initarg :datum :reader type-error-datum)) (:report (lambda (c s) (format s "The object ~Z `~S' is not of type ~S." (type-error-datum c) (type-error-datum c) (type-error-expected-type c))))) (define-condition simple-type-error (simple-condition type-error) ()) (define-condition etypecase-error (type-error) () (:report (lambda (c s) (format s "The object '~S' fell through an etypecase where the legal types were ~S." (type-error-datum c) (type-error-expected-type c))))) (defun etypecase-error (datum expecteds) (error 'etypecase-error :datum datum :expected-type (cons 'or expecteds))) (define-condition ecase-error (type-error) () (:report (lambda (c s) (format s "The object '~S' fell through an ecase where the legal cases were ~S." (type-error-datum c) (type-error-expected-type c))))) (defun ecase-error (datum expecteds) (error 'ecase-error :datum datum :expected-type (cons 'member expecteds))) (define-condition control-error (error) ()) (define-condition throw-error (control-error) ((tag :initarg :tag :reader throw-error-tag)) (:report (lambda (c s) (format s "Cannot throw to tag `~S'." (throw-error-tag c))))) (define-condition wrong-argument-count (program-error) ((function :initarg :function :reader condition-function) (argument-count :initarg :argument-count :reader condition-argument-count)) (:report (lambda (c s) (format s "Function ~S ~:A received ~:[an incorrect number of~;~:*~D~] arguments." (funobj-name (condition-function c)) (funobj-lambda-list (condition-function c)) (condition-argument-count c))))) (define-condition index-out-of-range (error) ((index :initarg :index :reader condition-index) (range :initarg :range :reader condition-range)) (:report (lambda (c s) (format s "Index ~D is beyond range 0-~D." (condition-index c) (condition-range c))))) (define-condition stream-error (error) ((stream :initarg :stream :reader stream-error-stream))) (define-condition reader-error (parse-error stream-error) ()) (define-condition end-of-file (stream-error) () (:report (lambda (c s) (format s "End of file encountered on ~W." (stream-error-stream c))))) (define-condition arithmetic-error (error) ((operation :initarg :operation :initform nil :reader arithmetic-error-operation) (operands :initarg :operands :initform nil :reader arithmetic-error-operands))) (define-condition division-by-zero (arithmetic-error) () (:report (lambda (c s) (declare (ignore c)) (format s "Division by zero.")))) (define-condition package-error (error) ((package :initarg :package :initform nil :reader package-error-package))) (define-condition file-error (error) ((pathname :initarg :pathname :initform nil :reader file-error-pathname))) (defun make-condition (type &rest slot-initializations) (declare (dynamic-extent slot-initializations)) (apply 'make-instance type slot-initializations)) (defun warn (datum &rest arguments) (declare (dynamic-extent arguments)) (cond ((not (eq t (get 'clos-bootstrap 'have-bootstrapped))) (fresh-line) (write-string "Warning: ") (apply 'format t datum arguments) (fresh-line)) (t (with-simple-restart (muffle-warning "Muffle warning.") (let ((c (signal-simple 'simple-warning datum arguments)) (*standard-output* *error-output*)) (typecase datum (string (fresh-line) (write-string "Warning: ") (apply 'format t datum arguments) (terpri)) (t (format t "~&Warning: ~A" (or c (coerce-to-condition 'simple-warning datum arguments))))))))) nil) (defun coerce-to-condition (default-type datum args) (etypecase datum (condition datum) (symbol (apply 'make-condition datum args)) (string (make-condition default-type :format-control datum :format-arguments (copy-list args))))) (defun signal-simple (default-type datum args) "Signal the condition denoted by a condition designator. Will only make-instance a condition when it is required. Return the condition object, if there was one." (let* ((class (etypecase datum (symbol (or (find-class datum nil) (error "No condition class named ~S." datum))) (string (find-class default-type)) (condition (class-of datum)))) (cpl (class-precedence-list class)) (condition nil) (bos-type *break-on-signals*)) (with-simple-restart (continue "Ignore *break-on-signals*.") (when (typecase bos-type (null nil) (symbol (let ((bos-class (find-class bos-type nil))) (if (not bos-class) (typep (class-prototype-value class) bos-type) (member bos-class cpl)))) (list (typep (class-prototype-value class) bos-type)) (t (member bos-type cpl))) (break "Signalling ~S" datum)))) (macrolet ((invoke-handler (handler) `(funcall ,handler (or condition (setf condition (coerce-to-condition default-type datum args)))))) (let ((*active-condition-handlers* *active-condition-handlers*)) (do () ((null *active-condition-handlers*)) (let ((handlers (pop *active-condition-handlers*))) (dolist (handler handlers) (let ((handler-type (car handler))) (typecase handler-type (symbol (let ((handler-class (find-class handler-type nil))) (when (if (not handler-class) (typep (class-prototype-value class) handler-type) (progn (member handler-class cpl))) (invoke-handler (cdr handler))))) (cons (when (typep (class-prototype-value class) handler-type) (invoke-handler (cdr handler)))) (null) (t (when (member handler-type cpl) (invoke-handler (cdr handler))))))))))) (or condition (when (typep datum condition) datum)))) (defun signal (datum &rest args) (declare (dynamic-extent args)) (signal-simple 'simple-condition datum args) nil) (defun invoke-debugger (condition) (when *debugger-hook* (let ((hook *debugger-hook*) (*debugger-hook* nil)) (funcall hook condition hook))) #+ignore (unless *debugger-function* (setf *debugger-function* #'muerte.init::my-debugger)) (cond ((not *debugger-function*) (let ((*never-use-print-object* t)) (backtrace :spartan t :conflate nil)) (format t "~&No debugger in *debugger-function*...") (dotimes (i 100000) (write-string "")) (format t "Trying to continue or abort.") (invoke-restart (or (find-restart 'continue) (find-restart 'abort) (format t "~%Condition for debugger: ~Z" condition) (format t "~%No abort restart is active. Halting CPU.") (halt-cpu)))) (t (let ((*debugger-invoked-stack-frame* (stack-frame-uplink nil (current-stack-frame)))) (funcall *debugger-function* condition)))) (format *debug-io* "~&Debugger ~@[on ~S ]returned!~%Trying to abort...~%" condition) (let ((r (find-restart 'abort))) (when r (invoke-restart r)) (format *debug-io* "~&Aborting failed. Halting CPU.") (halt-cpu))) (defun invoke-debugger-on-designator (&rest designator) (declare (dynamic-extent designator)) (if (or (eq 'break (car designator)) (and *error-no-condition-for-debugger* (symbolp (car designator))) do n't let an error trigger CLOS bootstrapping . (not (eq t (get 'clos-bootstrap 'have-bootstrapped)))) (invoke-debugger designator) (invoke-debugger (coerce-to-condition (car designator) (cadr designator) (cddr designator))))) (defun break (&optional format-control &rest format-arguments) (declare (dynamic-extent format-arguments)) (with-simple-restart (continue "Return from break~:[.~;~:*: ~?~]" format-control format-arguments) (let ((*debugger-hook* nil)) (apply 'invoke-debugger-on-designator 'break (or format-control "Break was invoked.") format-arguments))) nil) (define-condition newline () ()) (define-condition floating-point-inexact (arithmetic-error) ()) (define-condition floating-point-invalid-operation (arithmetic-error) ()) (define-condition floating-point-overflow (arithmetic-error) ()) (define-condition floating-point-underflow (arithmetic-error) ())
bb39588b22e8723e6db4fd66b00f30b6f6ae4da734cfaaad070898447b9320a3
otakar-smrz/elixir-fm
Lookup.hs
-- | -- -- Module : Elixir.Lookup Copyright : 2005 - 2016 -- License : GPL -- -- Maintainer : otakar-smrz users.sf.net -- Stability : provisional -- Portability : portable -- -- "ElixirFM" module Elixir.Lookup where import Elixir.Data import Elixir.Lexicon import Elixir.Inflect import Elixir.Derive import Elixir.Pretty import Encode.Arabic import Data.Char import Data.List hiding (lookup) import Prelude hiding (lookup) instance Pretty [Clips] => Pretty (String, [Clips]) where pretty (w, x) = text w <> align (vcat (map nice x)) <> line where nice x = vcat [ text "\t" <> width ((text . show) c) ( \ c' -> hcat ( punctuate ( line <> text "\t" <> fill c' empty ) [ unwraps ( \ (Nest r z) -> hcat ( punctuate ( line <> text "\t" <> fill c' empty ) [ text "\t" <> width ((text . show) i) ( \ i' -> hcat ( punctuate ( line <> text "\t" <> fill c' empty <> text "\t" <> fill i' empty ) ( ( text "\t" <> pretty (domain e) <> joinText [merge r (morphs e), show r, show (morphs e), show (reflex e), show (lookupForm r e)] ) : [ text "\t" <> width (pretty f) ( \ f' -> hcat ( punctuate ( line <> text "\t" <> fill c' empty <> text "\t" <> fill i' empty <> text "\t" <> fill f' empty ) [ joinText [merge r t, show r, show t] | t <- s ] ) ) | (f, s) <- [ (pretty f, s) | (f, s) <- display (entity e) ] ++ [ (pretty f, s) | (f : _, s) <- snd (limits e) ] ] ) ) ) | (i, e) <- zip y z ] ) ) w | w <- emanate c ] ) ) | c <- if not (null (snd x)) || null y then regroup y else [x] ] where y = enumerate x instance Pretty [Clips] where pretty = singleline pretty instance Pretty Clips where pretty x = vcat [ (text . show) c <> align ( vcat [ unwraps ( \ (Nest r z) -> vcat [ text "\t" <> width ((text . show) i) ( \ i' -> hcat ( punctuate ( line <> text "\t" <> fill i' empty ) ( ( text "\t" <> pretty (domain e) <> joinText [merge r (morphs e), show r, show (morphs e), show (reflex e), show (lookupForm r e)] ) : [ text "\t" <> width (pretty f) ( \ f' -> hcat ( punctuate ( line <> text "\t" <> fill i' empty <> text "\t" <> fill f' empty ) [ joinText [merge r t, show r, show t] | t <- s ] ) ) | (f, s) <- [ (pretty f, s) | (f, s) <- display (entity e) ] ++ [ (pretty f, s) | (f : _, s) <- snd (limits e) ] ] ) ) ) | (i, e) <- zip y z ] ) w | w <- emanate c ] ) | c <- if not (null (snd x)) || null y then regroup y else [x] ] where y = enumerate x display :: Morphing a a => Entity a -> [(String, [Morphs a])] display x = case x of Verb f p i c m t v -> eraseEmpty p [("-P--------", map morph p)] ++ eraseEmpty i [("-I--------", map morph i)] ++ eraseEmpty c [("-C--------", map morph c)] ++ eraseEmpty m [("N---------", m)] Noun l f e -> eraseEmpty l [("-------P--", l)] ++ eraseEmpty f [("------F---", f)] Adj l f -> eraseEmpty l [("-------P--", l)] ++ eraseEmpty f [("------F---", f)] Num l f -> eraseEmpty l [("-------P--", l)] ++ eraseEmpty f [("------F---", f)] _ -> [] where eraseNothing x y = case x of Nothing -> [] _ -> y eraseEmpty x y = case x of [] -> [] _ -> y regroup :: [Index] -> [Clips] regroup = map (\ z -> (fst (head z), map snd z)) . groupBy (\ x y -> fst x == fst y) enumerate :: Clips -> [Index] enumerate (i, n) = [ (j, z) | (j, w) <- find i lexicon, z <- unwraps (lookups n) w ] where find x y | x > 0 && x < z = [(x, y !! (x - 1))] | x < 0 && x > -z = find (x + z) y | otherwise = [] where z = length y + 1 lookups [] (Nest _ y) = [1 .. length y] lookups n (Nest _ y) = [ z | x <- n, (z, _) <- find x y ] emanate :: Clips -> Lexicon emanate (i, n) = [ z | w <- find i lexicon, z <- wraps (lookups n) w ] where find x y | x > 0 = take 1 (drop (x - 1) y) | x < 0 = find (-x) (reverse y) | otherwise = [] lookups [] z = [z] lookups n (Nest r y) = [Nest r [ e | x <- n, e <- find x y ]] lookupUsing :: Maybe [Clips] -> (Root -> Maybe Bool) -> (forall c . (Wrapping c, Template c, Show c, Rules c, Forming c, Morphing c c) => Root -> Entry c -> Bool) -> [Clips] lookupUsing Nothing p q = [ z | (n, i) <- zip lexicon [1 ..], z <- unwraps (lookups i p q) n ] where lookups i p q (Nest r l) = case p r of Just True -> [(i, [])] Just _ | not (null js) -> [(i, js)] _ -> [] where js = [ j | (e, j) <- zip l [1 ..], q r e ] lookupUsing (Just []) _ _ = [] lookupUsing (Just cs) p q = [ z | (n, i) <- zip lexicon [1 ..], (c, ds) <- cs, i == c, z <- unwraps (lookups i ds p q) n ] where lookups i ds p q (Nest r l) = case p r of Just True -> [(i, ds)] Just _ | not (null js) -> [(i, js)] _ -> [] where js = case ds of [] -> [ j | (e, j) <- zip l [1 ..], q r e ] _ -> [ j | (e, j) <- zip l [1 ..], d <- ds, j == d, q r e ] class Lookup a where lookup :: a -> [Clips] with :: [Clips] -> a -> [Clips] lookupWith :: Maybe [Clips] -> a -> [Clips] lookup = lookupWith Nothing with = lookupWith . Just infixl 3 `with` instance Lookup a => Lookup [a] where lookupWith y x = [ z | u <- x, z <- lookupWith y u ] instance Lookup Index where lookupWith y x = lookupWith y (clips x) instance Lookup Clips where lookupWith Nothing q = [q] lookupWith (Just p) (x, xs) = [ (x, zs) | (y, ys) <- p, y == x, zs <- ints xs ys ] where ints xs [] = [xs] ints [] ys = [ys] ints xs ys = case intersect ys xs of [] -> [] zs -> [zs] instance Lookup [UPoint] where lookupWith y [] = lookupWith y "" lookupWith y x = lookupUsing y f (\ r e -> q (decode TeX (merge r (morphs e)))) where f z = if isSubsumed (flip alike) assims (reduce z) r then Just (q (decode TeX z)) else Nothing q z = omitting alike omits (units z) u r = recode x u = units x instance Lookup String where lookupWith y x = lookupUsing y f (\ r e -> q (merge r (morphs e))) where f z = if isSubsumed (flip alike) assims (reduce z) u then Just (q z) else Nothing q z = omitting alike omits (units z) u u = units x instance Lookup [[UPoint]] where lookupWith y [] = [] lookupWith y x = lookupUsing y (Just . const False) (\ _ e -> let r = map (map toLower) (reflex e) in all (flip elem r) q) where q = map (map toLower . encode UCS) x -- (\ _ e -> flip all q ((flip elem . map (map toLower)) (reflex e))) -- (\ _ e -> any (flip elem q) (reflex e)) instance Lookup [String] where lookupWith y [] = [] lookupWith y x = lookupUsing y (Just . const False) (\ _ e -> let r = map (words . map toLower) (reflex e) in all (\ p -> any (\ s -> all (flip elem s) p) r) q) where q = map (words . map toLower) x -- (\ _ e -> any (flip all (map (map toLower) x) . flip elem . words . map toLower) (reflex e)) -- (\ _ e -> any (any (flip elem x) . words) (reflex e)) sense :: String -> [[UPoint]] sense x = senses [x] senses :: [String] -> [[UPoint]] senses = map (decode UCS) instance Show a => Lookup (Morphs a) where lookupWith y x = lookupUsing y (Just . const False) (\ _ e -> z `isInfixOf` (" " ++ show (morphs e) ++ " ")) where z = " " ++ show x ++ " " -- lookupUsing y (Just . const False) (\ _ e -> show x == show (morphs e)) instance (Morphing a b, Show b) => Lookup a where lookupWith y x = lookupWith y (morph x) instance Lookup Form where lookupWith y x = lookupUsing y (Just . const False) (\ r e -> z r e) where z r e = case entity e of Verb fs _ _ _ _ _ _ -> or [ x == f | f <- fs ] Noun _ _ _ -> or [ any (morphs e ==) [morph b, morph c, d] | (_, b, c, d) <- nounStems x r ] Adj _ _ -> or [ any (morphs e ==) [morph b, morph c] | (_, b, c, _) <- nounStems x r ] _ -> or [] -- lookupUsing y (Just . const False) (\ _ e -> isForm x (morphs e)) instance Lookup TagsType where lookupWith y x = lookupWith y [x] instance Lookup [TagsType] where lookupWith y x = lookupUsing y (Just . const False) (\ _ e -> (not . null) (restrict (domain e) x)) countNest :: Lexicon -> Int countNest = length countEntry :: Lexicon -> Int countEntry = sum . map countEach countEach :: Wrap Nest -> Int countEach = length . wraps ents inflectLookup :: (Lookup a, Inflect Lexeme b) => a -> b -> [[Wrap Inflected]] inflectLookup x y = [ wraps (\ (Nest r n) -> [ Inflected (inflect (Lexeme r e) y) | e <- n ]) w | l <- lookup x, w <- emanate l ] deriveLookup :: (Lookup a, Derive Lexeme b) => a -> b -> [[Wrap Derived]] deriveLookup x y = [ wraps (\ (Nest r n) -> [ Derived (derive (Lexeme r e) y) | e <- n ]) w | l <- lookup x, w <- emanate l ]
null
https://raw.githubusercontent.com/otakar-smrz/elixir-fm/fae5bab6dd53c15d25c1e147e7787b2c254aabf0/Haskell/ElixirFM/Elixir/Lookup.hs
haskell
| Module : Elixir.Lookup License : GPL Maintainer : otakar-smrz users.sf.net Stability : provisional Portability : portable "ElixirFM" (\ _ e -> flip all q ((flip elem . map (map toLower)) (reflex e))) (\ _ e -> any (flip elem q) (reflex e)) (\ _ e -> any (flip all (map (map toLower) x) . flip elem . words . map toLower) (reflex e)) (\ _ e -> any (any (flip elem x) . words) (reflex e)) lookupUsing y (Just . const False) (\ _ e -> show x == show (morphs e)) lookupUsing y (Just . const False) (\ _ e -> isForm x (morphs e))
Copyright : 2005 - 2016 module Elixir.Lookup where import Elixir.Data import Elixir.Lexicon import Elixir.Inflect import Elixir.Derive import Elixir.Pretty import Encode.Arabic import Data.Char import Data.List hiding (lookup) import Prelude hiding (lookup) instance Pretty [Clips] => Pretty (String, [Clips]) where pretty (w, x) = text w <> align (vcat (map nice x)) <> line where nice x = vcat [ text "\t" <> width ((text . show) c) ( \ c' -> hcat ( punctuate ( line <> text "\t" <> fill c' empty ) [ unwraps ( \ (Nest r z) -> hcat ( punctuate ( line <> text "\t" <> fill c' empty ) [ text "\t" <> width ((text . show) i) ( \ i' -> hcat ( punctuate ( line <> text "\t" <> fill c' empty <> text "\t" <> fill i' empty ) ( ( text "\t" <> pretty (domain e) <> joinText [merge r (morphs e), show r, show (morphs e), show (reflex e), show (lookupForm r e)] ) : [ text "\t" <> width (pretty f) ( \ f' -> hcat ( punctuate ( line <> text "\t" <> fill c' empty <> text "\t" <> fill i' empty <> text "\t" <> fill f' empty ) [ joinText [merge r t, show r, show t] | t <- s ] ) ) | (f, s) <- [ (pretty f, s) | (f, s) <- display (entity e) ] ++ [ (pretty f, s) | (f : _, s) <- snd (limits e) ] ] ) ) ) | (i, e) <- zip y z ] ) ) w | w <- emanate c ] ) ) | c <- if not (null (snd x)) || null y then regroup y else [x] ] where y = enumerate x instance Pretty [Clips] where pretty = singleline pretty instance Pretty Clips where pretty x = vcat [ (text . show) c <> align ( vcat [ unwraps ( \ (Nest r z) -> vcat [ text "\t" <> width ((text . show) i) ( \ i' -> hcat ( punctuate ( line <> text "\t" <> fill i' empty ) ( ( text "\t" <> pretty (domain e) <> joinText [merge r (morphs e), show r, show (morphs e), show (reflex e), show (lookupForm r e)] ) : [ text "\t" <> width (pretty f) ( \ f' -> hcat ( punctuate ( line <> text "\t" <> fill i' empty <> text "\t" <> fill f' empty ) [ joinText [merge r t, show r, show t] | t <- s ] ) ) | (f, s) <- [ (pretty f, s) | (f, s) <- display (entity e) ] ++ [ (pretty f, s) | (f : _, s) <- snd (limits e) ] ] ) ) ) | (i, e) <- zip y z ] ) w | w <- emanate c ] ) | c <- if not (null (snd x)) || null y then regroup y else [x] ] where y = enumerate x display :: Morphing a a => Entity a -> [(String, [Morphs a])] display x = case x of Verb f p i c m t v -> eraseEmpty p [("-P--------", map morph p)] ++ eraseEmpty i [("-I--------", map morph i)] ++ eraseEmpty c [("-C--------", map morph c)] ++ eraseEmpty m [("N---------", m)] Noun l f e -> eraseEmpty l [("-------P--", l)] ++ eraseEmpty f [("------F---", f)] Adj l f -> eraseEmpty l [("-------P--", l)] ++ eraseEmpty f [("------F---", f)] Num l f -> eraseEmpty l [("-------P--", l)] ++ eraseEmpty f [("------F---", f)] _ -> [] where eraseNothing x y = case x of Nothing -> [] _ -> y eraseEmpty x y = case x of [] -> [] _ -> y regroup :: [Index] -> [Clips] regroup = map (\ z -> (fst (head z), map snd z)) . groupBy (\ x y -> fst x == fst y) enumerate :: Clips -> [Index] enumerate (i, n) = [ (j, z) | (j, w) <- find i lexicon, z <- unwraps (lookups n) w ] where find x y | x > 0 && x < z = [(x, y !! (x - 1))] | x < 0 && x > -z = find (x + z) y | otherwise = [] where z = length y + 1 lookups [] (Nest _ y) = [1 .. length y] lookups n (Nest _ y) = [ z | x <- n, (z, _) <- find x y ] emanate :: Clips -> Lexicon emanate (i, n) = [ z | w <- find i lexicon, z <- wraps (lookups n) w ] where find x y | x > 0 = take 1 (drop (x - 1) y) | x < 0 = find (-x) (reverse y) | otherwise = [] lookups [] z = [z] lookups n (Nest r y) = [Nest r [ e | x <- n, e <- find x y ]] lookupUsing :: Maybe [Clips] -> (Root -> Maybe Bool) -> (forall c . (Wrapping c, Template c, Show c, Rules c, Forming c, Morphing c c) => Root -> Entry c -> Bool) -> [Clips] lookupUsing Nothing p q = [ z | (n, i) <- zip lexicon [1 ..], z <- unwraps (lookups i p q) n ] where lookups i p q (Nest r l) = case p r of Just True -> [(i, [])] Just _ | not (null js) -> [(i, js)] _ -> [] where js = [ j | (e, j) <- zip l [1 ..], q r e ] lookupUsing (Just []) _ _ = [] lookupUsing (Just cs) p q = [ z | (n, i) <- zip lexicon [1 ..], (c, ds) <- cs, i == c, z <- unwraps (lookups i ds p q) n ] where lookups i ds p q (Nest r l) = case p r of Just True -> [(i, ds)] Just _ | not (null js) -> [(i, js)] _ -> [] where js = case ds of [] -> [ j | (e, j) <- zip l [1 ..], q r e ] _ -> [ j | (e, j) <- zip l [1 ..], d <- ds, j == d, q r e ] class Lookup a where lookup :: a -> [Clips] with :: [Clips] -> a -> [Clips] lookupWith :: Maybe [Clips] -> a -> [Clips] lookup = lookupWith Nothing with = lookupWith . Just infixl 3 `with` instance Lookup a => Lookup [a] where lookupWith y x = [ z | u <- x, z <- lookupWith y u ] instance Lookup Index where lookupWith y x = lookupWith y (clips x) instance Lookup Clips where lookupWith Nothing q = [q] lookupWith (Just p) (x, xs) = [ (x, zs) | (y, ys) <- p, y == x, zs <- ints xs ys ] where ints xs [] = [xs] ints [] ys = [ys] ints xs ys = case intersect ys xs of [] -> [] zs -> [zs] instance Lookup [UPoint] where lookupWith y [] = lookupWith y "" lookupWith y x = lookupUsing y f (\ r e -> q (decode TeX (merge r (morphs e)))) where f z = if isSubsumed (flip alike) assims (reduce z) r then Just (q (decode TeX z)) else Nothing q z = omitting alike omits (units z) u r = recode x u = units x instance Lookup String where lookupWith y x = lookupUsing y f (\ r e -> q (merge r (morphs e))) where f z = if isSubsumed (flip alike) assims (reduce z) u then Just (q z) else Nothing q z = omitting alike omits (units z) u u = units x instance Lookup [[UPoint]] where lookupWith y [] = [] lookupWith y x = lookupUsing y (Just . const False) (\ _ e -> let r = map (map toLower) (reflex e) in all (flip elem r) q) where q = map (map toLower . encode UCS) x instance Lookup [String] where lookupWith y [] = [] lookupWith y x = lookupUsing y (Just . const False) (\ _ e -> let r = map (words . map toLower) (reflex e) in all (\ p -> any (\ s -> all (flip elem s) p) r) q) where q = map (words . map toLower) x sense :: String -> [[UPoint]] sense x = senses [x] senses :: [String] -> [[UPoint]] senses = map (decode UCS) instance Show a => Lookup (Morphs a) where lookupWith y x = lookupUsing y (Just . const False) (\ _ e -> z `isInfixOf` (" " ++ show (morphs e) ++ " ")) where z = " " ++ show x ++ " " instance (Morphing a b, Show b) => Lookup a where lookupWith y x = lookupWith y (morph x) instance Lookup Form where lookupWith y x = lookupUsing y (Just . const False) (\ r e -> z r e) where z r e = case entity e of Verb fs _ _ _ _ _ _ -> or [ x == f | f <- fs ] Noun _ _ _ -> or [ any (morphs e ==) [morph b, morph c, d] | (_, b, c, d) <- nounStems x r ] Adj _ _ -> or [ any (morphs e ==) [morph b, morph c] | (_, b, c, _) <- nounStems x r ] _ -> or [] instance Lookup TagsType where lookupWith y x = lookupWith y [x] instance Lookup [TagsType] where lookupWith y x = lookupUsing y (Just . const False) (\ _ e -> (not . null) (restrict (domain e) x)) countNest :: Lexicon -> Int countNest = length countEntry :: Lexicon -> Int countEntry = sum . map countEach countEach :: Wrap Nest -> Int countEach = length . wraps ents inflectLookup :: (Lookup a, Inflect Lexeme b) => a -> b -> [[Wrap Inflected]] inflectLookup x y = [ wraps (\ (Nest r n) -> [ Inflected (inflect (Lexeme r e) y) | e <- n ]) w | l <- lookup x, w <- emanate l ] deriveLookup :: (Lookup a, Derive Lexeme b) => a -> b -> [[Wrap Derived]] deriveLookup x y = [ wraps (\ (Nest r n) -> [ Derived (derive (Lexeme r e) y) | e <- n ]) w | l <- lookup x, w <- emanate l ]
0d7686fb7fced92818a4dbd07b8a9b5121139c3de95d794b25b6a89a571b2434
Vaguery/klapaucius
core.clj
(ns push.interpreter.core (:require [push.util.stack-manipulation :as stack] [push.util.code-wrangling :as util] [push.util.exceptions :as oops] [push.router.core :as router] [push.util.scratch :as scratch] [push.type.definitions.quoted :as quoted] [push.util.type-checkers :as types :refer [pushcode?]] )) (defn append-to-record "Appends the new thing to the collection stored under the indicated key, in the interpreter passed in" [interpreter key new-thing] (update-in interpreter [key] conj new-thing)) (defn merge-into-record "Merges the new map with the map stored under the indicated key, in the interpreter passed in" [interpreter keyname new-map] (assoc interpreter keyname (merge new-map (keyname interpreter) ))) (defn register-type "Takes an Interpreter record, and a PushType record, and adds the PushType to the :types collection in the Interpeter; adds the type's :name as a new stack (if not already present); appends the type's :router to the Interpreter's :routers vector; adds the type's internally defined instructions to the Interpreter's registry automatically." [interpreter type] (-> interpreter (append-to-record , :types type) (append-to-record , :routers (:router type)) (merge-into-record , :stacks {(or (get-in type [:router :target-stack]) (:name type)) '()}) (merge-into-record , :instructions (:instructions type)) )) (defn register-module "Takes an Interpreter record, and a module; adds the module's internally defined instructions to the Interpreter's registry automatically." [interpreter module] (-> interpreter (append-to-record , :types module) (merge-into-record , :instructions (:instructions module)) )) (defn register-types "Takes an Interpreter record, and a list of PushType records. Calls `register-type` on each of the types in turn." [interpreter types] (reduce register-type interpreter types)) (defn register-modules "Takes an Interpreter record, and a list of modules. Calls `register-module` on each of those in turn." [interpreter modules] (reduce register-module interpreter modules)) (defn bind-value "Takes an interpreter, a keyword, and any item. If the keyword is already registered in the interpreter's :bindings hashmap, the item is pushed to that; otherwise, a new binding is made first. If the item is `nil`, the binding is created (if necessary) but nothing is pushed to the stack." [interpreter kwd item] (let [old-stack (get-in interpreter [:bindings kwd] '())] (assoc-in interpreter [:bindings kwd] (if (nil? item) old-stack (conj old-stack item) )))) (defn peek-at-binding "Takes an interpreter and a keyword. Returns the top item (if any) on the indicated :bindings stack, or `nil` if the keyword is not recognized or there are no items on the stack." [interpreter kwd] (first (get-in interpreter [:bindings kwd]))) (defn bind-input "If the arguments are an Interpreter, a keyword and any item, it will store the item under the keyword key in the Interpreter's :bindings hashmap, pushing the item onto the top of the indicated value stack. If no keyword is given, one is constructed automatically." ([interpreter item] (let [next-index (inc (count (:bindings interpreter))) next-key (keyword (str "input!" next-index))] (bind-value interpreter next-key item))) ([interpreter kwd item] (bind-value interpreter kwd item))) (defn bind-inputs "Takes an Interpreter record, and a hashmap of key-value items. If the interpreter already has some of the bindings assigned, the new values are pushed onto the old stacks." [interpreter values] (cond (vector? values) (reduce (partial bind-input) interpreter values) (map? values) (reduce-kv bind-input interpreter values) :else (throw (Exception. "cannot bind inputs")))) (defn bound-keyword? "Takes an interpreter, and a keyword, and returns true if the keyword is a key in the :bindings hashmap" [interpreter kwd] (contains? (:bindings interpreter) kwd)) (defn add-instruction "Takes an Interpreter and an Instruction (record), and adds the instruction to the :instructions registry of the interpreter, without checking for prior definitions." [interpreter instruction] (assoc-in interpreter [:instructions (:token instruction)] instruction)) (defn register-instruction "Takes an Interpreter and an Instruction, and attempts to add the Instruction to the :instructions map of the Interpreter, keyed by its `:token`." [interpreter instruction] (let [token (:token instruction) registry (:instructions interpreter)] (if (contains? registry token) (oops/throw-redefined-instruction-error token)) (add-instruction interpreter instruction))) (defn forget-instruction "Takes an Interpreter and a keyword (the name of an instruction, supposedly). Un-registers ('forgets') the instruction, returning the Interpreter" [interpreter kw] (let [old-instructions (:instructions interpreter)] (assoc interpreter :instructions (dissoc old-instructions kw)))) ;;; reconfigure (defn reconfigure "takes an interpreter and a map of configuration pairs, and merges the map with the current interpreter map" [interpreter new-config] (let [old-config (:config interpreter)] (assoc interpreter :config (merge old-config new-config)))) ;;; manipulating Interpreter state (defn contains-at-least? "Takes an interpreter, a stack name, and a count; returns true if the named stack exists, and has at least that many items on it" [interpreter stack limit] (<= limit (count (stack/get-stack interpreter stack)))) (defn recognizes-instruction? "Takes an Interpreter and an instruction token, and returns true if the token is registered." [interpreter token] (contains? (:instructions interpreter) token)) (defn ready-for-instruction? "Takes an Interpreter (with registered instructions) and a keyword instruction token, and returns true if the number of items on the stacks meets or exceeds all the specified :needs for that instruction. Returns false if the instruction is not registered." [interpreter token] (let [needs (get-in interpreter [:instructions token :needs] )] (and (recognizes-instruction? interpreter token) (reduce-kv (fn [truth k v] (and truth (contains-at-least? interpreter k v))) true needs)))) (defn get-instruction [interpreter token] (get-in interpreter [:instructions token])) (defn store-item-in-ARGS "Takes an Interpreter an a Push item. If the Interpreter's :store-args? :config state is `true`, it will bind the item passed in as the new [top] value in the :binding called `:ARGS`. Otherwise it has no effect." [interpreter item] (let [store? (get-in interpreter [:config :store-args?] false)] (if store? (bind-value interpreter :ARGS item) interpreter))) (defn append-item-to-exec "Takes an Interpreter an a Push item. If the Interpreter's :cycle-args? :config state is `true`, it will append the item passed in to the `:exec` stack. Otherwise it has no effect." [interpreter item] (let [cycle? (get-in interpreter [:config :cycle-args?] false) old-exec (stack/get-stack interpreter :exec)] (if cycle? (stack/set-stack interpreter :exec (reverse (into (reverse old-exec) (list item)))) interpreter))) (defn apply-instruction "Takes an interpreter and a token. Returns the interpreter. If the `:store-args?` value is `true` in the interpreter's `:config`, the arguments will be saved onto the `:ARGS` binding. If the `:cycle-args?` value is `true` in the interpreter's `:config`, the arguments will (also) be appended to the tail of `:exec`. NOTE: returns ONLY the interpreter, not the state tuple." [interpreter token] (let [updated ((:transaction (get-instruction interpreter token)) interpreter) args (scratch/scratch-read updated :ARGS)] (-> updated (store-item-in-ARGS , args) (append-item-to-exec , args) ))) (defn push-item "Takes an Interpreter, a stack name and a Clojure expression, and returns the Interpreter with the item pushed onto the specified stack. If the stack doesn't already exist, it is created. If the item is nil, no change occurs." [interpreter stack item] (if (nil? item) interpreter (let [old-stack (get-in interpreter [:stacks stack])] (assoc-in interpreter [:stacks stack] (conj old-stack item))))) (defn missing-args-message [interpreter token] (let [t (:counter interpreter)] {:step t :item (str token " missing arguments")})) (defn execute-instruction "Takes an Interpreter and a token, and executes the registered Instruction using the Interpreter as the (only) argument. Raises an exception if the token is not registered." [interpreter token] (let [unrecognized (not (recognizes-instruction? interpreter token)) ready (ready-for-instruction? interpreter token)] (cond unrecognized (oops/throw-unknown-instruction-error token) ready (apply-instruction interpreter token) :else (push-item interpreter :error (missing-args-message interpreter token))))) (defn load-items "Takes an Interpreter, a stack name, and a collection of items. Puts all the items onto the named stack, one at time (probably reversing them along the way." [interpreter stackname item-list] (let [old-stack (get-in interpreter [:stacks stackname]) new-stack (into old-stack (reverse item-list))] (stack/set-stack interpreter stackname new-stack))) (defn instruction? "takes an Interpreter and a keyword, and returns true if the keyword is a key of the :instructions registry in that Interpreter instance" [interpreter token] (contains? (:instructions interpreter) token)) (defn routers-see? "Takes an Interpreter and an item, and returns true if any of its :routers collection matches. NOTE: returns nil otherwise!" [interpreter item] (let [recognizers (:routers interpreter)] (boolean (some #(router/router-recognize? % item) recognizers)))) (defn route-item "Takes an Interpreter and an item it recognizes (which should be established upstream) and sends the item to the designated stack determined by the first matching router predicate." [interpreter item] (let [all-routers (:routers interpreter) active-router (first (filter #(router/router-recognize? % item) all-routers)) preprocessor (:preprocessor active-router) preprocessed-item (preprocessor item) target-stack (:target-stack active-router)] (push-item interpreter target-stack preprocessed-item))) (defn handle-unknown-item "Takes an Interpreter and an item. If the :config :lenient? flag is true, it pushes an unknown item to the :unknown stack; otherwise it calls `throw-unknown-push-item-error`" [interpreter item] (if (keyword? item) (push-item interpreter :ref item) (if (get-in interpreter [:config :lenient?]) (push-item interpreter :unknown item) (oops/throw-unknown-push-item-error item)))) (defn handle-item "Takes an Interpreter and an item, and either recognizes and invokes a keyword registered in that Interpreter as an binding or instruction, or sends the item to the correct stack (if it exists). As a side-effect, the item being processed will be stored in `:current-item` in the Interpreter record." [naive-interpreter item] (let [interpreter (assoc naive-interpreter :current-item item)] (cond (keyword? item) (cond (bound-keyword? interpreter item) (if (get-in interpreter [:config :quote-refs?]) (push-item interpreter :ref item) (push-item interpreter :exec (peek-at-binding interpreter item))) (instruction? interpreter item) (execute-instruction interpreter item) :else (push-item interpreter :ref item)) (routers-see? interpreter item) (route-item interpreter item) (types/pushcode? item) (load-items interpreter :exec item) :else (handle-unknown-item interpreter item)))) (defn clear-all-stacks "removes all items from all stacks in an Interpreter" [interpreter] (let [stacklist (keys (:stacks interpreter))] (assoc interpreter :stacks (reduce #(assoc %1 %2 '()) {} stacklist)))) (defn push-program-to-code "when called, this copies the stored `:program` into the `:code` stack as a block" [interpreter] (push-item interpreter :code (seq (:program interpreter)))) (defn prep-code-stack "when called, this checks the :config of the interpreter and if :preload-code? is truthy it will copy the :program to a code block on top of the :code stack" [interpreter] (if (get-in interpreter [:config :preload-code?]) (push-program-to-code interpreter) interpreter)) (defn reset-interpreter "takes an Interpreter instance and: - sets the counter to 0 - clears all non-:exec stacks - puts the program onto the :exec stack" [interpreter] (-> interpreter (clear-all-stacks) (assoc , :counter 0) (load-items :exec (:program interpreter)) prep-code-stack)) (defn recycle-interpreter "takes an Interpreter instance, a program and new bindings; resets and runs the new setup" [interpreter program & {:keys [bindings] :or {bindings []}}] (-> interpreter (assoc , :program program) (assoc , :bindings {}) (bind-inputs , bindings) reset-interpreter)) (defn increment-counter "takes an Interpreter and increments its :counter (without otherwise changing it)" [interpreter] (update-in interpreter [:counter] inc)) (defn step-limit "reads the [:config :step-limit] value of an Interpreter; returns 0 if nil" [interpreter] (if-let [stop (get-in interpreter [:config :step-limit])] stop 0)) (defn is-done? "Takes and Interpreter and checks various halting conditions. Returns true if any is true. Does not change interpreter state." [interpreter] (let [limit (step-limit interpreter)] (or (and (empty? (stack/get-stack interpreter :exec)) (empty? (stack/get-stack interpreter :snapshot))) (>= (:counter interpreter) limit)))) (defn- set-doneness "Takes an interpreter and sets its :done? to the `is-done?` result" [interpreter] (assoc interpreter :done? (is-done? interpreter))) (defn- truncated-string [item length] (let [as-string (str item)] (if (< (count as-string) length) (subs as-string 0 (count as-string)) (str (subs as-string 0 length) "…")))) (defn log-routed-item "Takes an Interpreter and any item, and pushes a 'time-stamped' map of that item on the Interpreter's :log stack. The 'time-stamp' is the counter of the Interpreter when called." [interpreter item] (push-item interpreter :log {:step (:counter interpreter) :item (truncated-string item 32)})) (defn soft-snapshot-ending "Called when an Interpreter has an empty :exec stack but a stored :snapshot on that stack. Merges the stored stacks, keeps the persistent ones, combines the :exec stacks and puts the :return on top." [interpreter] (let [returns (stack/get-stack interpreter :return) current-exec (stack/get-stack interpreter :exec) snapshots (stack/get-stack interpreter :snapshot) retrieved (first snapshots) old-exec (:exec retrieved) new-exec (util/list! (concat (reverse returns) current-exec old-exec)) ] (-> (stack/merge-snapshot interpreter retrieved) (stack/set-stack , :exec new-exec) (stack/set-stack , :snapshot (pop snapshots)) (increment-counter ,) (log-routed-item , "SNAPSHOT STACK POPPED") (set-doneness ,)))) (defn step "Takes an Interpreter, pops one item off :exec, routes it to the router, increments the counter. If the :exec stack is empty, does nothing." [interpreter] (let [old-exec (stack/get-stack interpreter :exec)] (if-not (is-done? interpreter) (if (empty? old-exec) (soft-snapshot-ending interpreter) (let [next-item (first old-exec) new-exec (pop old-exec)] (-> interpreter (increment-counter) (stack/set-stack :exec new-exec) (handle-item next-item) (log-routed-item next-item) (set-doneness)))) interpreter))) (defn run-n "Takes an Interpreter, calls `reset` on it, and calls `step` on that reset state for `tick` iterations. Returns the Interpreter state at the end. Can be called for any non-negative integer `tick` value, regardless of halting state." [interpreter tick] (let [start (assoc-in (reset-interpreter interpreter) [:config :step-limit] tick)] (nth (iterate step start) tick))) (defn run-n-forgetfully "Takes an Interpreter, calls `reset` on it, and calls `step` on that reset state for `tick` iterations. Returns the Interpreter state at the end. Drops the head of the lazy recursion. Can be called for any non-negative integer `tick` value, regardless of halting state." [interpreter deadline] (loop [state (assoc-in (reset-interpreter interpreter) [:config :step-limit] deadline) time 0] (if (> time deadline) state (recur (step state) (inc time)) ))) (defn entire-run "Takes an Interpreter, calls `reset` on it, and returns a (lazy) seq containing all of the steps from the start to the specified end point." [interpreter tick] (let [start (assoc-in (reset-interpreter interpreter) [:config :step-limit] tick)] (take tick (iterate step start)))) (defn last-changed-step "Runs a program in the specified interpreter (with a reset) and returns the last step at which the stacks changed" [interpreter tick] (loop [i (assoc-in (reset-interpreter interpreter) [:config :step-limit] tick) stacks (:stacks i)] (if (or (>= (:counter i) tick) (is-done? i) (= (:stacks (step i)) stacks)) (step i) (recur (step i) (:stacks (step i)))))) (defn run-until-done "Takes an Interpreter, calls `reset` on it, and calls `step` on that reset state until :done? is true. Does not check for infinite loops." [interpreter] (let [start (reset-interpreter interpreter)] (first (filter is-done? (iterate step start)))))
null
https://raw.githubusercontent.com/Vaguery/klapaucius/17b55eb76feaa520a85d4df93597cccffe6bdba4/src/push/interpreter/core.clj
clojure
reconfigure manipulating Interpreter state returns true if otherwise it
(ns push.interpreter.core (:require [push.util.stack-manipulation :as stack] [push.util.code-wrangling :as util] [push.util.exceptions :as oops] [push.router.core :as router] [push.util.scratch :as scratch] [push.type.definitions.quoted :as quoted] [push.util.type-checkers :as types :refer [pushcode?]] )) (defn append-to-record "Appends the new thing to the collection stored under the indicated key, in the interpreter passed in" [interpreter key new-thing] (update-in interpreter [key] conj new-thing)) (defn merge-into-record "Merges the new map with the map stored under the indicated key, in the interpreter passed in" [interpreter keyname new-map] (assoc interpreter keyname (merge new-map (keyname interpreter) ))) (defn register-type "Takes an Interpreter record, and a PushType record, and adds the PushType to the :types collection in the Interpeter; adds the type's :name as a new stack (if not already present); appends the type's :router to the Interpreter's :routers vector; adds the type's internally defined instructions to the Interpreter's registry automatically." [interpreter type] (-> interpreter (append-to-record , :types type) (append-to-record , :routers (:router type)) (merge-into-record , :stacks {(or (get-in type [:router :target-stack]) (:name type)) '()}) (merge-into-record , :instructions (:instructions type)) )) (defn register-module "Takes an Interpreter record, and a module; adds the module's internally defined instructions to the Interpreter's registry automatically." [interpreter module] (-> interpreter (append-to-record , :types module) (merge-into-record , :instructions (:instructions module)) )) (defn register-types "Takes an Interpreter record, and a list of PushType records. Calls `register-type` on each of the types in turn." [interpreter types] (reduce register-type interpreter types)) (defn register-modules "Takes an Interpreter record, and a list of modules. Calls `register-module` on each of those in turn." [interpreter modules] (reduce register-module interpreter modules)) (defn bind-value "Takes an interpreter, a keyword, and any item. If the keyword is already registered in the interpreter's :bindings hashmap, the item is pushed to that; otherwise, a new binding is made first. If the item is `nil`, the binding is created (if necessary) but nothing is pushed to the stack." [interpreter kwd item] (let [old-stack (get-in interpreter [:bindings kwd] '())] (assoc-in interpreter [:bindings kwd] (if (nil? item) old-stack (conj old-stack item) )))) (defn peek-at-binding "Takes an interpreter and a keyword. Returns the top item (if any) on the indicated :bindings stack, or `nil` if the keyword is not recognized or there are no items on the stack." [interpreter kwd] (first (get-in interpreter [:bindings kwd]))) (defn bind-input "If the arguments are an Interpreter, a keyword and any item, it will store the item under the keyword key in the Interpreter's :bindings hashmap, pushing the item onto the top of the indicated value stack. If no keyword is given, one is constructed automatically." ([interpreter item] (let [next-index (inc (count (:bindings interpreter))) next-key (keyword (str "input!" next-index))] (bind-value interpreter next-key item))) ([interpreter kwd item] (bind-value interpreter kwd item))) (defn bind-inputs "Takes an Interpreter record, and a hashmap of key-value items. If the interpreter already has some of the bindings assigned, the new values are pushed onto the old stacks." [interpreter values] (cond (vector? values) (reduce (partial bind-input) interpreter values) (map? values) (reduce-kv bind-input interpreter values) :else (throw (Exception. "cannot bind inputs")))) (defn bound-keyword? "Takes an interpreter, and a keyword, and returns true if the keyword is a key in the :bindings hashmap" [interpreter kwd] (contains? (:bindings interpreter) kwd)) (defn add-instruction "Takes an Interpreter and an Instruction (record), and adds the instruction to the :instructions registry of the interpreter, without checking for prior definitions." [interpreter instruction] (assoc-in interpreter [:instructions (:token instruction)] instruction)) (defn register-instruction "Takes an Interpreter and an Instruction, and attempts to add the Instruction to the :instructions map of the Interpreter, keyed by its `:token`." [interpreter instruction] (let [token (:token instruction) registry (:instructions interpreter)] (if (contains? registry token) (oops/throw-redefined-instruction-error token)) (add-instruction interpreter instruction))) (defn forget-instruction "Takes an Interpreter and a keyword (the name of an instruction, supposedly). Un-registers ('forgets') the instruction, returning the Interpreter" [interpreter kw] (let [old-instructions (:instructions interpreter)] (assoc interpreter :instructions (dissoc old-instructions kw)))) (defn reconfigure "takes an interpreter and a map of configuration pairs, and merges the map with the current interpreter map" [interpreter new-config] (let [old-config (:config interpreter)] (assoc interpreter :config (merge old-config new-config)))) (defn contains-at-least? the named stack exists, and has at least that many items on it" [interpreter stack limit] (<= limit (count (stack/get-stack interpreter stack)))) (defn recognizes-instruction? "Takes an Interpreter and an instruction token, and returns true if the token is registered." [interpreter token] (contains? (:instructions interpreter) token)) (defn ready-for-instruction? "Takes an Interpreter (with registered instructions) and a keyword instruction token, and returns true if the number of items on the stacks meets or exceeds all the specified :needs for that instruction. Returns false if the instruction is not registered." [interpreter token] (let [needs (get-in interpreter [:instructions token :needs] )] (and (recognizes-instruction? interpreter token) (reduce-kv (fn [truth k v] (and truth (contains-at-least? interpreter k v))) true needs)))) (defn get-instruction [interpreter token] (get-in interpreter [:instructions token])) (defn store-item-in-ARGS "Takes an Interpreter an a Push item. If the Interpreter's :store-args? :config state is `true`, it will bind the item passed in as the new [top] value in the :binding called `:ARGS`. Otherwise it has no effect." [interpreter item] (let [store? (get-in interpreter [:config :store-args?] false)] (if store? (bind-value interpreter :ARGS item) interpreter))) (defn append-item-to-exec "Takes an Interpreter an a Push item. If the Interpreter's :cycle-args? :config state is `true`, it will append the item passed in to the `:exec` stack. Otherwise it has no effect." [interpreter item] (let [cycle? (get-in interpreter [:config :cycle-args?] false) old-exec (stack/get-stack interpreter :exec)] (if cycle? (stack/set-stack interpreter :exec (reverse (into (reverse old-exec) (list item)))) interpreter))) (defn apply-instruction "Takes an interpreter and a token. Returns the interpreter. If the `:store-args?` value is `true` in the interpreter's `:config`, the arguments will be saved onto the `:ARGS` binding. If the `:cycle-args?` value is `true` in the interpreter's `:config`, the arguments will (also) be appended to the tail of `:exec`. NOTE: returns ONLY the interpreter, not the state tuple." [interpreter token] (let [updated ((:transaction (get-instruction interpreter token)) interpreter) args (scratch/scratch-read updated :ARGS)] (-> updated (store-item-in-ARGS , args) (append-item-to-exec , args) ))) (defn push-item "Takes an Interpreter, a stack name and a Clojure expression, and returns the Interpreter with the item pushed onto the specified stack. If the stack doesn't already exist, it is created. If the item is nil, no change occurs." [interpreter stack item] (if (nil? item) interpreter (let [old-stack (get-in interpreter [:stacks stack])] (assoc-in interpreter [:stacks stack] (conj old-stack item))))) (defn missing-args-message [interpreter token] (let [t (:counter interpreter)] {:step t :item (str token " missing arguments")})) (defn execute-instruction "Takes an Interpreter and a token, and executes the registered Instruction using the Interpreter as the (only) argument. Raises an exception if the token is not registered." [interpreter token] (let [unrecognized (not (recognizes-instruction? interpreter token)) ready (ready-for-instruction? interpreter token)] (cond unrecognized (oops/throw-unknown-instruction-error token) ready (apply-instruction interpreter token) :else (push-item interpreter :error (missing-args-message interpreter token))))) (defn load-items "Takes an Interpreter, a stack name, and a collection of items. Puts all the items onto the named stack, one at time (probably reversing them along the way." [interpreter stackname item-list] (let [old-stack (get-in interpreter [:stacks stackname]) new-stack (into old-stack (reverse item-list))] (stack/set-stack interpreter stackname new-stack))) (defn instruction? "takes an Interpreter and a keyword, and returns true if the keyword is a key of the :instructions registry in that Interpreter instance" [interpreter token] (contains? (:instructions interpreter) token)) (defn routers-see? "Takes an Interpreter and an item, and returns true if any of its :routers collection matches. NOTE: returns nil otherwise!" [interpreter item] (let [recognizers (:routers interpreter)] (boolean (some #(router/router-recognize? % item) recognizers)))) (defn route-item "Takes an Interpreter and an item it recognizes (which should be established upstream) and sends the item to the designated stack determined by the first matching router predicate." [interpreter item] (let [all-routers (:routers interpreter) active-router (first (filter #(router/router-recognize? % item) all-routers)) preprocessor (:preprocessor active-router) preprocessed-item (preprocessor item) target-stack (:target-stack active-router)] (push-item interpreter target-stack preprocessed-item))) (defn handle-unknown-item "Takes an Interpreter and an item. If the :config :lenient? flag is calls `throw-unknown-push-item-error`" [interpreter item] (if (keyword? item) (push-item interpreter :ref item) (if (get-in interpreter [:config :lenient?]) (push-item interpreter :unknown item) (oops/throw-unknown-push-item-error item)))) (defn handle-item "Takes an Interpreter and an item, and either recognizes and invokes a keyword registered in that Interpreter as an binding or instruction, or sends the item to the correct stack (if it exists). As a side-effect, the item being processed will be stored in `:current-item` in the Interpreter record." [naive-interpreter item] (let [interpreter (assoc naive-interpreter :current-item item)] (cond (keyword? item) (cond (bound-keyword? interpreter item) (if (get-in interpreter [:config :quote-refs?]) (push-item interpreter :ref item) (push-item interpreter :exec (peek-at-binding interpreter item))) (instruction? interpreter item) (execute-instruction interpreter item) :else (push-item interpreter :ref item)) (routers-see? interpreter item) (route-item interpreter item) (types/pushcode? item) (load-items interpreter :exec item) :else (handle-unknown-item interpreter item)))) (defn clear-all-stacks "removes all items from all stacks in an Interpreter" [interpreter] (let [stacklist (keys (:stacks interpreter))] (assoc interpreter :stacks (reduce #(assoc %1 %2 '()) {} stacklist)))) (defn push-program-to-code "when called, this copies the stored `:program` into the `:code` stack as a block" [interpreter] (push-item interpreter :code (seq (:program interpreter)))) (defn prep-code-stack "when called, this checks the :config of the interpreter and if :preload-code? is truthy it will copy the :program to a code block on top of the :code stack" [interpreter] (if (get-in interpreter [:config :preload-code?]) (push-program-to-code interpreter) interpreter)) (defn reset-interpreter "takes an Interpreter instance and: - sets the counter to 0 - clears all non-:exec stacks - puts the program onto the :exec stack" [interpreter] (-> interpreter (clear-all-stacks) (assoc , :counter 0) (load-items :exec (:program interpreter)) prep-code-stack)) (defn recycle-interpreter "takes an Interpreter instance, a program and new bindings; resets and runs the new setup" [interpreter program & {:keys [bindings] :or {bindings []}}] (-> interpreter (assoc , :program program) (assoc , :bindings {}) (bind-inputs , bindings) reset-interpreter)) (defn increment-counter "takes an Interpreter and increments its :counter (without otherwise changing it)" [interpreter] (update-in interpreter [:counter] inc)) (defn step-limit "reads the [:config :step-limit] value of an Interpreter; returns 0 if nil" [interpreter] (if-let [stop (get-in interpreter [:config :step-limit])] stop 0)) (defn is-done? "Takes and Interpreter and checks various halting conditions. Returns true if any is true. Does not change interpreter state." [interpreter] (let [limit (step-limit interpreter)] (or (and (empty? (stack/get-stack interpreter :exec)) (empty? (stack/get-stack interpreter :snapshot))) (>= (:counter interpreter) limit)))) (defn- set-doneness "Takes an interpreter and sets its :done? to the `is-done?` result" [interpreter] (assoc interpreter :done? (is-done? interpreter))) (defn- truncated-string [item length] (let [as-string (str item)] (if (< (count as-string) length) (subs as-string 0 (count as-string)) (str (subs as-string 0 length) "…")))) (defn log-routed-item "Takes an Interpreter and any item, and pushes a 'time-stamped' map of that item on the Interpreter's :log stack. The 'time-stamp' is the counter of the Interpreter when called." [interpreter item] (push-item interpreter :log {:step (:counter interpreter) :item (truncated-string item 32)})) (defn soft-snapshot-ending "Called when an Interpreter has an empty :exec stack but a stored :snapshot on that stack. Merges the stored stacks, keeps the persistent ones, combines the :exec stacks and puts the :return on top." [interpreter] (let [returns (stack/get-stack interpreter :return) current-exec (stack/get-stack interpreter :exec) snapshots (stack/get-stack interpreter :snapshot) retrieved (first snapshots) old-exec (:exec retrieved) new-exec (util/list! (concat (reverse returns) current-exec old-exec)) ] (-> (stack/merge-snapshot interpreter retrieved) (stack/set-stack , :exec new-exec) (stack/set-stack , :snapshot (pop snapshots)) (increment-counter ,) (log-routed-item , "SNAPSHOT STACK POPPED") (set-doneness ,)))) (defn step "Takes an Interpreter, pops one item off :exec, routes it to the router, increments the counter. If the :exec stack is empty, does nothing." [interpreter] (let [old-exec (stack/get-stack interpreter :exec)] (if-not (is-done? interpreter) (if (empty? old-exec) (soft-snapshot-ending interpreter) (let [next-item (first old-exec) new-exec (pop old-exec)] (-> interpreter (increment-counter) (stack/set-stack :exec new-exec) (handle-item next-item) (log-routed-item next-item) (set-doneness)))) interpreter))) (defn run-n "Takes an Interpreter, calls `reset` on it, and calls `step` on that reset state for `tick` iterations. Returns the Interpreter state at the end. Can be called for any non-negative integer `tick` value, regardless of halting state." [interpreter tick] (let [start (assoc-in (reset-interpreter interpreter) [:config :step-limit] tick)] (nth (iterate step start) tick))) (defn run-n-forgetfully "Takes an Interpreter, calls `reset` on it, and calls `step` on that reset state for `tick` iterations. Returns the Interpreter state at the end. Drops the head of the lazy recursion. Can be called for any non-negative integer `tick` value, regardless of halting state." [interpreter deadline] (loop [state (assoc-in (reset-interpreter interpreter) [:config :step-limit] deadline) time 0] (if (> time deadline) state (recur (step state) (inc time)) ))) (defn entire-run "Takes an Interpreter, calls `reset` on it, and returns a (lazy) seq containing all of the steps from the start to the specified end point." [interpreter tick] (let [start (assoc-in (reset-interpreter interpreter) [:config :step-limit] tick)] (take tick (iterate step start)))) (defn last-changed-step "Runs a program in the specified interpreter (with a reset) and returns the last step at which the stacks changed" [interpreter tick] (loop [i (assoc-in (reset-interpreter interpreter) [:config :step-limit] tick) stacks (:stacks i)] (if (or (>= (:counter i) tick) (is-done? i) (= (:stacks (step i)) stacks)) (step i) (recur (step i) (:stacks (step i)))))) (defn run-until-done "Takes an Interpreter, calls `reset` on it, and calls `step` on that reset state until :done? is true. Does not check for infinite loops." [interpreter] (let [start (reset-interpreter interpreter)] (first (filter is-done? (iterate step start)))))
46d591a4aa2ed1cfd0c4404815e77c1ede72211852bc0bd8eb9cc98a28d9e4a0
locusmath/locus
aut.clj
(ns locus.algebra.group.core.aut (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.copresheaf.structure.core.protocols :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.mapping.general.core.util :refer :all] [locus.set.copresheaf.bijection.core.object :refer :all] [locus.set.quiver.unary.core.morphism :refer :all] [locus.set.copresheaf.bijection.core.morphism :refer :all] [locus.set.quiver.diset.core.object :refer :all] [locus.set.quiver.diset.core.morphism :refer :all] [locus.algebra.category.hom.sethom :refer :all] [locus.algebra.category.hom.bhom :refer :all] [locus.algebra.category.hom.dhom :refer :all] [locus.algebra.category.hom.funhom :refer :all] [locus.algebra.commutative.semigroup.object :refer :all] [locus.algebra.semigroup.core.object :refer :all] [locus.algebra.semigroup.monoid.object :refer :all] [locus.algebra.group.core.object :refer :all] [locus.set.quiver.structure.core.protocols :refer :all]) (:import (locus.set.mapping.general.core.object SetFunction) (locus.set.quiver.diset.core.object Diset) (locus.set.copresheaf.bijection.core.object Bijection))) ; Let C be a category, then the set of all isomorphisms of C forms a wide subcategory called ; the underlying groupoid of C. It follows that every category has an underlying groupoid. ; The automorphism group of an object X in a category is the hom class Hom(X,X) of X ; in the underlying groupoid. It follows that the definition of automorphism groups involves two components : the enumeration theory of hom classes and the construction of ; underlying groupoids of categories. ; The special case of sets (defn set-automorphism-group [coll] (->Group (bijective-set-hom coll coll) (fn [[a b]] (compose a b)) (identity-function coll) invert-function)) ; Computation of automorphism groups by a multimethod (defmulti aut type) (defmethod aut :locus.set.logic.core.set/universal [coll] (set-automorphism-group coll)) (defmethod aut SetFunction [func] (->Monoid (function-isomorphisms func func) (fn [[a b]] (compose a b)) (identity-morphism func))) (defmethod aut Diset [pair] (->Monoid (diset-isomorphisms pair pair) (fn [[a b]] (compose a b)) (identity-morphism pair))) (defmethod aut Bijection [func] (->Monoid (bijection-isomorphisms func func) (fn [[a b]] (compose a b)) (identity-morphism func)))
null
https://raw.githubusercontent.com/locusmath/locus/b232579217be4e39458410893827a84d744168e4/src/clojure/locus/algebra/group/core/aut.clj
clojure
Let C be a category, then the set of all isomorphisms of C forms a wide subcategory called the underlying groupoid of C. It follows that every category has an underlying groupoid. The automorphism group of an object X in a category is the hom class Hom(X,X) of X in the underlying groupoid. It follows that the definition of automorphism groups involves underlying groupoids of categories. The special case of sets Computation of automorphism groups by a multimethod
(ns locus.algebra.group.core.aut (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.copresheaf.structure.core.protocols :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.mapping.general.core.util :refer :all] [locus.set.copresheaf.bijection.core.object :refer :all] [locus.set.quiver.unary.core.morphism :refer :all] [locus.set.copresheaf.bijection.core.morphism :refer :all] [locus.set.quiver.diset.core.object :refer :all] [locus.set.quiver.diset.core.morphism :refer :all] [locus.algebra.category.hom.sethom :refer :all] [locus.algebra.category.hom.bhom :refer :all] [locus.algebra.category.hom.dhom :refer :all] [locus.algebra.category.hom.funhom :refer :all] [locus.algebra.commutative.semigroup.object :refer :all] [locus.algebra.semigroup.core.object :refer :all] [locus.algebra.semigroup.monoid.object :refer :all] [locus.algebra.group.core.object :refer :all] [locus.set.quiver.structure.core.protocols :refer :all]) (:import (locus.set.mapping.general.core.object SetFunction) (locus.set.quiver.diset.core.object Diset) (locus.set.copresheaf.bijection.core.object Bijection))) two components : the enumeration theory of hom classes and the construction of (defn set-automorphism-group [coll] (->Group (bijective-set-hom coll coll) (fn [[a b]] (compose a b)) (identity-function coll) invert-function)) (defmulti aut type) (defmethod aut :locus.set.logic.core.set/universal [coll] (set-automorphism-group coll)) (defmethod aut SetFunction [func] (->Monoid (function-isomorphisms func func) (fn [[a b]] (compose a b)) (identity-morphism func))) (defmethod aut Diset [pair] (->Monoid (diset-isomorphisms pair pair) (fn [[a b]] (compose a b)) (identity-morphism pair))) (defmethod aut Bijection [func] (->Monoid (bijection-isomorphisms func func) (fn [[a b]] (compose a b)) (identity-morphism func)))
1bbca73211ac46995be004facbc517c2cc2d2ec6c4c59b6729df0234676ef521
xh4/web-toolkit
entity-file.lisp
(in-package :http) (defclass file-entity (entity) ((file :initarg :file :initform nil :reader entity-file))) (defmethod print-object ((entity file-entity) stream) (print-unreadable-object (entity stream :type t :identity t) (let ((pathname (entity-body entity))) (format stream "~S" pathname)))) (defun make-file-entity (pathname &key header status method uri version) (check-type pathname pathname) (when (directory-pathname-p pathname) (error "Pathname ~S should denote a file" pathname)) (let* ((file (make-instance 'file :pathname pathname)) (content-type (or (mime-type pathname) "application/octet-stream")) (content-length (or (file-size file) 0)) (last-modified (rfc-1123-date (file-modify-time file))) (status (or status (if (probe-file pathname) 200 404))) (body pathname)) (make-instance 'file-entity :status status :method method :uri uri :version version :header (header :content-type content-type :content-length content-length :last-modified last-modified header) :body body :file file)))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/http/entity-file.lisp
lisp
(in-package :http) (defclass file-entity (entity) ((file :initarg :file :initform nil :reader entity-file))) (defmethod print-object ((entity file-entity) stream) (print-unreadable-object (entity stream :type t :identity t) (let ((pathname (entity-body entity))) (format stream "~S" pathname)))) (defun make-file-entity (pathname &key header status method uri version) (check-type pathname pathname) (when (directory-pathname-p pathname) (error "Pathname ~S should denote a file" pathname)) (let* ((file (make-instance 'file :pathname pathname)) (content-type (or (mime-type pathname) "application/octet-stream")) (content-length (or (file-size file) 0)) (last-modified (rfc-1123-date (file-modify-time file))) (status (or status (if (probe-file pathname) 200 404))) (body pathname)) (make-instance 'file-entity :status status :method method :uri uri :version version :header (header :content-type content-type :content-length content-length :last-modified last-modified header) :body body :file file)))
a17cbdf421658f22865853375af11cce79b251d3acc5d5176684189766646dd6
wavewave/hxournal
EventConnect.hs
----------------------------------------------------------------------------- -- | -- Module : Application.HXournal.Coroutine.EventConnect Copyright : ( c ) 2011 , 2012 -- -- License : BSD3 Maintainer : < > -- Stability : experimental Portability : GHC -- ----------------------------------------------------------------------------- module Application.HXournal.Coroutine.EventConnect where import Graphics.UI.Gtk hiding (get,set,disconnect) import Application.HXournal.Type.Event import Application.HXournal.Type.Canvas import Application.HXournal.Type.XournalState import Application.HXournal.Device import Application.HXournal.Type.Coroutine import Application.HXournal.Accessor import qualified Control . Monad . State as St import Control.Applicative import Control.Monad.Trans import Control.Category import Data.Label import Prelude hiding ((.), id) -- | disconnect :: (WidgetClass w) => ConnectId w -> MainCoroutine () disconnect = liftIO . signalDisconnect -- | connectPenUp :: CanvasInfo a -> MainCoroutine (ConnectId DrawingArea) connectPenUp cinfo = do let cid = get canvasId cinfo canvas = get drawArea cinfo connPenUp canvas cid -- | connectPenMove :: CanvasInfo a -> MainCoroutine (ConnectId DrawingArea) connectPenMove cinfo = do let cid = get canvasId cinfo canvas = get drawArea cinfo connPenMove canvas cid -- | connPenMove :: (WidgetClass w) => w -> CanvasId -> MainCoroutine (ConnectId w) connPenMove c cid = do callbk <- get callBack <$> getSt dev <- get deviceList <$> getSt liftIO (c `on` motionNotifyEvent $ tryEvent $ do (_,p) <- getPointer dev liftIO (callbk (PenMove cid p))) -- | connPenUp :: (WidgetClass w) => w -> CanvasId -> MainCoroutine (ConnectId w) connPenUp c cid = do callbk <- get callBack <$> getSt dev <- get deviceList <$> getSt liftIO (c `on` buttonReleaseEvent $ tryEvent $ do (_,p) <- getPointer dev liftIO (callbk (PenMove cid p)))
null
https://raw.githubusercontent.com/wavewave/hxournal/b8eb538a2d1a474cc74bc0b5f5c7f251dafe75b9/lib/Application/HXournal/Coroutine/EventConnect.hs
haskell
--------------------------------------------------------------------------- | Module : Application.HXournal.Coroutine.EventConnect License : BSD3 Stability : experimental --------------------------------------------------------------------------- | | | | |
Copyright : ( c ) 2011 , 2012 Maintainer : < > Portability : GHC module Application.HXournal.Coroutine.EventConnect where import Graphics.UI.Gtk hiding (get,set,disconnect) import Application.HXournal.Type.Event import Application.HXournal.Type.Canvas import Application.HXournal.Type.XournalState import Application.HXournal.Device import Application.HXournal.Type.Coroutine import Application.HXournal.Accessor import qualified Control . Monad . State as St import Control.Applicative import Control.Monad.Trans import Control.Category import Data.Label import Prelude hiding ((.), id) disconnect :: (WidgetClass w) => ConnectId w -> MainCoroutine () disconnect = liftIO . signalDisconnect connectPenUp :: CanvasInfo a -> MainCoroutine (ConnectId DrawingArea) connectPenUp cinfo = do let cid = get canvasId cinfo canvas = get drawArea cinfo connPenUp canvas cid connectPenMove :: CanvasInfo a -> MainCoroutine (ConnectId DrawingArea) connectPenMove cinfo = do let cid = get canvasId cinfo canvas = get drawArea cinfo connPenMove canvas cid connPenMove :: (WidgetClass w) => w -> CanvasId -> MainCoroutine (ConnectId w) connPenMove c cid = do callbk <- get callBack <$> getSt dev <- get deviceList <$> getSt liftIO (c `on` motionNotifyEvent $ tryEvent $ do (_,p) <- getPointer dev liftIO (callbk (PenMove cid p))) connPenUp :: (WidgetClass w) => w -> CanvasId -> MainCoroutine (ConnectId w) connPenUp c cid = do callbk <- get callBack <$> getSt dev <- get deviceList <$> getSt liftIO (c `on` buttonReleaseEvent $ tryEvent $ do (_,p) <- getPointer dev liftIO (callbk (PenMove cid p)))
29d40bf04fa0ef6e20d87ff65ec2582b799d63d9cbec95fce5637922081497be
mroman42/mikrokosmos
Types.hs
module Stlc.Types ( Type (Tvar, Arrow, Times, Union, Unitty, Bottom) , typeinference , typeinfer , unify , applyctx , emptyctx , incrementindices , variables , normalizeTemplate , applynormalization , Top (Top) , Context , Variable , Substitution ) where import Control.Monad import Lambda import qualified Data.Map as Map -- | A type context is a map from deBruijn indices to types. Given -- any lambda variable as a deBruijn index, it returns its type. type Context = Map.Map Integer Type -- | A type variable is an integer. type Variable = Integer -- | A type substitution is a function that can be applied to any type -- to get a new one. type Substitution = Type -> Type | A type template is a free type variable or an arrow between two -- types; that is, the function type. data Type = Tvar Variable | Arrow Type Type | Times Type Type | Union Type Type | Unitty | Bottom deriving (Eq) instance Show Type where show (Tvar t) = typevariableNames !! fromInteger t show (Arrow a b) = showparens a ++ " → " ++ show b show (Times a b) = showparens a ++ " × " ++ showparens b show (Union a b) = showparens a ++ " + " ++ showparens b show Unitty = "⊤" show Bottom = "⊥" showparens :: Type -> String showparens (Tvar t) = show (Tvar t) showparens Unitty = show Unitty showparens Bottom = show Bottom showparens m = "(" ++ show m ++ ")" -- | Creates the substitution given by the change of a variable for -- the given type. subs :: Variable -> Type -> Substitution subs x typ (Tvar y) | x == y = typ | otherwise = Tvar y subs x typ (Arrow a b) = Arrow (subs x typ a) (subs x typ b) subs x typ (Times a b) = Times (subs x typ a) (subs x typ b) subs x typ (Union a b) = Union (subs x typ a) (subs x typ b) subs _ _ Unitty = Unitty subs _ _ Bottom = Bottom -- | Returns true if the given variable appears on the type. occurs :: Variable -> Type -> Bool occurs x (Tvar y) = x == y occurs x (Arrow a b) = occurs x a || occurs x b occurs x (Times a b) = occurs x a || occurs x b occurs x (Union a b) = occurs x a || occurs x b occurs _ Unitty = False occurs _ Bottom = False | two types with their most general unifier . Returns the substitution -- that transforms any of the types into the unifier. unify :: Type -> Type -> Maybe Substitution unify (Tvar x) (Tvar y) | x == y = Just id | otherwise = Just (subs x (Tvar y)) unify (Tvar x) b | occurs x b = Nothing | otherwise = Just (subs x b) unify a (Tvar y) | occurs y a = Nothing | otherwise = Just (subs y a) unify (Arrow a b) (Arrow c d) = unifypair (a,b) (c,d) unify (Times a b) (Times c d) = unifypair (a,b) (c,d) unify (Union a b) (Union c d) = unifypair (a, b) (c, d) unify Unitty Unitty = Just id unify Bottom Bottom = Just id unify _ _ = Nothing | a pair of types unifypair :: (Type,Type) -> (Type,Type) -> Maybe Substitution unifypair (a,b) (c,d) = do p <- unify b d q <- unify (p a) (p c) return (q . p) -- | Apply a substitution to all the types on a type context. applyctx :: Substitution -> Context -> Context applyctx = Map.map -- | The empty context. emptyctx :: Context emptyctx = Map.empty -- | Increments all the indices of a given context. It is useful for -- adapting the context to a new scope. incrementindices :: Context -> Context incrementindices = Map.mapKeys succ -- | Type inference algorithm. Infers a type from a given context and expression -- with a set of constraints represented by a unifier type. The result type must -- be unifiable with this given type. typeinfer :: [Variable] -- ^ List of fresh variables -> Context -- ^ Type context -> Exp -- ^ Lambda expression whose type has to be inferred -> Type -- ^ Constraint -> Maybe Substitution typeinfer [] _ _ _ = Nothing typeinfer [_] _ _ _ = Nothing typeinfer _ ctx (Var n) b | Map.member n ctx = do var <- Map.lookup n ctx unify var b | otherwise = Nothing typeinfer (x:vars) ctx (App p q) b = do sigma <- typeinfer (evens vars) ctx p (Arrow (Tvar x) b) tau <- typeinfer (odds vars) (applyctx sigma ctx) q (sigma (Tvar x)) return (tau . sigma) where odds [] = [] odds [_] = [] odds (_:e:xs) = e : odds xs evens [] = [] evens [e] = [e] evens (e:_:xs) = e : evens xs typeinfer (a:x:vars) ctx (Lambda p) b = do sigma <- unify b (Arrow (Tvar a) (Tvar x)) let nctx = applyctx sigma (Map.insert 1 (sigma $ Tvar a) (incrementindices ctx)) tau <- typeinfer vars nctx p (sigma $ Tvar x) return (tau . sigma) typeinfer (x:y:vars) ctx (Pair m n) a = do sigma <- unify a (Times (Tvar x) (Tvar y)) tau <- typeinfer (evens vars) (applyctx sigma ctx) m (sigma (Tvar x)) rho <- typeinfer (odds vars) (applyctx (tau . sigma) ctx) n (tau (sigma (Tvar y))) return (rho . tau . sigma) where odds [] = [] odds [_] = [] odds (_:e:xs) = e : odds xs evens [] = [] evens [e] = [e] evens (e:_:xs) = e : evens xs typeinfer (y:vars) ctx (Pi1 m) a = typeinfer vars ctx m (Times a (Tvar y)) typeinfer (x:vars) ctx (Pi2 m) b = typeinfer vars ctx m (Times (Tvar x) b) typeinfer (x:y:vars) ctx (Inl m) a = do sigma <- unify a (Union (Tvar x) (Tvar y)) tau <- typeinfer vars (applyctx sigma ctx) m (sigma (Tvar x)) return (tau . sigma) typeinfer (x:y:vars) ctx (Inr m) a = do sigma <- unify a (Union (Tvar x) (Tvar y)) tau <- typeinfer vars (applyctx sigma ctx) m (sigma (Tvar y)) return (tau . sigma) typeinfer (x:y:vars) ctx (Caseof m f g) a = do sigma <- typeinfer (third1 vars) ctx f (Arrow (Tvar x) a) tau <- typeinfer (third2 vars) (applyctx sigma ctx) g (Arrow (sigma $ Tvar y) (sigma a)) rho <- typeinfer (third3 vars) (applyctx (tau . sigma) ctx) m (Union (tau . sigma $ Tvar x) (tau . sigma $ Tvar y)) return (rho . tau . sigma) where third1 [] = [] third1 [_] = [] third1 [_,_] = [] third1 (_:_:e:xs) = e : third1 xs third2 [] = [] third2 [_] = [] third2 [_,e] = [e] third2 (_:e:_:xs) = e : third2 xs third3 [] = [] third3 [e] = [e] third3 [e,_] = [e] third3 (e:_:_:xs) = e : third3 xs typeinfer _ _ Unit a = unify Unitty a typeinfer vars ctx (Abort m) _ = typeinfer vars ctx m Bottom typeinfer vars ctx (Absurd m) a = do sigma <- unify Bottom a tau <- typeinfer vars (applyctx sigma ctx) m Bottom return (tau . sigma) -- | Type inference of a lambda expression. typeinference :: Exp -> Maybe Type typeinference e = normalize <$> (typeinfer variables emptyctx e (Tvar 0) <*> pure (Tvar 0)) -- | List of possible variable names. typevariableNames :: [String] typevariableNames = concatMap (`replicateM` ['A'..'Z']) [1..] -- | Infinite list of variables. variables :: [Variable] variables = [1..] -- | Substitutes a set of type variables on a type template for the smaller -- possible ones. normalizeTemplate :: Map.Map Integer Integer -> Integer -> Type -> (Map.Map Integer Integer, Integer) normalizeTemplate sub n (Tvar m) = case Map.lookup m sub of Just _ -> (sub, n) Nothing -> (Map.insert m n sub, succ n) normalizeTemplate sub n (Arrow a b) = let (nsub, nn) = normalizeTemplate sub n a in normalizeTemplate nsub nn b normalizeTemplate sub n (Times a b) = let (nsub, nn) = normalizeTemplate sub n a in normalizeTemplate nsub nn b normalizeTemplate sub n (Union a b) = let (nsub, nn) = normalizeTemplate sub n a in normalizeTemplate nsub nn b normalizeTemplate sub n Unitty = (sub, n) normalizeTemplate sub n Bottom = (sub, n) -- | Applies a set of variable substitutions to a type to normalize it. applynormalization :: Map.Map Integer Integer -> Type -> Type applynormalization sub (Tvar m) = case Map.lookup m sub of Just n -> Tvar n Nothing -> Tvar m applynormalization sub (Arrow a b) = Arrow (applynormalization sub a) (applynormalization sub b) applynormalization sub (Times a b) = Times (applynormalization sub a) (applynormalization sub b) applynormalization sub (Union a b) = Union (applynormalization sub a) (applynormalization sub b) applynormalization _ Unitty = Unitty applynormalization _ Bottom = Bottom | Normalizes a type , that is , substitutes the set of type variables for -- the smaller possible ones. normalize :: Type -> Type normalize t = applynormalization (fst $ normalizeTemplate Map.empty 0 t) t -- This is definitely not an easter egg newtype Top = Top Type instance Show Top where show (Top (Tvar t)) = typevariableNames !! fromInteger t show (Top (Arrow a Bottom)) = "(Ω∖" ++ showparensT (Top a) ++ ")ᴼ" show (Top (Arrow a b)) = "((Ω∖" ++ showparensT (Top a) ++ ") ∪ " ++ showparensT (Top b) ++ ")ᴼ" show (Top (Times a b)) = showparensT (Top a) ++ " ∩ " ++ showparensT (Top b) show (Top (Union a b)) = showparensT (Top a) ++ " ∪ " ++ showparensT (Top b) show (Top Unitty) = "Ω" show (Top Bottom) = "Ø" showparensT :: Top -> String showparensT (Top (Tvar t)) = show (Top (Tvar t)) showparensT (Top Unitty) = show (Top Unitty) showparensT (Top Bottom) = show (Top Bottom) showparensT (Top m) = "(" ++ show (Top m) ++ ")"
null
https://raw.githubusercontent.com/mroman42/mikrokosmos/fa3f9d5ebd9d62a6be44731ae867d020aa082a69/source/Stlc/Types.hs
haskell
| A type context is a map from deBruijn indices to types. Given any lambda variable as a deBruijn index, it returns its type. | A type variable is an integer. | A type substitution is a function that can be applied to any type to get a new one. types; that is, the function type. | Creates the substitution given by the change of a variable for the given type. | Returns true if the given variable appears on the type. that transforms any of the types into the unifier. | Apply a substitution to all the types on a type context. | The empty context. | Increments all the indices of a given context. It is useful for adapting the context to a new scope. | Type inference algorithm. Infers a type from a given context and expression with a set of constraints represented by a unifier type. The result type must be unifiable with this given type. ^ List of fresh variables ^ Type context ^ Lambda expression whose type has to be inferred ^ Constraint | Type inference of a lambda expression. | List of possible variable names. | Infinite list of variables. | Substitutes a set of type variables on a type template for the smaller possible ones. | Applies a set of variable substitutions to a type to normalize it. the smaller possible ones. This is definitely not an easter egg
module Stlc.Types ( Type (Tvar, Arrow, Times, Union, Unitty, Bottom) , typeinference , typeinfer , unify , applyctx , emptyctx , incrementindices , variables , normalizeTemplate , applynormalization , Top (Top) , Context , Variable , Substitution ) where import Control.Monad import Lambda import qualified Data.Map as Map type Context = Map.Map Integer Type type Variable = Integer type Substitution = Type -> Type | A type template is a free type variable or an arrow between two data Type = Tvar Variable | Arrow Type Type | Times Type Type | Union Type Type | Unitty | Bottom deriving (Eq) instance Show Type where show (Tvar t) = typevariableNames !! fromInteger t show (Arrow a b) = showparens a ++ " → " ++ show b show (Times a b) = showparens a ++ " × " ++ showparens b show (Union a b) = showparens a ++ " + " ++ showparens b show Unitty = "⊤" show Bottom = "⊥" showparens :: Type -> String showparens (Tvar t) = show (Tvar t) showparens Unitty = show Unitty showparens Bottom = show Bottom showparens m = "(" ++ show m ++ ")" subs :: Variable -> Type -> Substitution subs x typ (Tvar y) | x == y = typ | otherwise = Tvar y subs x typ (Arrow a b) = Arrow (subs x typ a) (subs x typ b) subs x typ (Times a b) = Times (subs x typ a) (subs x typ b) subs x typ (Union a b) = Union (subs x typ a) (subs x typ b) subs _ _ Unitty = Unitty subs _ _ Bottom = Bottom occurs :: Variable -> Type -> Bool occurs x (Tvar y) = x == y occurs x (Arrow a b) = occurs x a || occurs x b occurs x (Times a b) = occurs x a || occurs x b occurs x (Union a b) = occurs x a || occurs x b occurs _ Unitty = False occurs _ Bottom = False | two types with their most general unifier . Returns the substitution unify :: Type -> Type -> Maybe Substitution unify (Tvar x) (Tvar y) | x == y = Just id | otherwise = Just (subs x (Tvar y)) unify (Tvar x) b | occurs x b = Nothing | otherwise = Just (subs x b) unify a (Tvar y) | occurs y a = Nothing | otherwise = Just (subs y a) unify (Arrow a b) (Arrow c d) = unifypair (a,b) (c,d) unify (Times a b) (Times c d) = unifypair (a,b) (c,d) unify (Union a b) (Union c d) = unifypair (a, b) (c, d) unify Unitty Unitty = Just id unify Bottom Bottom = Just id unify _ _ = Nothing | a pair of types unifypair :: (Type,Type) -> (Type,Type) -> Maybe Substitution unifypair (a,b) (c,d) = do p <- unify b d q <- unify (p a) (p c) return (q . p) applyctx :: Substitution -> Context -> Context applyctx = Map.map emptyctx :: Context emptyctx = Map.empty incrementindices :: Context -> Context incrementindices = Map.mapKeys succ -> Maybe Substitution typeinfer [] _ _ _ = Nothing typeinfer [_] _ _ _ = Nothing typeinfer _ ctx (Var n) b | Map.member n ctx = do var <- Map.lookup n ctx unify var b | otherwise = Nothing typeinfer (x:vars) ctx (App p q) b = do sigma <- typeinfer (evens vars) ctx p (Arrow (Tvar x) b) tau <- typeinfer (odds vars) (applyctx sigma ctx) q (sigma (Tvar x)) return (tau . sigma) where odds [] = [] odds [_] = [] odds (_:e:xs) = e : odds xs evens [] = [] evens [e] = [e] evens (e:_:xs) = e : evens xs typeinfer (a:x:vars) ctx (Lambda p) b = do sigma <- unify b (Arrow (Tvar a) (Tvar x)) let nctx = applyctx sigma (Map.insert 1 (sigma $ Tvar a) (incrementindices ctx)) tau <- typeinfer vars nctx p (sigma $ Tvar x) return (tau . sigma) typeinfer (x:y:vars) ctx (Pair m n) a = do sigma <- unify a (Times (Tvar x) (Tvar y)) tau <- typeinfer (evens vars) (applyctx sigma ctx) m (sigma (Tvar x)) rho <- typeinfer (odds vars) (applyctx (tau . sigma) ctx) n (tau (sigma (Tvar y))) return (rho . tau . sigma) where odds [] = [] odds [_] = [] odds (_:e:xs) = e : odds xs evens [] = [] evens [e] = [e] evens (e:_:xs) = e : evens xs typeinfer (y:vars) ctx (Pi1 m) a = typeinfer vars ctx m (Times a (Tvar y)) typeinfer (x:vars) ctx (Pi2 m) b = typeinfer vars ctx m (Times (Tvar x) b) typeinfer (x:y:vars) ctx (Inl m) a = do sigma <- unify a (Union (Tvar x) (Tvar y)) tau <- typeinfer vars (applyctx sigma ctx) m (sigma (Tvar x)) return (tau . sigma) typeinfer (x:y:vars) ctx (Inr m) a = do sigma <- unify a (Union (Tvar x) (Tvar y)) tau <- typeinfer vars (applyctx sigma ctx) m (sigma (Tvar y)) return (tau . sigma) typeinfer (x:y:vars) ctx (Caseof m f g) a = do sigma <- typeinfer (third1 vars) ctx f (Arrow (Tvar x) a) tau <- typeinfer (third2 vars) (applyctx sigma ctx) g (Arrow (sigma $ Tvar y) (sigma a)) rho <- typeinfer (third3 vars) (applyctx (tau . sigma) ctx) m (Union (tau . sigma $ Tvar x) (tau . sigma $ Tvar y)) return (rho . tau . sigma) where third1 [] = [] third1 [_] = [] third1 [_,_] = [] third1 (_:_:e:xs) = e : third1 xs third2 [] = [] third2 [_] = [] third2 [_,e] = [e] third2 (_:e:_:xs) = e : third2 xs third3 [] = [] third3 [e] = [e] third3 [e,_] = [e] third3 (e:_:_:xs) = e : third3 xs typeinfer _ _ Unit a = unify Unitty a typeinfer vars ctx (Abort m) _ = typeinfer vars ctx m Bottom typeinfer vars ctx (Absurd m) a = do sigma <- unify Bottom a tau <- typeinfer vars (applyctx sigma ctx) m Bottom return (tau . sigma) typeinference :: Exp -> Maybe Type typeinference e = normalize <$> (typeinfer variables emptyctx e (Tvar 0) <*> pure (Tvar 0)) typevariableNames :: [String] typevariableNames = concatMap (`replicateM` ['A'..'Z']) [1..] variables :: [Variable] variables = [1..] normalizeTemplate :: Map.Map Integer Integer -> Integer -> Type -> (Map.Map Integer Integer, Integer) normalizeTemplate sub n (Tvar m) = case Map.lookup m sub of Just _ -> (sub, n) Nothing -> (Map.insert m n sub, succ n) normalizeTemplate sub n (Arrow a b) = let (nsub, nn) = normalizeTemplate sub n a in normalizeTemplate nsub nn b normalizeTemplate sub n (Times a b) = let (nsub, nn) = normalizeTemplate sub n a in normalizeTemplate nsub nn b normalizeTemplate sub n (Union a b) = let (nsub, nn) = normalizeTemplate sub n a in normalizeTemplate nsub nn b normalizeTemplate sub n Unitty = (sub, n) normalizeTemplate sub n Bottom = (sub, n) applynormalization :: Map.Map Integer Integer -> Type -> Type applynormalization sub (Tvar m) = case Map.lookup m sub of Just n -> Tvar n Nothing -> Tvar m applynormalization sub (Arrow a b) = Arrow (applynormalization sub a) (applynormalization sub b) applynormalization sub (Times a b) = Times (applynormalization sub a) (applynormalization sub b) applynormalization sub (Union a b) = Union (applynormalization sub a) (applynormalization sub b) applynormalization _ Unitty = Unitty applynormalization _ Bottom = Bottom | Normalizes a type , that is , substitutes the set of type variables for normalize :: Type -> Type normalize t = applynormalization (fst $ normalizeTemplate Map.empty 0 t) t newtype Top = Top Type instance Show Top where show (Top (Tvar t)) = typevariableNames !! fromInteger t show (Top (Arrow a Bottom)) = "(Ω∖" ++ showparensT (Top a) ++ ")ᴼ" show (Top (Arrow a b)) = "((Ω∖" ++ showparensT (Top a) ++ ") ∪ " ++ showparensT (Top b) ++ ")ᴼ" show (Top (Times a b)) = showparensT (Top a) ++ " ∩ " ++ showparensT (Top b) show (Top (Union a b)) = showparensT (Top a) ++ " ∪ " ++ showparensT (Top b) show (Top Unitty) = "Ω" show (Top Bottom) = "Ø" showparensT :: Top -> String showparensT (Top (Tvar t)) = show (Top (Tvar t)) showparensT (Top Unitty) = show (Top Unitty) showparensT (Top Bottom) = show (Top Bottom) showparensT (Top m) = "(" ++ show (Top m) ++ ")"
2ef400fc5d85bce762bfe2d8589c75edcd502bb8d01da27c84391c4e8958fb57
eareese/htdp-exercises
226-predicate-color-states.rkt
;;--------------------------------------------------------------------------------------------------- #lang htdp/bsl (require 2htdp/image) A FSM is one of : ; – '() – ( cons Transition FSM ) (define-struct transition [current next]) ; A Transition is a structure: ( make - transition FSM - State FSM - State ) FSM - State is a Color . interpretation A FSM represents the transitions that a finite state machine can take from one state to another ; in reaction to key strokes Exercise 226 . Design state= ? , an equality predicate for states . FSM - State FSM - State - > Boolean produces true if the two FSM - States are the same color (check-expect (state=? "blue" "blue") #t) (check-expect (state=? "blue" "Blue") #t) (check-expect (state=? "BLUE" "Blue") #t) (check-expect (state=? "blue" "green") #f) (define (state=? s1 s2) (and (image-color? s1) (image-color? s2) (string-ci=? s1 s2)))
null
https://raw.githubusercontent.com/eareese/htdp-exercises/a85ff3111d459dda0e94d9b463d01a09accbf9bf/part02-arbitrarily-large-data/226-predicate-color-states.rkt
racket
--------------------------------------------------------------------------------------------------- – '() A Transition is a structure: in reaction to key strokes
#lang htdp/bsl (require 2htdp/image) A FSM is one of : – ( cons Transition FSM ) (define-struct transition [current next]) ( make - transition FSM - State FSM - State ) FSM - State is a Color . interpretation A FSM represents the transitions that a finite state machine can take from one state to another Exercise 226 . Design state= ? , an equality predicate for states . FSM - State FSM - State - > Boolean produces true if the two FSM - States are the same color (check-expect (state=? "blue" "blue") #t) (check-expect (state=? "blue" "Blue") #t) (check-expect (state=? "BLUE" "Blue") #t) (check-expect (state=? "blue" "green") #f) (define (state=? s1 s2) (and (image-color? s1) (image-color? s2) (string-ci=? s1 s2)))
7ae7152c7b4c3232e79242cacde74e4b44b13c4dfc5c8ac4ef52d7bfc7517e91
well-typed-lightbulbs/ocaml-esp32
int.ml
(**************************************************************************) (* *) (* OCaml *) (* *) (* The OCaml programmers *) (* *) Copyright 2018 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) type t = int let zero = 0 let one = 1 let minus_one = -1 external neg : int -> int = "%negint" external add : int -> int -> int = "%addint" external sub : int -> int -> int = "%subint" external mul : int -> int -> int = "%mulint" external div : int -> int -> int = "%divint" external rem : int -> int -> int = "%modint" external succ : int -> int = "%succint" external pred : int -> int = "%predint" let abs x = if x >= 0 then x else -x let max_int = (-1) lsr 1 let min_int = max_int + 1 external logand : int -> int -> int = "%andint" external logor : int -> int -> int = "%orint" external logxor : int -> int -> int = "%xorint" let lognot x = logxor x (-1) external shift_left : int -> int -> int = "%lslint" external shift_right : int -> int -> int = "%asrint" external shift_right_logical : int -> int -> int = "%lsrint" let equal : int -> int -> bool = ( = ) let compare : int -> int -> int = Stdlib.compare external to_float : int -> float = "%floatofint" external of_float : float -> int = "%intoffloat" external int_of_string : string - > int = " caml_int_of_string " let of_string s = try Some ( ) with Failure _ - > None external int_of_string : string -> int = "caml_int_of_string" let of_string s = try Some (int_of_string s) with Failure _ -> None *) external format_int : string -> int -> string = "caml_format_int" let to_string x = format_int "%d" x
null
https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/stdlib/int.ml
ocaml
************************************************************************ OCaml The OCaml programmers en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************
Copyright 2018 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the type t = int let zero = 0 let one = 1 let minus_one = -1 external neg : int -> int = "%negint" external add : int -> int -> int = "%addint" external sub : int -> int -> int = "%subint" external mul : int -> int -> int = "%mulint" external div : int -> int -> int = "%divint" external rem : int -> int -> int = "%modint" external succ : int -> int = "%succint" external pred : int -> int = "%predint" let abs x = if x >= 0 then x else -x let max_int = (-1) lsr 1 let min_int = max_int + 1 external logand : int -> int -> int = "%andint" external logor : int -> int -> int = "%orint" external logxor : int -> int -> int = "%xorint" let lognot x = logxor x (-1) external shift_left : int -> int -> int = "%lslint" external shift_right : int -> int -> int = "%asrint" external shift_right_logical : int -> int -> int = "%lsrint" let equal : int -> int -> bool = ( = ) let compare : int -> int -> int = Stdlib.compare external to_float : int -> float = "%floatofint" external of_float : float -> int = "%intoffloat" external int_of_string : string - > int = " caml_int_of_string " let of_string s = try Some ( ) with Failure _ - > None external int_of_string : string -> int = "caml_int_of_string" let of_string s = try Some (int_of_string s) with Failure _ -> None *) external format_int : string -> int -> string = "caml_format_int" let to_string x = format_int "%d" x
bc99bc640333f2943a8c587c8d3adbb0b26f8f787d2f5aaa64e84621c5c39bed
ds-wizard/engine-backend
Detail_DELETE.hs
module Registry.Specs.API.Organization.Detail_DELETE ( detail_delete, ) where import Network.HTTP.Types import Network.Wai (Application) import Test.Hspec import Test.Hspec.Wai import Registry.Model.Context.AppContext import Registry.Specs.API.Common import SharedTest.Specs.API.Common -- ------------------------------------------------------------------------ -- DELETE /organizations/{orgId} -- ------------------------------------------------------------------------ detail_delete :: AppContext -> SpecWith ((), Application) detail_delete appContext = describe "DELETE /organizations/{orgId}" $ do test_204 appContext test_401 appContext test_403 appContext test_404 appContext -- ---------------------------------------------------- -- ---------------------------------------------------- -- ---------------------------------------------------- reqMethod = methodDelete reqUrl = "/organizations/global" reqHeaders = [reqAdminAuthHeader] reqBody = "" -- ---------------------------------------------------- -- ---------------------------------------------------- -- ---------------------------------------------------- test_204 appContext = it "HTTP 204 NO CONTENT" $ -- GIVEN: Prepare expectation do let expStatus = 204 let expHeaders = resCorsHeadersPlain -- WHEN: Call API response <- request reqMethod reqUrl reqHeaders reqBody -- THEN: Compare response with expectation assertEmptyResponse expStatus expHeaders response -- ---------------------------------------------------- -- ---------------------------------------------------- -- ---------------------------------------------------- test_401 appContext = createAuthTest reqMethod reqUrl [reqCtHeader] reqBody -- ---------------------------------------------------- -- ---------------------------------------------------- -- ---------------------------------------------------- test_403 appContext = createForbiddenTest reqMethod reqUrl [reqUserAuthHeader] reqBody "Detail Organization" -- ---------------------------------------------------- -- ---------------------------------------------------- -- ---------------------------------------------------- test_404 appContext = createNotFoundTest reqMethod "/organizations/nonexisting.organization" reqHeaders reqBody "organization" [("organization_id", "nonexisting.organization")]
null
https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-registry/test/Registry/Specs/API/Organization/Detail_DELETE.hs
haskell
------------------------------------------------------------------------ DELETE /organizations/{orgId} ------------------------------------------------------------------------ ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- GIVEN: Prepare expectation WHEN: Call API THEN: Compare response with expectation ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ----------------------------------------------------
module Registry.Specs.API.Organization.Detail_DELETE ( detail_delete, ) where import Network.HTTP.Types import Network.Wai (Application) import Test.Hspec import Test.Hspec.Wai import Registry.Model.Context.AppContext import Registry.Specs.API.Common import SharedTest.Specs.API.Common detail_delete :: AppContext -> SpecWith ((), Application) detail_delete appContext = describe "DELETE /organizations/{orgId}" $ do test_204 appContext test_401 appContext test_403 appContext test_404 appContext reqMethod = methodDelete reqUrl = "/organizations/global" reqHeaders = [reqAdminAuthHeader] reqBody = "" test_204 appContext = it "HTTP 204 NO CONTENT" $ do let expStatus = 204 let expHeaders = resCorsHeadersPlain response <- request reqMethod reqUrl reqHeaders reqBody assertEmptyResponse expStatus expHeaders response test_401 appContext = createAuthTest reqMethod reqUrl [reqCtHeader] reqBody test_403 appContext = createForbiddenTest reqMethod reqUrl [reqUserAuthHeader] reqBody "Detail Organization" test_404 appContext = createNotFoundTest reqMethod "/organizations/nonexisting.organization" reqHeaders reqBody "organization" [("organization_id", "nonexisting.organization")]
15cc5e006c9070c69a19d0efa70b5d181fa0facf6ff92b7adcf0170e0553837d
rtoy/cmucl
linux-os.lisp
;;; -*- Package: SYSTEM -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . ;;; (ext:file-comment "$Header: src/code/linux-os.lisp $") ;;; ;;; ********************************************************************** ;;; OS interface functions for CMUCL under Linux . ;;; Written and maintained mostly by and . , , and did stuff here , too . ;;; Derived from mach-os.lisp by (in-package "SYSTEM") (use-package "EXTENSIONS") (intl:textdomain "cmucl-linux-os") (export '(get-system-info get-page-size os-init)) (register-lisp-feature :linux) (register-lisp-feature :elf) (register-lisp-runtime-feature :executable) (setq *software-type* "Linux") ;;; Instead of reading /proc/version (which has some bugs with select ( ) in Linux kernel 2.6.x ) and instead of running uname -r , ;;; let's just get the info from uname(). (defun software-version () "Returns a string describing version of the supporting software." (multiple-value-bind (sysname nodename release version) (unix:unix-uname) (declare (ignore sysname nodename)) (concatenate 'string release " " version))) OS - Init initializes our operating - system interface . ;;; (defun os-init () nil) GET - SYSTEM - INFO -- Interface ;;; ;;; Return system time, user time and number of page faults. ;;; (defun get-system-info () (multiple-value-bind (err? utime stime maxrss ixrss idrss isrss minflt majflt) (unix:unix-getrusage unix:rusage_self) (declare (ignore maxrss ixrss idrss isrss minflt)) (unless err? (error (intl:gettext "Unix system call getrusage failed: ~A.") (unix:get-unix-error-msg utime))) (values utime stime majflt))) GET - PAGE - SIZE -- Interface ;;; ;;; Return the system page size. ;;; (defun get-page-size () (multiple-value-bind (val err) (unix:unix-getpagesize) (unless val (error (intl:gettext "Getpagesize failed: ~A") (unix:get-unix-error-msg err))) val))
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/code/linux-os.lisp
lisp
-*- Package: SYSTEM -*- ********************************************************************** ********************************************************************** Instead of reading /proc/version (which has some bugs with let's just get the info from uname(). Return system time, user time and number of page faults. Return the system page size.
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . (ext:file-comment "$Header: src/code/linux-os.lisp $") OS interface functions for CMUCL under Linux . Written and maintained mostly by and . , , and did stuff here , too . Derived from mach-os.lisp by (in-package "SYSTEM") (use-package "EXTENSIONS") (intl:textdomain "cmucl-linux-os") (export '(get-system-info get-page-size os-init)) (register-lisp-feature :linux) (register-lisp-feature :elf) (register-lisp-runtime-feature :executable) (setq *software-type* "Linux") select ( ) in Linux kernel 2.6.x ) and instead of running uname -r , (defun software-version () "Returns a string describing version of the supporting software." (multiple-value-bind (sysname nodename release version) (unix:unix-uname) (declare (ignore sysname nodename)) (concatenate 'string release " " version))) OS - Init initializes our operating - system interface . (defun os-init () nil) GET - SYSTEM - INFO -- Interface (defun get-system-info () (multiple-value-bind (err? utime stime maxrss ixrss idrss isrss minflt majflt) (unix:unix-getrusage unix:rusage_self) (declare (ignore maxrss ixrss idrss isrss minflt)) (unless err? (error (intl:gettext "Unix system call getrusage failed: ~A.") (unix:get-unix-error-msg utime))) (values utime stime majflt))) GET - PAGE - SIZE -- Interface (defun get-page-size () (multiple-value-bind (val err) (unix:unix-getpagesize) (unless val (error (intl:gettext "Getpagesize failed: ~A") (unix:get-unix-error-msg err))) val))
e9ae90503445a0b67aa31709427e535d6b3963b4e67ece8a43f5d1ba031944f7
clojurewerkz/support
io.clj
(ns clojurewerkz.support.io (:import com.google.common.io.Files)) (defn ^java.io.File create-temp-dir [] once we drop JDK 6 support , this can be ;; done via JDK 7's java.nio.files.Files that supports directory prefixes . MK . (Files/createTempDir))
null
https://raw.githubusercontent.com/clojurewerkz/support/33d28084829f6ccb6aed870a357fa6b53c57d2cc/src/clojure/clojurewerkz/support/io.clj
clojure
done via JDK 7's java.nio.files.Files that
(ns clojurewerkz.support.io (:import com.google.common.io.Files)) (defn ^java.io.File create-temp-dir [] once we drop JDK 6 support , this can be supports directory prefixes . MK . (Files/createTempDir))
61648c523015e8ec743da6e50ca960968804d342ff4816226ddfdecdcdc41ac6
biocad/math-grads
Interaction.hs
| Module that provides various functions for interaction with ' 's , -- 'EdgeList's and vertices themselves. -- module Math.Grads.Algo.Interaction ( -- * Vertex Functions -- areAdjacent , getEnds , getOtherEnd , getSharedVertex , getVertexAdjacent , getVertexIncident , getVertexIncidentIdx , haveSharedVertex , isIncident , (~=) , (/~=) -- * Edge Functions -- , matchEdges , getEdgeIncident -- * EdgeList Functions -- , doubleEdgeList , edgeListToMap , haveSharedEdge , sortBondList , getIndices ) where import Data.List (find, findIndices, intersect, sortOn) import Data.Map (Map) import qualified Data.Map as M import Data.Maybe (fromJust, isJust) import Math.Grads.Graph (EdgeList, GraphEdge, edgeType) import Math.Grads.Utils (nub) | Equality operator for ' 's . -- (~=) :: GraphEdge e1 -> GraphEdge e2 -> Bool (b, e, _) ~= (b', e', _) = (b == b' && e == e') || (b == e' && e == b') | Inequality operator for ' 's . -- (/~=) :: GraphEdge e1 -> GraphEdge e2 -> Bool b1 /~= b2 = not $ b1 ~= b2 | Checks that vertex with given index is incident to . -- isIncident :: GraphEdge e -> Int -> Bool isIncident (b, e, _) n = b == n || e == n -- | Find all edges in given 'EdgeList' that are incident to vertex with given index. -- getVertexIncident :: EdgeList e -> Int -> EdgeList e getVertexIncident bs n = filter (`isIncident` n) bs -- | Returns indices of edges in 'EdgeList' that are incident to vertex with given index. -- getVertexIncidentIdx :: EdgeList e -> Int -> [Int] getVertexIncidentIdx bs n = findIndices (`isIncident` n) bs | Returns index of vertex incident to given ' ' and different from passed index . -- getOtherEnd :: GraphEdge e -> Int -> Int getOtherEnd (b, e, _) n | b == n = e | e == n = b | otherwise = error "There is no such index in edge." -- | Finds in given 'EdgeList' all indices of vertices adjacent to given vertex. -- getVertexAdjacent :: EdgeList e -> Int -> [Int] getVertexAdjacent bs n = (`getOtherEnd` n) <$> getVertexIncident bs n | Checks whether two vertices with given indices are adjacent in given ' EdgeList ' . -- areAdjacent :: EdgeList e -> Int -> Int -> Bool areAdjacent bs n n' = n' `elem` getVertexAdjacent bs n | Retrieves indices of vertices that are being connected by given ' ' . -- getEnds :: GraphEdge e -> [Int] getEnds (b, e, _) = [b, e] | Checks that two edges have common vertex . -- haveSharedVertex :: GraphEdge e1 -> GraphEdge e2 -> Bool haveSharedVertex b1 b2 = isJust $ getSharedVertex b1 b2 | Gets shared common vertex of two edges . If edges do n't have common vertex , -- returns Nothing. -- getSharedVertex :: GraphEdge e1 -> GraphEdge e2 -> Maybe Int getSharedVertex b1 b2 | null is = Nothing | length is == 2 = Nothing | otherwise = Just $ head is where is = getEnds b1 `intersect` getEnds b2 -- | Find edges in 'EdgeList' which ordered pairs of indices, that they are connecting, -- are present in passed list of ordered pairs. -- matchEdges :: EdgeList e -> [(Int, Int)] -> EdgeList e matchEdges bonds = fmap (\(a, b) -> fromJust (find (~= (a, b, undefined)) bonds)) -- | Find all edges that are incident to edge in 'EdgeList' with given index. -- getEdgeIncident :: Ord e => EdgeList e -> Int -> EdgeList e getEdgeIncident bs n | n >= length bs = [] | otherwise = filter (/= (beg, end, typ)) $ getVertexIncident bs beg ++ getVertexIncident bs end where (beg, end, typ) = bs !! n -- | For every edge in 'EdgeList' add to that list an edge in opposite direction. -- doubleEdgeList :: EdgeList e -> EdgeList e doubleEdgeList = concatMap (\(a, b, t) -> [(a, b, t), (b, a, t)]) -- | Transforms 'EdgeList' into 'Map' that corresponds to adjacency list of undirected -- graph induced by these edges. -- edgeListToMap :: EdgeList e -> Map Int [Int] edgeListToMap bonds' = M.fromList (fmap (toVertex bonds) (getIndices bonds)) where bonds = doubleEdgeList bonds' toVertex :: EdgeList e -> Int -> (Int, [Int]) toVertex bs i = (i, concatMap (\(a, b, _) -> [a | b == i]) bs) | Checks that two ' EdgeList 's have common edge . -- haveSharedEdge :: Eq e => EdgeList e -> EdgeList e -> Bool haveSharedEdge b1 b2 = or $ fmap (`elem` b2) b1 -- | Sorting for 'EdgeList', that sorts edges on their type, then on index of their -- to (right) vertex, then on index of their from (left) vertex. -- sortBondList :: Ord e => EdgeList e -> EdgeList e sortBondList = sortOn left . sortOn right . sortOn edgeType where left (a, _, _) = a right (_, b, _) = b -- | Gets all vertices from 'EdgeList'. -- getIndices :: EdgeList e -> [Int] getIndices = nub . concatMap getEnds
null
https://raw.githubusercontent.com/biocad/math-grads/df7bdc48f86f57f3d011991c64188489e8d73bc1/src/Math/Grads/Algo/Interaction.hs
haskell
'EdgeList's and vertices themselves. * Vertex Functions * Edge Functions * EdgeList Functions | Find all edges in given 'EdgeList' that are incident to vertex with given index. | Returns indices of edges in 'EdgeList' that are incident to vertex with given index. | Finds in given 'EdgeList' all indices of vertices adjacent to given vertex. returns Nothing. | Find edges in 'EdgeList' which ordered pairs of indices, that they are connecting, are present in passed list of ordered pairs. | Find all edges that are incident to edge in 'EdgeList' with given index. | For every edge in 'EdgeList' add to that list an edge in opposite direction. | Transforms 'EdgeList' into 'Map' that corresponds to adjacency list of undirected graph induced by these edges. | Sorting for 'EdgeList', that sorts edges on their type, then on index of their to (right) vertex, then on index of their from (left) vertex. | Gets all vertices from 'EdgeList'.
| Module that provides various functions for interaction with ' 's , module Math.Grads.Algo.Interaction ( areAdjacent , getEnds , getOtherEnd , getSharedVertex , getVertexAdjacent , getVertexIncident , getVertexIncidentIdx , haveSharedVertex , isIncident , (~=) , (/~=) , matchEdges , getEdgeIncident , doubleEdgeList , edgeListToMap , haveSharedEdge , sortBondList , getIndices ) where import Data.List (find, findIndices, intersect, sortOn) import Data.Map (Map) import qualified Data.Map as M import Data.Maybe (fromJust, isJust) import Math.Grads.Graph (EdgeList, GraphEdge, edgeType) import Math.Grads.Utils (nub) | Equality operator for ' 's . (~=) :: GraphEdge e1 -> GraphEdge e2 -> Bool (b, e, _) ~= (b', e', _) = (b == b' && e == e') || (b == e' && e == b') | Inequality operator for ' 's . (/~=) :: GraphEdge e1 -> GraphEdge e2 -> Bool b1 /~= b2 = not $ b1 ~= b2 | Checks that vertex with given index is incident to . isIncident :: GraphEdge e -> Int -> Bool isIncident (b, e, _) n = b == n || e == n getVertexIncident :: EdgeList e -> Int -> EdgeList e getVertexIncident bs n = filter (`isIncident` n) bs getVertexIncidentIdx :: EdgeList e -> Int -> [Int] getVertexIncidentIdx bs n = findIndices (`isIncident` n) bs | Returns index of vertex incident to given ' ' and different from passed index . getOtherEnd :: GraphEdge e -> Int -> Int getOtherEnd (b, e, _) n | b == n = e | e == n = b | otherwise = error "There is no such index in edge." getVertexAdjacent :: EdgeList e -> Int -> [Int] getVertexAdjacent bs n = (`getOtherEnd` n) <$> getVertexIncident bs n | Checks whether two vertices with given indices are adjacent in given ' EdgeList ' . areAdjacent :: EdgeList e -> Int -> Int -> Bool areAdjacent bs n n' = n' `elem` getVertexAdjacent bs n | Retrieves indices of vertices that are being connected by given ' ' . getEnds :: GraphEdge e -> [Int] getEnds (b, e, _) = [b, e] | Checks that two edges have common vertex . haveSharedVertex :: GraphEdge e1 -> GraphEdge e2 -> Bool haveSharedVertex b1 b2 = isJust $ getSharedVertex b1 b2 | Gets shared common vertex of two edges . If edges do n't have common vertex , getSharedVertex :: GraphEdge e1 -> GraphEdge e2 -> Maybe Int getSharedVertex b1 b2 | null is = Nothing | length is == 2 = Nothing | otherwise = Just $ head is where is = getEnds b1 `intersect` getEnds b2 matchEdges :: EdgeList e -> [(Int, Int)] -> EdgeList e matchEdges bonds = fmap (\(a, b) -> fromJust (find (~= (a, b, undefined)) bonds)) getEdgeIncident :: Ord e => EdgeList e -> Int -> EdgeList e getEdgeIncident bs n | n >= length bs = [] | otherwise = filter (/= (beg, end, typ)) $ getVertexIncident bs beg ++ getVertexIncident bs end where (beg, end, typ) = bs !! n doubleEdgeList :: EdgeList e -> EdgeList e doubleEdgeList = concatMap (\(a, b, t) -> [(a, b, t), (b, a, t)]) edgeListToMap :: EdgeList e -> Map Int [Int] edgeListToMap bonds' = M.fromList (fmap (toVertex bonds) (getIndices bonds)) where bonds = doubleEdgeList bonds' toVertex :: EdgeList e -> Int -> (Int, [Int]) toVertex bs i = (i, concatMap (\(a, b, _) -> [a | b == i]) bs) | Checks that two ' EdgeList 's have common edge . haveSharedEdge :: Eq e => EdgeList e -> EdgeList e -> Bool haveSharedEdge b1 b2 = or $ fmap (`elem` b2) b1 sortBondList :: Ord e => EdgeList e -> EdgeList e sortBondList = sortOn left . sortOn right . sortOn edgeType where left (a, _, _) = a right (_, b, _) = b getIndices :: EdgeList e -> [Int] getIndices = nub . concatMap getEnds
29440083be7238330fc816fd19298d30c73166aab65ba253eedc7ea822a1d628
racket/macro-debugger
info.rkt
#lang info (define scribblings '(("macro-debugger.scrbl" () (tool-library)))) (define raco-commands '(("macro-stepper" (submod macro-debugger/stepper main) "explore expansion steps" #f)))
null
https://raw.githubusercontent.com/racket/macro-debugger/d4e2325e6d8eced81badf315048ff54f515110d5/macro-debugger/macro-debugger/info.rkt
racket
#lang info (define scribblings '(("macro-debugger.scrbl" () (tool-library)))) (define raco-commands '(("macro-stepper" (submod macro-debugger/stepper main) "explore expansion steps" #f)))
f4e56ce2dfade11b246140a185ec41a704dd7583a8afed1bd58523788024245e
MinaProtocol/mina
account_identifier.ml
* This file has been generated by the OCamlClientCodegen generator for openapi - generator . * * Generated by : -generator.tech * * Schema Account_identifier.t : The account_identifier uniquely identifies an account within a network . All fields in the account_identifier are utilized to determine this uniqueness ( including the metadata field , if populated ) . * This file has been generated by the OCamlClientCodegen generator for openapi-generator. * * Generated by: -generator.tech * * Schema Account_identifier.t : The account_identifier uniquely identifies an account within a network. All fields in the account_identifier are utilized to determine this uniqueness (including the metadata field, if populated). *) type t = { (* The address may be a cryptographic public key (or some encoding of it) or a provided username. *) address : string ; sub_account : Sub_account_identifier.t option [@default None] Blockchains that utilize a username model ( where the address is not a derivative of a cryptographic public key ) should specify the public ) owned by the address in metadata . metadata : Yojson.Safe.t option [@default None] } [@@deriving yojson { strict = false }, show, eq] (** The account_identifier uniquely identifies an account within a network. All fields in the account_identifier are utilized to determine this uniqueness (including the metadata field, if populated). *) let create (address : string) : t = { address; sub_account = None; metadata = None }
null
https://raw.githubusercontent.com/MinaProtocol/mina/a80b00221953c26ff158e7375a948b5fa9e7bd8b/src/lib/rosetta_models/account_identifier.ml
ocaml
The address may be a cryptographic public key (or some encoding of it) or a provided username. * The account_identifier uniquely identifies an account within a network. All fields in the account_identifier are utilized to determine this uniqueness (including the metadata field, if populated).
* This file has been generated by the OCamlClientCodegen generator for openapi - generator . * * Generated by : -generator.tech * * Schema Account_identifier.t : The account_identifier uniquely identifies an account within a network . All fields in the account_identifier are utilized to determine this uniqueness ( including the metadata field , if populated ) . * This file has been generated by the OCamlClientCodegen generator for openapi-generator. * * Generated by: -generator.tech * * Schema Account_identifier.t : The account_identifier uniquely identifies an account within a network. All fields in the account_identifier are utilized to determine this uniqueness (including the metadata field, if populated). *) type t = address : string ; sub_account : Sub_account_identifier.t option [@default None] Blockchains that utilize a username model ( where the address is not a derivative of a cryptographic public key ) should specify the public ) owned by the address in metadata . metadata : Yojson.Safe.t option [@default None] } [@@deriving yojson { strict = false }, show, eq] let create (address : string) : t = { address; sub_account = None; metadata = None }
79a02bc0af91c1db28803a070a90b97218372521d20962876be2aa133b05b9f6
fpco/ide-backend
GetOpt.hs
----------------------------------------------------------------------------- -- | Module : Distribution . Copyright : ( c ) 2002 - 2005 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Portability : portable -- -- This library provides facilities for parsing the command-line options in a standalone program . It is essentially a Haskell port of the GNU -- @getopt@ library. -- ----------------------------------------------------------------------------- < > Oct. 1996 ( small changes Dec. 1997 ) Two rather obscure features are missing : The Bash 2.0 non - option hack ( if you do n't already know it , you probably do n't want to hear about it ... ) and the recognition of long options with a single dash ( e.g. ' -help ' is recognised as ' --help ' , as long as there is no short option ' h ' ) . Other differences between GNU 's and this implementation : * To enforce a coherent description of options and arguments , there are explanation fields in the option / argument descriptor . * Error messages are now more informative , but no longer POSIX compliant ... :-( And a final advertisement : The GNU C implementation uses well over 1100 lines , we need only 195 here , including a 46 line example ! :-) Sven Panne <> Oct. 1996 (small changes Dec. 1997) Two rather obscure features are missing: The Bash 2.0 non-option hack (if you don't already know it, you probably don't want to hear about it...) and the recognition of long options with a single dash (e.g. '-help' is recognised as '--help', as long as there is no short option 'h'). Other differences between GNU's getopt and this implementation: * To enforce a coherent description of options and arguments, there are explanation fields in the option/argument descriptor. * Error messages are now more informative, but no longer POSIX compliant... :-( And a final Haskell advertisement: The GNU C implementation uses well over 1100 lines, we need only 195 here, including a 46 line example! :-) -} {-# OPTIONS_HADDOCK hide #-} module Distribution.GetOpt ( * getOpt, getOpt', usageInfo, ArgOrder(..), OptDescr(..), ArgDescr(..), -- * Example -- $example ) where import Data.List ( isPrefixOf, intercalate, find ) import Data.Maybe ( isJust ) -- |What to do with options following non-options data ArgOrder a ^ no option processing after first non - option | Permute -- ^ freely intersperse options and non-options | ReturnInOrder (String -> a) -- ^ wrap non-options into options | Each ' OptDescr ' describes a single option . The arguments to ' Option ' are : * list of short option characters * list of long option strings ( without \"--\ " ) * argument descriptor * explanation of option for user Each 'OptDescr' describes a single option. The arguments to 'Option' are: * list of short option characters * list of long option strings (without \"--\") * argument descriptor * explanation of option for user -} data OptDescr a = -- description of a single options: Option [Char] -- list of short option characters [String] -- list of long option strings (without "--") (ArgDescr a) -- argument descriptor String -- explanation of option for user -- |Describes whether an option takes an argument or not, and if so how the argument is injected into a value of type data ArgDescr a = NoArg a -- ^ no argument expected | ReqArg (String -> a) String -- ^ option requires argument | OptArg (Maybe String -> a) String -- ^ optional argument data OptKind a -- kind of cmd line arg (internal use only): = Opt a -- an option an un - recognized option | NonOpt String -- a non-option | EndOfOpts -- end-of-options marker (i.e. "--") | OptErr String -- something went wrong... -- | Return a string describing the usage of a command, derived from the header ( first argument ) and the options described by the second argument . usageInfo :: String -- header -> [OptDescr a] -- option descriptors -> String -- nicely formatted decription of options usageInfo header optDescr = unlines (header:table) where (ss,ls,ds) = unzip3 [ (intercalate ", " (map (fmtShort ad) sos) ,concatMap (fmtLong ad) (take 1 los) ,d) | Option sos los ad d <- optDescr ] ssWidth = (maximum . map length) ss lsWidth = (maximum . map length) ls dsWidth = 30 `max` (80 - (ssWidth + lsWidth + 3)) table = [ " " ++ padTo ssWidth so' ++ " " ++ padTo lsWidth lo' ++ " " ++ d' | (so,lo,d) <- zip3 ss ls ds , (so',lo',d') <- fmtOpt dsWidth so lo d ] padTo n x = take n (x ++ repeat ' ') fmtOpt :: Int -> String -> String -> String -> [(String, String, String)] fmtOpt descrWidth so lo descr = case wrapText descrWidth descr of [] -> [(so,lo,"")] (d:ds) -> (so,lo,d) : [ ("","",d') | d' <- ds ] fmtShort :: ArgDescr a -> Char -> String fmtShort (NoArg _ ) so = "-" ++ [so] fmtShort (ReqArg _ _) so = "-" ++ [so] fmtShort (OptArg _ _) so = "-" ++ [so] fmtLong :: ArgDescr a -> String -> String fmtLong (NoArg _ ) lo = "--" ++ lo fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]" wrapText :: Int -> String -> [String] wrapText width = map unwords . wrap 0 [] . words where wrap :: Int -> [String] -> [String] -> [[String]] wrap 0 [] (w:ws) | length w + 1 > width = wrap (length w) [w] ws wrap col line (w:ws) | col + length w + 1 > width = reverse line : wrap 0 [] (w:ws) wrap col line (w:ws) = let col' = col + length w + 1 in wrap col' (w:line) ws wrap _ [] [] = [] wrap _ line [] = [reverse line] | Process the command - line , and return the list of values that matched ( and those that didn\'t ) . The arguments are : * The order requirements ( see ' ArgOrder ' ) * The option descriptions ( see ' OptDescr ' ) * The actual command line arguments ( presumably got from ' System . Environment.getArgs ' ) . ' getOpt ' returns a triple consisting of the option arguments , a list of non - options , and a list of error messages . Process the command-line, and return the list of values that matched (and those that didn\'t). The arguments are: * The order requirements (see 'ArgOrder') * The option descriptions (see 'OptDescr') * The actual command line arguments (presumably got from 'System.Environment.getArgs'). 'getOpt' returns a triple consisting of the option arguments, a list of non-options, and a list of error messages. -} getOpt :: ArgOrder a -- non-option handling -> [OptDescr a] -- option descriptors -> [String] -- the command-line arguments -> ([a],[String],[String]) -- (options,non-options,error messages) getOpt ordering optDescr args = (os,xs,es ++ map errUnrec us) where (os,xs,us,es) = getOpt' ordering optDescr args {-| This is almost the same as 'getOpt', but returns a quadruple consisting of the option arguments, a list of non-options, a list of unrecognized options, and a list of error messages. -} getOpt' :: ArgOrder a -- non-option handling -> [OptDescr a] -- option descriptors -> [String] -- the command-line arguments -> ([a],[String], [String] ,[String]) -- (options,non-options,unrecognized,error messages) getOpt' _ _ [] = ([],[],[],[]) getOpt' ordering optDescr (arg:args) = procNextOpt opt ordering where procNextOpt (Opt o) _ = (o:os,xs,us,es) procNextOpt (UnreqOpt u) _ = (os,xs,u:us,es) procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[],[]) procNextOpt (NonOpt x) Permute = (os,x:xs,us,es) procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,us,es) procNextOpt EndOfOpts RequireOrder = ([],rest,[],[]) procNextOpt EndOfOpts Permute = ([],rest,[],[]) procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[],[]) procNextOpt (OptErr e) _ = (os,xs,us,e:es) (opt,rest) = getNext arg args optDescr (os,xs,us,es) = getOpt' ordering optDescr rest -- take a look at the next cmd line arg and decide what to do with it getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String]) getNext ('-':'-':[]) rest _ = (EndOfOpts,rest) getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr getNext a rest _ = (NonOpt a,rest) -- handle long option longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String]) longOpt ls rs optDescr = long ads arg rs where (opt,arg) = break (=='=') ls getWith p = [ o | o@(Option _ xs _ _) <- optDescr , isJust (find (p opt) xs)] exact = getWith (==) options = if null exact then getWith isPrefixOf else exact ads = [ ad | Option _ _ ad _ <- options ] optStr = "--" ++ opt long (_:_:_) _ rest = (errAmbig options optStr,rest) long [NoArg a ] [] rest = (Opt a,rest) long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest) long [ReqArg _ d] [] [] = (errReq d optStr,[]) long [ReqArg f _] [] (r:rest) = (Opt (f r),rest) long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest) long [OptArg f _] [] rest = (Opt (f Nothing),rest) long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest) long _ _ rest = (UnreqOpt ("--"++ls),rest) -- handle short option shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String]) shortOpt y ys rs optDescr = short ads ys rs where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, y == s ] ads = [ ad | Option _ _ ad _ <- options ] optStr = '-':[y] short (_:_:_) _ rest = (errAmbig options optStr,rest) short (NoArg a :_) [] rest = (Opt a,rest) short (NoArg a :_) xs rest = (Opt a,('-':xs):rest) short (ReqArg _ d:_) [] [] = (errReq d optStr,[]) short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest) short (ReqArg f _:_) xs rest = (Opt (f xs),rest) short (OptArg f _:_) [] rest = (Opt (f Nothing),rest) short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest) short [] [] rest = (UnreqOpt optStr,rest) short [] xs rest = (UnreqOpt (optStr++xs),rest) -- miscellaneous error formatting errAmbig :: [OptDescr a] -> String -> OptKind a errAmbig ods optStr = OptErr (usageInfo header ods) where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:" errReq :: String -> String -> OptKind a errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n") errUnrec :: String -> String errUnrec optStr = "unrecognized option `" ++ optStr ++ "'\n" errNoArg :: String -> OptKind a errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n") ----------------------------------------------------------------------------------------- -- and here a small and hopefully enlightening example : data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show options : : [ OptDescr Flag ] options = [ Option [ ' v ' ] [ " verbose " ] ( ) " verbosely list files " , Option [ ' V ' , ' ? ' ] [ " version","release " ] ( NoArg Version ) " show version info " , Option [ ' o ' ] [ " output " ] ( OptArg out " FILE " ) " use FILE for dump " , Option [ ' n ' ] [ " name " ] ( ReqArg Name " USER " ) " only dump USER 's files " ] out : : Maybe String - > Flag out Nothing = Output " stdout " out ( Just o ) = Output o test : : ArgOrder Flag - > [ String ] - > String test order cmdline = case getOpt order options cmdline of ( o , n , [ ] ) - > " options= " + + show o + + " args= " + + show n + + " \n " ( _ , _ , errs ) - > concat errs + + usageInfo header options where header = " Usage : foobar [ OPTION ... ] files ... " -- example runs : -- putStr ( test RequireOrder [ " foo","-v " ] ) -- = = > options= [ ] args=["foo " , " -v " ] -- putStr ( test Permute [ " foo","-v " ] ) -- = = > options=[Verbose ] args=["foo " ] -- putStr ( test ( ReturnInOrder Arg ) [ " foo","-v " ] ) -- = = > options=[Arg " foo " , [ ] -- putStr ( test Permute [ " foo","--","-v " ] ) -- = = > options= [ ] args=["foo " , " -v " ] -- putStr ( test Permute [ " -?o","--name","bar","--na = baz " ] ) -- = = > options=[Version , Output " stdout " , Name " bar " , Name " baz " ] args= [ ] -- putStr ( test Permute [ " --ver","foo " ] ) -- = = > option ` --ver ' is ambiguous ; could be one of : -- -v --verbose verbosely list files -- -V , - ? --version , --release show version info -- Usage : foobar [ OPTION ... ] files ... -- -v --verbose verbosely list files -- -V , - ? --version , --release show version info -- -o[FILE ] --output[=FILE ] use FILE for dump -- -n USER --name = USER only dump USER 's files ----------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------- -- and here a small and hopefully enlightening example: data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show options :: [OptDescr Flag] options = [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files", Option ['V','?'] ["version","release"] (NoArg Version) "show version info", Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump", Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"] out :: Maybe String -> Flag out Nothing = Output "stdout" out (Just o) = Output o test :: ArgOrder Flag -> [String] -> String test order cmdline = case getOpt order options cmdline of (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n" (_,_,errs) -> concat errs ++ usageInfo header options where header = "Usage: foobar [OPTION...] files..." -- example runs: -- putStr (test RequireOrder ["foo","-v"]) -- ==> options=[] args=["foo", "-v"] -- putStr (test Permute ["foo","-v"]) -- ==> options=[Verbose] args=["foo"] -- putStr (test (ReturnInOrder Arg) ["foo","-v"]) -- ==> options=[Arg "foo", Verbose] args=[] -- putStr (test Permute ["foo","--","-v"]) -- ==> options=[] args=["foo", "-v"] -- putStr (test Permute ["-?o","--name","bar","--na=baz"]) -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[] -- putStr (test Permute ["--ver","foo"]) -- ==> option `--ver' is ambiguous; could be one of: -- -v --verbose verbosely list files -- -V, -? --version, --release show version info -- Usage: foobar [OPTION...] files... -- -v --verbose verbosely list files -- -V, -? --version, --release show version info -- -o[FILE] --output[=FILE] use FILE for dump -- -n USER --name=USER only dump USER's files ----------------------------------------------------------------------------------------- -} $ example To hopefully illuminate the role of the different data structures , here\ 's the command - line options for a ( very simple ) compiler : > module where > > import Distribution . > import Data . Maybe ( fromMaybe ) > > data Flag > = Verbose | Version > | Input String | Output String | > deriving Show > > options : : [ OptDescr Flag ] > options = > [ Option [ ' v ' ] [ " verbose " ] ( ) " chatty output on stderr " > , Option [ ' V ' , ' ? ' ] [ " version " ] ( NoArg Version ) " show version number " > , Option [ ' o ' ] [ " output " ] ( OptArg outp " FILE " ) " output FILE " > , Option [ ' c ' ] [ ] ( OptArg inp " FILE " ) " input FILE " > , Option [ ' L ' ] [ " " ] ( ReqArg LibDir " DIR " ) " library directory " > ] > > , outp : : Maybe String - > Flag > outp = Output . fromMaybe " stdout " > inp = Input . fromMaybe " stdin " > > compilerOpts : : [ String ] - > IO ( [ Flag ] , [ String ] ) > compilerOpts argv = > case getOpt Permute options argv of > ( o , n , [ ] ) - > return ( o , n ) > ( _ , _ , errs ) - > ioError ( userError ( concat errs + + usageInfo header options ) ) > where header = " Usage : ic [ OPTION ... ] files ... " To hopefully illuminate the role of the different data structures, here\'s the command-line options for a (very simple) compiler: > module Opts where > > import Distribution.GetOpt > import Data.Maybe ( fromMaybe ) > > data Flag > = Verbose | Version > | Input String | Output String | LibDir String > deriving Show > > options :: [OptDescr Flag] > options = > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr" > , Option ['V','?'] ["version"] (NoArg Version) "show version number" > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE" > , Option ['c'] [] (OptArg inp "FILE") "input FILE" > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory" > ] > > inp,outp :: Maybe String -> Flag > outp = Output . fromMaybe "stdout" > inp = Input . fromMaybe "stdin" > > compilerOpts :: [String] -> IO ([Flag], [String]) > compilerOpts argv = > case getOpt Permute options argv of > (o,n,[] ) -> return (o,n) > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) > where header = "Usage: ic [OPTION...] files..." -}
null
https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend/TestSuite/inputs/Cabal-1.22.0.0/Distribution/GetOpt.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Portability : portable This library provides facilities for parsing the command-line options @getopt@ library. --------------------------------------------------------------------------- help ' , as long as there is no short help', as long as there is no short # OPTIONS_HADDOCK hide # * Example $example |What to do with options following non-options ^ freely intersperse options and non-options ^ wrap non-options into options description of a single options: list of short option characters list of long option strings (without "--") argument descriptor explanation of option for user |Describes whether an option takes an argument or not, and if so ^ no argument expected ^ option requires argument ^ optional argument kind of cmd line arg (internal use only): an option a non-option end-of-options marker (i.e. "--") something went wrong... | Return a string describing the usage of a command, derived from header option descriptors nicely formatted decription of options non-option handling option descriptors the command-line arguments (options,non-options,error messages) | This is almost the same as 'getOpt', but returns a quadruple consisting of the option arguments, a list of non-options, a list of unrecognized options, and a list of error messages. non-option handling option descriptors the command-line arguments (options,non-options,unrecognized,error messages) take a look at the next cmd line arg and decide what to do with it handle long option handle short option miscellaneous error formatting --------------------------------------------------------------------------------------- and here a small and hopefully enlightening example : example runs : putStr ( test RequireOrder [ " foo","-v " ] ) = = > options= [ ] args=["foo " , " -v " ] putStr ( test Permute [ " foo","-v " ] ) = = > options=[Verbose ] args=["foo " ] putStr ( test ( ReturnInOrder Arg ) [ " foo","-v " ] ) = = > options=[Arg " foo " , [ ] putStr ( test Permute [ " foo","--","-v " ] ) = = > options= [ ] args=["foo " , " -v " ] putStr ( test Permute [ " -?o","--name","bar","--na = baz " ] ) = = > options=[Version , Output " stdout " , Name " bar " , Name " baz " ] args= [ ] putStr ( test Permute [ " --ver","foo " ] ) = = > option ` --ver ' is ambiguous ; could be one of : -v --verbose verbosely list files -V , - ? --version , --release show version info Usage : foobar [ OPTION ... ] files ... -v --verbose verbosely list files -V , - ? --version , --release show version info -o[FILE ] --output[=FILE ] use FILE for dump -n USER --name = USER only dump USER 's files --------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------- and here a small and hopefully enlightening example: example runs: putStr (test RequireOrder ["foo","-v"]) ==> options=[] args=["foo", "-v"] putStr (test Permute ["foo","-v"]) ==> options=[Verbose] args=["foo"] putStr (test (ReturnInOrder Arg) ["foo","-v"]) ==> options=[Arg "foo", Verbose] args=[] putStr (test Permute ["foo","--","-v"]) ==> options=[] args=["foo", "-v"] putStr (test Permute ["-?o","--name","bar","--na=baz"]) ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[] putStr (test Permute ["--ver","foo"]) ==> option `--ver' is ambiguous; could be one of: -v --verbose verbosely list files -V, -? --version, --release show version info Usage: foobar [OPTION...] files... -v --verbose verbosely list files -V, -? --version, --release show version info -o[FILE] --output[=FILE] use FILE for dump -n USER --name=USER only dump USER's files ---------------------------------------------------------------------------------------
Module : Distribution . Copyright : ( c ) 2002 - 2005 in a standalone program . It is essentially a Haskell port of the GNU < > Oct. 1996 ( small changes Dec. 1997 ) Two rather obscure features are missing : The Bash 2.0 non - option hack ( if you do n't already know it , you probably do n't want to hear about it ... ) and the recognition of long options with a single dash option ' h ' ) . Other differences between GNU 's and this implementation : * To enforce a coherent description of options and arguments , there are explanation fields in the option / argument descriptor . * Error messages are now more informative , but no longer POSIX compliant ... :-( And a final advertisement : The GNU C implementation uses well over 1100 lines , we need only 195 here , including a 46 line example ! :-) Sven Panne <> Oct. 1996 (small changes Dec. 1997) Two rather obscure features are missing: The Bash 2.0 non-option hack (if you don't already know it, you probably don't want to hear about it...) and the recognition of long options with a single dash option 'h'). Other differences between GNU's getopt and this implementation: * To enforce a coherent description of options and arguments, there are explanation fields in the option/argument descriptor. * Error messages are now more informative, but no longer POSIX compliant... :-( And a final Haskell advertisement: The GNU C implementation uses well over 1100 lines, we need only 195 here, including a 46 line example! :-) -} module Distribution.GetOpt ( * getOpt, getOpt', usageInfo, ArgOrder(..), OptDescr(..), ArgDescr(..), ) where import Data.List ( isPrefixOf, intercalate, find ) import Data.Maybe ( isJust ) data ArgOrder a ^ no option processing after first non - option | Each ' OptDescr ' describes a single option . The arguments to ' Option ' are : * list of short option characters * list of long option strings ( without \"--\ " ) * argument descriptor * explanation of option for user Each 'OptDescr' describes a single option. The arguments to 'Option' are: * list of short option characters * list of long option strings (without \"--\") * argument descriptor * explanation of option for user -} how the argument is injected into a value of type data ArgDescr a an un - recognized option the header ( first argument ) and the options described by the second argument . usageInfo header optDescr = unlines (header:table) where (ss,ls,ds) = unzip3 [ (intercalate ", " (map (fmtShort ad) sos) ,concatMap (fmtLong ad) (take 1 los) ,d) | Option sos los ad d <- optDescr ] ssWidth = (maximum . map length) ss lsWidth = (maximum . map length) ls dsWidth = 30 `max` (80 - (ssWidth + lsWidth + 3)) table = [ " " ++ padTo ssWidth so' ++ " " ++ padTo lsWidth lo' ++ " " ++ d' | (so,lo,d) <- zip3 ss ls ds , (so',lo',d') <- fmtOpt dsWidth so lo d ] padTo n x = take n (x ++ repeat ' ') fmtOpt :: Int -> String -> String -> String -> [(String, String, String)] fmtOpt descrWidth so lo descr = case wrapText descrWidth descr of [] -> [(so,lo,"")] (d:ds) -> (so,lo,d) : [ ("","",d') | d' <- ds ] fmtShort :: ArgDescr a -> Char -> String fmtShort (NoArg _ ) so = "-" ++ [so] fmtShort (ReqArg _ _) so = "-" ++ [so] fmtShort (OptArg _ _) so = "-" ++ [so] fmtLong :: ArgDescr a -> String -> String fmtLong (NoArg _ ) lo = "--" ++ lo fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]" wrapText :: Int -> String -> [String] wrapText width = map unwords . wrap 0 [] . words where wrap :: Int -> [String] -> [String] -> [[String]] wrap 0 [] (w:ws) | length w + 1 > width = wrap (length w) [w] ws wrap col line (w:ws) | col + length w + 1 > width = reverse line : wrap 0 [] (w:ws) wrap col line (w:ws) = let col' = col + length w + 1 in wrap col' (w:line) ws wrap _ [] [] = [] wrap _ line [] = [reverse line] | Process the command - line , and return the list of values that matched ( and those that didn\'t ) . The arguments are : * The order requirements ( see ' ArgOrder ' ) * The option descriptions ( see ' OptDescr ' ) * The actual command line arguments ( presumably got from ' System . Environment.getArgs ' ) . ' getOpt ' returns a triple consisting of the option arguments , a list of non - options , and a list of error messages . Process the command-line, and return the list of values that matched (and those that didn\'t). The arguments are: * The order requirements (see 'ArgOrder') * The option descriptions (see 'OptDescr') * The actual command line arguments (presumably got from 'System.Environment.getArgs'). 'getOpt' returns a triple consisting of the option arguments, a list of non-options, and a list of error messages. -} getOpt ordering optDescr args = (os,xs,es ++ map errUnrec us) where (os,xs,us,es) = getOpt' ordering optDescr args getOpt' _ _ [] = ([],[],[],[]) getOpt' ordering optDescr (arg:args) = procNextOpt opt ordering where procNextOpt (Opt o) _ = (o:os,xs,us,es) procNextOpt (UnreqOpt u) _ = (os,xs,u:us,es) procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[],[]) procNextOpt (NonOpt x) Permute = (os,x:xs,us,es) procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,us,es) procNextOpt EndOfOpts RequireOrder = ([],rest,[],[]) procNextOpt EndOfOpts Permute = ([],rest,[],[]) procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[],[]) procNextOpt (OptErr e) _ = (os,xs,us,e:es) (opt,rest) = getNext arg args optDescr (os,xs,us,es) = getOpt' ordering optDescr rest getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String]) getNext ('-':'-':[]) rest _ = (EndOfOpts,rest) getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr getNext a rest _ = (NonOpt a,rest) longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String]) longOpt ls rs optDescr = long ads arg rs where (opt,arg) = break (=='=') ls getWith p = [ o | o@(Option _ xs _ _) <- optDescr , isJust (find (p opt) xs)] exact = getWith (==) options = if null exact then getWith isPrefixOf else exact ads = [ ad | Option _ _ ad _ <- options ] optStr = "--" ++ opt long (_:_:_) _ rest = (errAmbig options optStr,rest) long [NoArg a ] [] rest = (Opt a,rest) long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest) long [ReqArg _ d] [] [] = (errReq d optStr,[]) long [ReqArg f _] [] (r:rest) = (Opt (f r),rest) long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest) long [OptArg f _] [] rest = (Opt (f Nothing),rest) long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest) long _ _ rest = (UnreqOpt ("--"++ls),rest) shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String]) shortOpt y ys rs optDescr = short ads ys rs where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, y == s ] ads = [ ad | Option _ _ ad _ <- options ] optStr = '-':[y] short (_:_:_) _ rest = (errAmbig options optStr,rest) short (NoArg a :_) [] rest = (Opt a,rest) short (NoArg a :_) xs rest = (Opt a,('-':xs):rest) short (ReqArg _ d:_) [] [] = (errReq d optStr,[]) short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest) short (ReqArg f _:_) xs rest = (Opt (f xs),rest) short (OptArg f _:_) [] rest = (Opt (f Nothing),rest) short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest) short [] [] rest = (UnreqOpt optStr,rest) short [] xs rest = (UnreqOpt (optStr++xs),rest) errAmbig :: [OptDescr a] -> String -> OptKind a errAmbig ods optStr = OptErr (usageInfo header ods) where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:" errReq :: String -> String -> OptKind a errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n") errUnrec :: String -> String errUnrec optStr = "unrecognized option `" ++ optStr ++ "'\n" errNoArg :: String -> OptKind a errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n") data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show options : : [ OptDescr Flag ] options = [ Option [ ' v ' ] [ " verbose " ] ( ) " verbosely list files " , Option [ ' V ' , ' ? ' ] [ " version","release " ] ( NoArg Version ) " show version info " , Option [ ' o ' ] [ " output " ] ( OptArg out " FILE " ) " use FILE for dump " , Option [ ' n ' ] [ " name " ] ( ReqArg Name " USER " ) " only dump USER 's files " ] out : : Maybe String - > Flag out Nothing = Output " stdout " out ( Just o ) = Output o test : : ArgOrder Flag - > [ String ] - > String test order cmdline = case getOpt order options cmdline of ( o , n , [ ] ) - > " options= " + + show o + + " args= " + + show n + + " \n " ( _ , _ , errs ) - > concat errs + + usageInfo header options where header = " Usage : foobar [ OPTION ... ] files ... " data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show options :: [OptDescr Flag] options = [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files", Option ['V','?'] ["version","release"] (NoArg Version) "show version info", Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump", Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"] out :: Maybe String -> Flag out Nothing = Output "stdout" out (Just o) = Output o test :: ArgOrder Flag -> [String] -> String test order cmdline = case getOpt order options cmdline of (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n" (_,_,errs) -> concat errs ++ usageInfo header options where header = "Usage: foobar [OPTION...] files..." -} $ example To hopefully illuminate the role of the different data structures , here\ 's the command - line options for a ( very simple ) compiler : > module where > > import Distribution . > import Data . Maybe ( fromMaybe ) > > data Flag > = Verbose | Version > | Input String | Output String | > deriving Show > > options : : [ OptDescr Flag ] > options = > [ Option [ ' v ' ] [ " verbose " ] ( ) " chatty output on stderr " > , Option [ ' V ' , ' ? ' ] [ " version " ] ( NoArg Version ) " show version number " > , Option [ ' o ' ] [ " output " ] ( OptArg outp " FILE " ) " output FILE " > , Option [ ' c ' ] [ ] ( OptArg inp " FILE " ) " input FILE " > , Option [ ' L ' ] [ " " ] ( ReqArg LibDir " DIR " ) " library directory " > ] > > , outp : : Maybe String - > Flag > outp = Output . fromMaybe " stdout " > inp = Input . fromMaybe " stdin " > > compilerOpts : : [ String ] - > IO ( [ Flag ] , [ String ] ) > compilerOpts argv = > case getOpt Permute options argv of > ( o , n , [ ] ) - > return ( o , n ) > ( _ , _ , errs ) - > ioError ( userError ( concat errs + + usageInfo header options ) ) > where header = " Usage : ic [ OPTION ... ] files ... " To hopefully illuminate the role of the different data structures, here\'s the command-line options for a (very simple) compiler: > module Opts where > > import Distribution.GetOpt > import Data.Maybe ( fromMaybe ) > > data Flag > = Verbose | Version > | Input String | Output String | LibDir String > deriving Show > > options :: [OptDescr Flag] > options = > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr" > , Option ['V','?'] ["version"] (NoArg Version) "show version number" > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE" > , Option ['c'] [] (OptArg inp "FILE") "input FILE" > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory" > ] > > inp,outp :: Maybe String -> Flag > outp = Output . fromMaybe "stdout" > inp = Input . fromMaybe "stdin" > > compilerOpts :: [String] -> IO ([Flag], [String]) > compilerOpts argv = > case getOpt Permute options argv of > (o,n,[] ) -> return (o,n) > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) > where header = "Usage: ic [OPTION...] files..." -}
7b840535be32cbd57f8d965f369f9fdefd6f92283ff55e6eb4dfac5a4d665ee8
change-metrics/monocle
Auth.hs
# LANGUAGE DataKinds # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeApplications # # LANGUAGE NoGeneralisedNewtypeDeriving # # OPTIONS_GHC -fno - warn - missing - export - lists # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # -- | Generated by Haskell protocol buffer compiler. DO NOT EDIT! module Monocle.Protob.Auth where import Control.Applicative ((<$>), (<*>), (<|>)) import Control.Applicative qualified as Hs import Control.DeepSeq qualified as Hs import Control.Monad qualified as Hs import Data.ByteString qualified as Hs import Data.Coerce qualified as Hs import Data.Int qualified as Hs (Int16, Int32, Int64) import Data.List.NonEmpty qualified as Hs (NonEmpty (..)) import Data.Map qualified as Hs (Map, mapKeysMonotonic) import Data.Proxy qualified as Proxy import Data.String qualified as Hs (fromString) import Data.Text.Lazy qualified as Hs (Text) import Data.Vector qualified as Hs (Vector) import Data.Word qualified as Hs (Word16, Word32, Word64) import GHC.Enum qualified as Hs import GHC.Generics qualified as Hs import Proto3.Suite.Class qualified as HsProtobuf import Proto3.Suite.DotProto qualified as HsProtobuf import Proto3.Suite.JSONPB ((.:), (.=)) import Proto3.Suite.JSONPB qualified as HsJSONPB import Proto3.Suite.Types qualified as HsProtobuf import Proto3.Wire qualified as HsProtobuf import Unsafe.Coerce qualified as Hs import Prelude qualified as Hs newtype GetMagicJwtRequest = GetMagicJwtRequest { getMagicJwtRequestToken :: Hs.Text } deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named GetMagicJwtRequest where nameOf _ = (Hs.fromString "GetMagicJwtRequest") instance HsProtobuf.HasDefault GetMagicJwtRequest instance HsProtobuf.Message GetMagicJwtRequest where encodeMessage _ GetMagicJwtRequest { getMagicJwtRequestToken = getMagicJwtRequestToken } = ( Hs.mconcat [ ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 1) getMagicJwtRequestToken ) ] ) decodeMessage _ = (Hs.pure GetMagicJwtRequest) <*> ( HsProtobuf.at HsProtobuf.decodeMessageField (HsProtobuf.FieldNumber 1) ) dotProto _ = [ ( HsProtobuf.DotProtoField (HsProtobuf.FieldNumber 1) (HsProtobuf.Prim HsProtobuf.String) (HsProtobuf.Single "token") [] "" ) ] instance HsJSONPB.ToJSONPB GetMagicJwtRequest where toJSONPB (GetMagicJwtRequest f1) = (HsJSONPB.object ["token" .= f1]) toEncodingPB (GetMagicJwtRequest f1) = (HsJSONPB.pairs ["token" .= f1]) instance HsJSONPB.FromJSONPB GetMagicJwtRequest where parseJSONPB = ( HsJSONPB.withObject "GetMagicJwtRequest" (\obj -> (Hs.pure GetMagicJwtRequest) <*> obj .: "token") ) instance HsJSONPB.ToJSON GetMagicJwtRequest where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON GetMagicJwtRequest where parseJSON = HsJSONPB.parseJSONPB data GetMagicJwtError = GetMagicJwtErrorInvalidAdminToken | GetMagicJwtErrorMagicTokenDisabled | GetMagicJwtErrorMagicTokenCreateError deriving (Hs.Show, Hs.Eq, Hs.Generic, Hs.NFData) instance HsProtobuf.Named GetMagicJwtError where nameOf _ = (Hs.fromString "GetMagicJwtError") instance HsProtobuf.HasDefault GetMagicJwtError instance Hs.Bounded GetMagicJwtError where minBound = GetMagicJwtErrorInvalidAdminToken maxBound = GetMagicJwtErrorMagicTokenCreateError instance Hs.Ord GetMagicJwtError where compare x y = Hs.compare (HsProtobuf.fromProtoEnum x) (HsProtobuf.fromProtoEnum y) instance HsProtobuf.ProtoEnum GetMagicJwtError where toProtoEnumMay 0 = Hs.Just GetMagicJwtErrorInvalidAdminToken toProtoEnumMay 1 = Hs.Just GetMagicJwtErrorMagicTokenDisabled toProtoEnumMay 2 = Hs.Just GetMagicJwtErrorMagicTokenCreateError toProtoEnumMay _ = Hs.Nothing fromProtoEnum (GetMagicJwtErrorInvalidAdminToken) = 0 fromProtoEnum (GetMagicJwtErrorMagicTokenDisabled) = 1 fromProtoEnum (GetMagicJwtErrorMagicTokenCreateError) = 2 instance HsJSONPB.ToJSONPB GetMagicJwtError where toJSONPB x _ = HsJSONPB.enumFieldString x toEncodingPB x _ = HsJSONPB.enumFieldEncoding x instance HsJSONPB.FromJSONPB GetMagicJwtError where parseJSONPB (HsJSONPB.String "InvalidAdminToken") = Hs.pure GetMagicJwtErrorInvalidAdminToken parseJSONPB (HsJSONPB.String "MagicTokenDisabled") = Hs.pure GetMagicJwtErrorMagicTokenDisabled parseJSONPB (HsJSONPB.String "MagicTokenCreateError") = Hs.pure GetMagicJwtErrorMagicTokenCreateError parseJSONPB v = (HsJSONPB.typeMismatch "GetMagicJwtError" v) instance HsJSONPB.ToJSON GetMagicJwtError where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON GetMagicJwtError where parseJSON = HsJSONPB.parseJSONPB instance HsProtobuf.Finite GetMagicJwtError newtype GetMagicJwtResponse = GetMagicJwtResponse { getMagicJwtResponseResult :: Hs.Maybe GetMagicJwtResponseResult } deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named GetMagicJwtResponse where nameOf _ = (Hs.fromString "GetMagicJwtResponse") instance HsProtobuf.HasDefault GetMagicJwtResponse instance HsProtobuf.Message GetMagicJwtResponse where encodeMessage _ GetMagicJwtResponse { getMagicJwtResponseResult = getMagicJwtResponseResult } = ( Hs.mconcat [ case getMagicJwtResponseResult of Hs.Nothing -> Hs.mempty Hs.Just x -> case x of GetMagicJwtResponseResultError y -> ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 1) (HsProtobuf.ForceEmit y) ) GetMagicJwtResponseResultJwt y -> ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 2) (HsProtobuf.ForceEmit y) ) ] ) decodeMessage _ = (Hs.pure GetMagicJwtResponse) <*> ( HsProtobuf.oneof Hs.Nothing [ ( (HsProtobuf.FieldNumber 1) , (Hs.pure (Hs.Just Hs.. GetMagicJwtResponseResultError)) <*> HsProtobuf.decodeMessageField ) , ( (HsProtobuf.FieldNumber 2) , (Hs.pure (Hs.Just Hs.. GetMagicJwtResponseResultJwt)) <*> HsProtobuf.decodeMessageField ) ] ) dotProto _ = [] instance HsJSONPB.ToJSONPB GetMagicJwtResponse where toJSONPB (GetMagicJwtResponse f1_or_f2) = ( HsJSONPB.object [ ( let encodeResult = ( case f1_or_f2 of Hs.Just (GetMagicJwtResponseResultError f1) -> (HsJSONPB.pair "error" f1) Hs.Just (GetMagicJwtResponseResultJwt f2) -> (HsJSONPB.pair "jwt" f2) Hs.Nothing -> Hs.mempty ) in \options -> if HsJSONPB.optEmitNamedOneof options then ("result" .= (HsJSONPB.objectOrNull [encodeResult] options)) options else encodeResult options ) ] ) toEncodingPB (GetMagicJwtResponse f1_or_f2) = ( HsJSONPB.pairs [ ( let encodeResult = ( case f1_or_f2 of Hs.Just (GetMagicJwtResponseResultError f1) -> (HsJSONPB.pair "error" f1) Hs.Just (GetMagicJwtResponseResultJwt f2) -> (HsJSONPB.pair "jwt" f2) Hs.Nothing -> Hs.mempty ) in \options -> if HsJSONPB.optEmitNamedOneof options then ("result" .= (HsJSONPB.pairsOrNull [encodeResult] options)) options else encodeResult options ) ] ) instance HsJSONPB.FromJSONPB GetMagicJwtResponse where parseJSONPB = ( HsJSONPB.withObject "GetMagicJwtResponse" ( \obj -> (Hs.pure GetMagicJwtResponse) <*> ( let parseResult parseObj = Hs.msum [ Hs.Just Hs.. GetMagicJwtResponseResultError <$> (HsJSONPB.parseField parseObj "error") , Hs.Just Hs.. GetMagicJwtResponseResultJwt <$> (HsJSONPB.parseField parseObj "jwt") , Hs.pure Hs.Nothing ] in ( (obj .: "result") Hs.>>= (HsJSONPB.withObject "result" parseResult) ) <|> (parseResult obj) ) ) ) instance HsJSONPB.ToJSON GetMagicJwtResponse where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON GetMagicJwtResponse where parseJSON = HsJSONPB.parseJSONPB data GetMagicJwtResponseResult = GetMagicJwtResponseResultError ( HsProtobuf.Enumerated Monocle.Protob.Auth.GetMagicJwtError ) | GetMagicJwtResponseResultJwt Hs.Text deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named GetMagicJwtResponseResult where nameOf _ = (Hs.fromString "GetMagicJwtResponseResult") newtype WhoAmiRequest = WhoAmiRequest {whoAmiRequestVoid :: Hs.Text} deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named WhoAmiRequest where nameOf _ = (Hs.fromString "WhoAmiRequest") instance HsProtobuf.HasDefault WhoAmiRequest instance HsProtobuf.Message WhoAmiRequest where encodeMessage _ WhoAmiRequest {whoAmiRequestVoid = whoAmiRequestVoid} = ( Hs.mconcat [ ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 1) whoAmiRequestVoid ) ] ) decodeMessage _ = (Hs.pure WhoAmiRequest) <*> ( HsProtobuf.at HsProtobuf.decodeMessageField (HsProtobuf.FieldNumber 1) ) dotProto _ = [ ( HsProtobuf.DotProtoField (HsProtobuf.FieldNumber 1) (HsProtobuf.Prim HsProtobuf.String) (HsProtobuf.Single "void") [] "" ) ] instance HsJSONPB.ToJSONPB WhoAmiRequest where toJSONPB (WhoAmiRequest f1) = (HsJSONPB.object ["void" .= f1]) toEncodingPB (WhoAmiRequest f1) = (HsJSONPB.pairs ["void" .= f1]) instance HsJSONPB.FromJSONPB WhoAmiRequest where parseJSONPB = ( HsJSONPB.withObject "WhoAmiRequest" (\obj -> (Hs.pure WhoAmiRequest) <*> obj .: "void") ) instance HsJSONPB.ToJSON WhoAmiRequest where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON WhoAmiRequest where parseJSON = HsJSONPB.parseJSONPB data WhoAmiError = WhoAmiErrorUnAuthorized deriving (Hs.Show, Hs.Eq, Hs.Generic, Hs.NFData) instance HsProtobuf.Named WhoAmiError where nameOf _ = (Hs.fromString "WhoAmiError") instance HsProtobuf.HasDefault WhoAmiError instance Hs.Bounded WhoAmiError where minBound = WhoAmiErrorUnAuthorized maxBound = WhoAmiErrorUnAuthorized instance Hs.Ord WhoAmiError where compare x y = Hs.compare (HsProtobuf.fromProtoEnum x) (HsProtobuf.fromProtoEnum y) instance HsProtobuf.ProtoEnum WhoAmiError where toProtoEnumMay 0 = Hs.Just WhoAmiErrorUnAuthorized toProtoEnumMay _ = Hs.Nothing fromProtoEnum (WhoAmiErrorUnAuthorized) = 0 instance HsJSONPB.ToJSONPB WhoAmiError where toJSONPB x _ = HsJSONPB.enumFieldString x toEncodingPB x _ = HsJSONPB.enumFieldEncoding x instance HsJSONPB.FromJSONPB WhoAmiError where parseJSONPB (HsJSONPB.String "UnAuthorized") = Hs.pure WhoAmiErrorUnAuthorized parseJSONPB v = (HsJSONPB.typeMismatch "WhoAmiError" v) instance HsJSONPB.ToJSON WhoAmiError where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON WhoAmiError where parseJSON = HsJSONPB.parseJSONPB instance HsProtobuf.Finite WhoAmiError newtype WhoAmiResponse = WhoAmiResponse { whoAmiResponseResult :: Hs.Maybe WhoAmiResponseResult } deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named WhoAmiResponse where nameOf _ = (Hs.fromString "WhoAmiResponse") instance HsProtobuf.HasDefault WhoAmiResponse instance HsProtobuf.Message WhoAmiResponse where encodeMessage _ WhoAmiResponse {whoAmiResponseResult = whoAmiResponseResult} = ( Hs.mconcat [ case whoAmiResponseResult of Hs.Nothing -> Hs.mempty Hs.Just x -> case x of WhoAmiResponseResultError y -> ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 1) (HsProtobuf.ForceEmit y) ) WhoAmiResponseResultUid y -> ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 2) (HsProtobuf.ForceEmit y) ) ] ) decodeMessage _ = (Hs.pure WhoAmiResponse) <*> ( HsProtobuf.oneof Hs.Nothing [ ( (HsProtobuf.FieldNumber 1) , (Hs.pure (Hs.Just Hs.. WhoAmiResponseResultError)) <*> HsProtobuf.decodeMessageField ) , ( (HsProtobuf.FieldNumber 2) , (Hs.pure (Hs.Just Hs.. WhoAmiResponseResultUid)) <*> HsProtobuf.decodeMessageField ) ] ) dotProto _ = [] instance HsJSONPB.ToJSONPB WhoAmiResponse where toJSONPB (WhoAmiResponse f1_or_f2) = ( HsJSONPB.object [ ( let encodeResult = ( case f1_or_f2 of Hs.Just (WhoAmiResponseResultError f1) -> (HsJSONPB.pair "error" f1) Hs.Just (WhoAmiResponseResultUid f2) -> (HsJSONPB.pair "uid" f2) Hs.Nothing -> Hs.mempty ) in \options -> if HsJSONPB.optEmitNamedOneof options then ("result" .= (HsJSONPB.objectOrNull [encodeResult] options)) options else encodeResult options ) ] ) toEncodingPB (WhoAmiResponse f1_or_f2) = ( HsJSONPB.pairs [ ( let encodeResult = ( case f1_or_f2 of Hs.Just (WhoAmiResponseResultError f1) -> (HsJSONPB.pair "error" f1) Hs.Just (WhoAmiResponseResultUid f2) -> (HsJSONPB.pair "uid" f2) Hs.Nothing -> Hs.mempty ) in \options -> if HsJSONPB.optEmitNamedOneof options then ("result" .= (HsJSONPB.pairsOrNull [encodeResult] options)) options else encodeResult options ) ] ) instance HsJSONPB.FromJSONPB WhoAmiResponse where parseJSONPB = ( HsJSONPB.withObject "WhoAmiResponse" ( \obj -> (Hs.pure WhoAmiResponse) <*> ( let parseResult parseObj = Hs.msum [ Hs.Just Hs.. WhoAmiResponseResultError <$> (HsJSONPB.parseField parseObj "error") , Hs.Just Hs.. WhoAmiResponseResultUid <$> (HsJSONPB.parseField parseObj "uid") , Hs.pure Hs.Nothing ] in ( (obj .: "result") Hs.>>= (HsJSONPB.withObject "result" parseResult) ) <|> (parseResult obj) ) ) ) instance HsJSONPB.ToJSON WhoAmiResponse where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON WhoAmiResponse where parseJSON = HsJSONPB.parseJSONPB data WhoAmiResponseResult = WhoAmiResponseResultError ( HsProtobuf.Enumerated Monocle.Protob.Auth.WhoAmiError ) | WhoAmiResponseResultUid Hs.Text deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named WhoAmiResponseResult where nameOf _ = (Hs.fromString "WhoAmiResponseResult")
null
https://raw.githubusercontent.com/change-metrics/monocle/8b239d7ee0e9e30690cd82baf7e46a5fda221583/codegen/Monocle/Protob/Auth.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # | Generated by Haskell protocol buffer compiler. DO NOT EDIT!
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE TypeApplications # # LANGUAGE NoGeneralisedNewtypeDeriving # # OPTIONS_GHC -fno - warn - missing - export - lists # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # module Monocle.Protob.Auth where import Control.Applicative ((<$>), (<*>), (<|>)) import Control.Applicative qualified as Hs import Control.DeepSeq qualified as Hs import Control.Monad qualified as Hs import Data.ByteString qualified as Hs import Data.Coerce qualified as Hs import Data.Int qualified as Hs (Int16, Int32, Int64) import Data.List.NonEmpty qualified as Hs (NonEmpty (..)) import Data.Map qualified as Hs (Map, mapKeysMonotonic) import Data.Proxy qualified as Proxy import Data.String qualified as Hs (fromString) import Data.Text.Lazy qualified as Hs (Text) import Data.Vector qualified as Hs (Vector) import Data.Word qualified as Hs (Word16, Word32, Word64) import GHC.Enum qualified as Hs import GHC.Generics qualified as Hs import Proto3.Suite.Class qualified as HsProtobuf import Proto3.Suite.DotProto qualified as HsProtobuf import Proto3.Suite.JSONPB ((.:), (.=)) import Proto3.Suite.JSONPB qualified as HsJSONPB import Proto3.Suite.Types qualified as HsProtobuf import Proto3.Wire qualified as HsProtobuf import Unsafe.Coerce qualified as Hs import Prelude qualified as Hs newtype GetMagicJwtRequest = GetMagicJwtRequest { getMagicJwtRequestToken :: Hs.Text } deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named GetMagicJwtRequest where nameOf _ = (Hs.fromString "GetMagicJwtRequest") instance HsProtobuf.HasDefault GetMagicJwtRequest instance HsProtobuf.Message GetMagicJwtRequest where encodeMessage _ GetMagicJwtRequest { getMagicJwtRequestToken = getMagicJwtRequestToken } = ( Hs.mconcat [ ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 1) getMagicJwtRequestToken ) ] ) decodeMessage _ = (Hs.pure GetMagicJwtRequest) <*> ( HsProtobuf.at HsProtobuf.decodeMessageField (HsProtobuf.FieldNumber 1) ) dotProto _ = [ ( HsProtobuf.DotProtoField (HsProtobuf.FieldNumber 1) (HsProtobuf.Prim HsProtobuf.String) (HsProtobuf.Single "token") [] "" ) ] instance HsJSONPB.ToJSONPB GetMagicJwtRequest where toJSONPB (GetMagicJwtRequest f1) = (HsJSONPB.object ["token" .= f1]) toEncodingPB (GetMagicJwtRequest f1) = (HsJSONPB.pairs ["token" .= f1]) instance HsJSONPB.FromJSONPB GetMagicJwtRequest where parseJSONPB = ( HsJSONPB.withObject "GetMagicJwtRequest" (\obj -> (Hs.pure GetMagicJwtRequest) <*> obj .: "token") ) instance HsJSONPB.ToJSON GetMagicJwtRequest where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON GetMagicJwtRequest where parseJSON = HsJSONPB.parseJSONPB data GetMagicJwtError = GetMagicJwtErrorInvalidAdminToken | GetMagicJwtErrorMagicTokenDisabled | GetMagicJwtErrorMagicTokenCreateError deriving (Hs.Show, Hs.Eq, Hs.Generic, Hs.NFData) instance HsProtobuf.Named GetMagicJwtError where nameOf _ = (Hs.fromString "GetMagicJwtError") instance HsProtobuf.HasDefault GetMagicJwtError instance Hs.Bounded GetMagicJwtError where minBound = GetMagicJwtErrorInvalidAdminToken maxBound = GetMagicJwtErrorMagicTokenCreateError instance Hs.Ord GetMagicJwtError where compare x y = Hs.compare (HsProtobuf.fromProtoEnum x) (HsProtobuf.fromProtoEnum y) instance HsProtobuf.ProtoEnum GetMagicJwtError where toProtoEnumMay 0 = Hs.Just GetMagicJwtErrorInvalidAdminToken toProtoEnumMay 1 = Hs.Just GetMagicJwtErrorMagicTokenDisabled toProtoEnumMay 2 = Hs.Just GetMagicJwtErrorMagicTokenCreateError toProtoEnumMay _ = Hs.Nothing fromProtoEnum (GetMagicJwtErrorInvalidAdminToken) = 0 fromProtoEnum (GetMagicJwtErrorMagicTokenDisabled) = 1 fromProtoEnum (GetMagicJwtErrorMagicTokenCreateError) = 2 instance HsJSONPB.ToJSONPB GetMagicJwtError where toJSONPB x _ = HsJSONPB.enumFieldString x toEncodingPB x _ = HsJSONPB.enumFieldEncoding x instance HsJSONPB.FromJSONPB GetMagicJwtError where parseJSONPB (HsJSONPB.String "InvalidAdminToken") = Hs.pure GetMagicJwtErrorInvalidAdminToken parseJSONPB (HsJSONPB.String "MagicTokenDisabled") = Hs.pure GetMagicJwtErrorMagicTokenDisabled parseJSONPB (HsJSONPB.String "MagicTokenCreateError") = Hs.pure GetMagicJwtErrorMagicTokenCreateError parseJSONPB v = (HsJSONPB.typeMismatch "GetMagicJwtError" v) instance HsJSONPB.ToJSON GetMagicJwtError where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON GetMagicJwtError where parseJSON = HsJSONPB.parseJSONPB instance HsProtobuf.Finite GetMagicJwtError newtype GetMagicJwtResponse = GetMagicJwtResponse { getMagicJwtResponseResult :: Hs.Maybe GetMagicJwtResponseResult } deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named GetMagicJwtResponse where nameOf _ = (Hs.fromString "GetMagicJwtResponse") instance HsProtobuf.HasDefault GetMagicJwtResponse instance HsProtobuf.Message GetMagicJwtResponse where encodeMessage _ GetMagicJwtResponse { getMagicJwtResponseResult = getMagicJwtResponseResult } = ( Hs.mconcat [ case getMagicJwtResponseResult of Hs.Nothing -> Hs.mempty Hs.Just x -> case x of GetMagicJwtResponseResultError y -> ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 1) (HsProtobuf.ForceEmit y) ) GetMagicJwtResponseResultJwt y -> ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 2) (HsProtobuf.ForceEmit y) ) ] ) decodeMessage _ = (Hs.pure GetMagicJwtResponse) <*> ( HsProtobuf.oneof Hs.Nothing [ ( (HsProtobuf.FieldNumber 1) , (Hs.pure (Hs.Just Hs.. GetMagicJwtResponseResultError)) <*> HsProtobuf.decodeMessageField ) , ( (HsProtobuf.FieldNumber 2) , (Hs.pure (Hs.Just Hs.. GetMagicJwtResponseResultJwt)) <*> HsProtobuf.decodeMessageField ) ] ) dotProto _ = [] instance HsJSONPB.ToJSONPB GetMagicJwtResponse where toJSONPB (GetMagicJwtResponse f1_or_f2) = ( HsJSONPB.object [ ( let encodeResult = ( case f1_or_f2 of Hs.Just (GetMagicJwtResponseResultError f1) -> (HsJSONPB.pair "error" f1) Hs.Just (GetMagicJwtResponseResultJwt f2) -> (HsJSONPB.pair "jwt" f2) Hs.Nothing -> Hs.mempty ) in \options -> if HsJSONPB.optEmitNamedOneof options then ("result" .= (HsJSONPB.objectOrNull [encodeResult] options)) options else encodeResult options ) ] ) toEncodingPB (GetMagicJwtResponse f1_or_f2) = ( HsJSONPB.pairs [ ( let encodeResult = ( case f1_or_f2 of Hs.Just (GetMagicJwtResponseResultError f1) -> (HsJSONPB.pair "error" f1) Hs.Just (GetMagicJwtResponseResultJwt f2) -> (HsJSONPB.pair "jwt" f2) Hs.Nothing -> Hs.mempty ) in \options -> if HsJSONPB.optEmitNamedOneof options then ("result" .= (HsJSONPB.pairsOrNull [encodeResult] options)) options else encodeResult options ) ] ) instance HsJSONPB.FromJSONPB GetMagicJwtResponse where parseJSONPB = ( HsJSONPB.withObject "GetMagicJwtResponse" ( \obj -> (Hs.pure GetMagicJwtResponse) <*> ( let parseResult parseObj = Hs.msum [ Hs.Just Hs.. GetMagicJwtResponseResultError <$> (HsJSONPB.parseField parseObj "error") , Hs.Just Hs.. GetMagicJwtResponseResultJwt <$> (HsJSONPB.parseField parseObj "jwt") , Hs.pure Hs.Nothing ] in ( (obj .: "result") Hs.>>= (HsJSONPB.withObject "result" parseResult) ) <|> (parseResult obj) ) ) ) instance HsJSONPB.ToJSON GetMagicJwtResponse where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON GetMagicJwtResponse where parseJSON = HsJSONPB.parseJSONPB data GetMagicJwtResponseResult = GetMagicJwtResponseResultError ( HsProtobuf.Enumerated Monocle.Protob.Auth.GetMagicJwtError ) | GetMagicJwtResponseResultJwt Hs.Text deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named GetMagicJwtResponseResult where nameOf _ = (Hs.fromString "GetMagicJwtResponseResult") newtype WhoAmiRequest = WhoAmiRequest {whoAmiRequestVoid :: Hs.Text} deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named WhoAmiRequest where nameOf _ = (Hs.fromString "WhoAmiRequest") instance HsProtobuf.HasDefault WhoAmiRequest instance HsProtobuf.Message WhoAmiRequest where encodeMessage _ WhoAmiRequest {whoAmiRequestVoid = whoAmiRequestVoid} = ( Hs.mconcat [ ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 1) whoAmiRequestVoid ) ] ) decodeMessage _ = (Hs.pure WhoAmiRequest) <*> ( HsProtobuf.at HsProtobuf.decodeMessageField (HsProtobuf.FieldNumber 1) ) dotProto _ = [ ( HsProtobuf.DotProtoField (HsProtobuf.FieldNumber 1) (HsProtobuf.Prim HsProtobuf.String) (HsProtobuf.Single "void") [] "" ) ] instance HsJSONPB.ToJSONPB WhoAmiRequest where toJSONPB (WhoAmiRequest f1) = (HsJSONPB.object ["void" .= f1]) toEncodingPB (WhoAmiRequest f1) = (HsJSONPB.pairs ["void" .= f1]) instance HsJSONPB.FromJSONPB WhoAmiRequest where parseJSONPB = ( HsJSONPB.withObject "WhoAmiRequest" (\obj -> (Hs.pure WhoAmiRequest) <*> obj .: "void") ) instance HsJSONPB.ToJSON WhoAmiRequest where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON WhoAmiRequest where parseJSON = HsJSONPB.parseJSONPB data WhoAmiError = WhoAmiErrorUnAuthorized deriving (Hs.Show, Hs.Eq, Hs.Generic, Hs.NFData) instance HsProtobuf.Named WhoAmiError where nameOf _ = (Hs.fromString "WhoAmiError") instance HsProtobuf.HasDefault WhoAmiError instance Hs.Bounded WhoAmiError where minBound = WhoAmiErrorUnAuthorized maxBound = WhoAmiErrorUnAuthorized instance Hs.Ord WhoAmiError where compare x y = Hs.compare (HsProtobuf.fromProtoEnum x) (HsProtobuf.fromProtoEnum y) instance HsProtobuf.ProtoEnum WhoAmiError where toProtoEnumMay 0 = Hs.Just WhoAmiErrorUnAuthorized toProtoEnumMay _ = Hs.Nothing fromProtoEnum (WhoAmiErrorUnAuthorized) = 0 instance HsJSONPB.ToJSONPB WhoAmiError where toJSONPB x _ = HsJSONPB.enumFieldString x toEncodingPB x _ = HsJSONPB.enumFieldEncoding x instance HsJSONPB.FromJSONPB WhoAmiError where parseJSONPB (HsJSONPB.String "UnAuthorized") = Hs.pure WhoAmiErrorUnAuthorized parseJSONPB v = (HsJSONPB.typeMismatch "WhoAmiError" v) instance HsJSONPB.ToJSON WhoAmiError where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON WhoAmiError where parseJSON = HsJSONPB.parseJSONPB instance HsProtobuf.Finite WhoAmiError newtype WhoAmiResponse = WhoAmiResponse { whoAmiResponseResult :: Hs.Maybe WhoAmiResponseResult } deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named WhoAmiResponse where nameOf _ = (Hs.fromString "WhoAmiResponse") instance HsProtobuf.HasDefault WhoAmiResponse instance HsProtobuf.Message WhoAmiResponse where encodeMessage _ WhoAmiResponse {whoAmiResponseResult = whoAmiResponseResult} = ( Hs.mconcat [ case whoAmiResponseResult of Hs.Nothing -> Hs.mempty Hs.Just x -> case x of WhoAmiResponseResultError y -> ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 1) (HsProtobuf.ForceEmit y) ) WhoAmiResponseResultUid y -> ( HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 2) (HsProtobuf.ForceEmit y) ) ] ) decodeMessage _ = (Hs.pure WhoAmiResponse) <*> ( HsProtobuf.oneof Hs.Nothing [ ( (HsProtobuf.FieldNumber 1) , (Hs.pure (Hs.Just Hs.. WhoAmiResponseResultError)) <*> HsProtobuf.decodeMessageField ) , ( (HsProtobuf.FieldNumber 2) , (Hs.pure (Hs.Just Hs.. WhoAmiResponseResultUid)) <*> HsProtobuf.decodeMessageField ) ] ) dotProto _ = [] instance HsJSONPB.ToJSONPB WhoAmiResponse where toJSONPB (WhoAmiResponse f1_or_f2) = ( HsJSONPB.object [ ( let encodeResult = ( case f1_or_f2 of Hs.Just (WhoAmiResponseResultError f1) -> (HsJSONPB.pair "error" f1) Hs.Just (WhoAmiResponseResultUid f2) -> (HsJSONPB.pair "uid" f2) Hs.Nothing -> Hs.mempty ) in \options -> if HsJSONPB.optEmitNamedOneof options then ("result" .= (HsJSONPB.objectOrNull [encodeResult] options)) options else encodeResult options ) ] ) toEncodingPB (WhoAmiResponse f1_or_f2) = ( HsJSONPB.pairs [ ( let encodeResult = ( case f1_or_f2 of Hs.Just (WhoAmiResponseResultError f1) -> (HsJSONPB.pair "error" f1) Hs.Just (WhoAmiResponseResultUid f2) -> (HsJSONPB.pair "uid" f2) Hs.Nothing -> Hs.mempty ) in \options -> if HsJSONPB.optEmitNamedOneof options then ("result" .= (HsJSONPB.pairsOrNull [encodeResult] options)) options else encodeResult options ) ] ) instance HsJSONPB.FromJSONPB WhoAmiResponse where parseJSONPB = ( HsJSONPB.withObject "WhoAmiResponse" ( \obj -> (Hs.pure WhoAmiResponse) <*> ( let parseResult parseObj = Hs.msum [ Hs.Just Hs.. WhoAmiResponseResultError <$> (HsJSONPB.parseField parseObj "error") , Hs.Just Hs.. WhoAmiResponseResultUid <$> (HsJSONPB.parseField parseObj "uid") , Hs.pure Hs.Nothing ] in ( (obj .: "result") Hs.>>= (HsJSONPB.withObject "result" parseResult) ) <|> (parseResult obj) ) ) ) instance HsJSONPB.ToJSON WhoAmiResponse where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON WhoAmiResponse where parseJSON = HsJSONPB.parseJSONPB data WhoAmiResponseResult = WhoAmiResponseResultError ( HsProtobuf.Enumerated Monocle.Protob.Auth.WhoAmiError ) | WhoAmiResponseResultUid Hs.Text deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named WhoAmiResponseResult where nameOf _ = (Hs.fromString "WhoAmiResponseResult")
b9ad1d10e9adc083fb788f24bfddb90ffefbc7ed62168784d051e3aeef91c38a
KenDickey/Crosstalk
gambit-apropos.scm
;;; FILE: "apropos.scm" ;;; IMPLEMENTS: apropos function for Scheme globals ;;; return a list of variable name symbols containing ;;; the target string. AUTHOR : DATE : 30 June 2016 Copyright ( c ) 2016 , ;; All rights reserved. ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; * Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;======================================================= ;; Run from command line via "larceny -r7rs", then ;; (import (scheme load)) ;; (load "apropos.scm") ;; ;; (apropos 'cons) ;; (apropos "char") ;(import (primitives interaction-environment environment-variables) ; (rnrs sorting) ; ) (define (symbol-table->list st) (define (symbol-chain s syms) (let loop ((s s) (syms syms)) (if (symbol? s) (loop (##vector-ref s 2) (cons s syms)) syms))) (let loop ((lst (vector->list st)) (syms '())) (if (pair? lst) (loop (cdr lst) (symbol-chain (car lst) syms)) (reverse syms)))) (define (interned-symbols) (symbol-table->list (##symbol-table))) (define (apropos string-or-symbol) (let ( (contains-substring? (substring-search-maker (if (symbol? string-or-symbol) (symbol->string string-or-symbol) string-or-symbol))) (env-syms (interned-symbols)) ) (let loop ( (results '()) (syms env-syms) ) (if (null? syms) (list-sort symbol<? results) (let ( (var-name (symbol->string (car syms))) ) (cond ((contains-substring? var-name) (loop (cons (sanitize var-name) results) (cdr syms)) ) (else (loop results (cdr syms))))) ) ) ) ) (define (sanitize name-string) NB : takes a string & returns a symbol (string->symbol (if (< (char->integer (string-ref name-string 0)) 32) (substring name-string 1 (string-length name-string)) name-string)) ) (define (symbol<? s1 s2) (string<? (symbol->string s1) (symbol->string s2))) ;; SUBSTRING-SEARCH-MAKER takes a string (the "pattern") and returns a function ;; which takes a string (the "target") and either returns #f or the index in the target in which the pattern first occurs as a substring . ;; E.g. ( ( substring - search - maker " test " ) " This is a test string " ) - > 10 ;; ((substring-search-maker "test") "This is a text string") -> #f ; NOTES Based on " A Very Fast Substring Search Algorithm " , , CACM v33 , # 8 , August 1990 . (define (substring-search-maker pattern-string) (define num-chars-in-charset 256) (define (build-shift-vector pattern-string) (let* ( (pat-len (string-length pattern-string)) (shift-vec (make-vector num-chars-in-charset (+ pat-len 1))) (max-pat-index (- pat-len 1)) ) (let loop ( (index 0) ) (vector-set! shift-vec (char->integer (string-ref pattern-string index)) (- pat-len index) ) (if (< index max-pat-index) (loop (+ index 1)) shift-vec) ) ) ) (let ( (shift-vec (build-shift-vector pattern-string)) (pat-len (string-length pattern-string)) ) (lambda (target-string) (let* ( (tar-len (string-length target-string)) (max-tar-index (- tar-len 1)) (max-pat-index (- pat-len 1)) ) (let outer ( (start-index 0) ) (if (> (+ pat-len start-index) tar-len) #f (let inner ( (p-ind 0) (t-ind start-index) ) (cond ((> p-ind max-pat-index) ; nothing left to check #f ; fail ) ((char=? (string-ref pattern-string p-ind) (string-ref target-string t-ind)) (if (= p-ind max-pat-index) start-index ;; success -- return start index of match (inner (+ p-ind 1) (+ t-ind 1)) ; keep checking ) ) ((> (+ pat-len start-index) max-tar-index) #f) ; fail (else (outer (+ start-index (vector-ref shift-vec (char->integer (string-ref target-string (+ start-index pat-len) ) ) ) ) ) ) ) ; end-cond ) ) ) ) ) ; end-lambda ) ) ;; --- E O F ---
null
https://raw.githubusercontent.com/KenDickey/Crosstalk/c4a315baf039e714980e14f5b07860632b9bd0e6/gambit-apropos.scm
scheme
FILE: "apropos.scm" IMPLEMENTS: apropos function for Scheme globals return a list of variable name symbols containing the target string. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ======================================================= Run from command line via "larceny -r7rs", then (import (scheme load)) (load "apropos.scm") (apropos 'cons) (apropos "char") (import (primitives interaction-environment environment-variables) (rnrs sorting) ) SUBSTRING-SEARCH-MAKER takes a string (the "pattern") and returns a function which takes a string (the "target") and either returns #f or the index in ((substring-search-maker "test") "This is a text string") -> #f NOTES nothing left to check fail success -- return start index of match keep checking fail end-cond end-lambda --- E O F ---
AUTHOR : DATE : 30 June 2016 Copyright ( c ) 2016 , THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , (define (symbol-table->list st) (define (symbol-chain s syms) (let loop ((s s) (syms syms)) (if (symbol? s) (loop (##vector-ref s 2) (cons s syms)) syms))) (let loop ((lst (vector->list st)) (syms '())) (if (pair? lst) (loop (cdr lst) (symbol-chain (car lst) syms)) (reverse syms)))) (define (interned-symbols) (symbol-table->list (##symbol-table))) (define (apropos string-or-symbol) (let ( (contains-substring? (substring-search-maker (if (symbol? string-or-symbol) (symbol->string string-or-symbol) string-or-symbol))) (env-syms (interned-symbols)) ) (let loop ( (results '()) (syms env-syms) ) (if (null? syms) (list-sort symbol<? results) (let ( (var-name (symbol->string (car syms))) ) (cond ((contains-substring? var-name) (loop (cons (sanitize var-name) results) (cdr syms)) ) (else (loop results (cdr syms))))) ) ) ) ) (define (sanitize name-string) NB : takes a string & returns a symbol (string->symbol (if (< (char->integer (string-ref name-string 0)) 32) (substring name-string 1 (string-length name-string)) name-string)) ) (define (symbol<? s1 s2) (string<? (symbol->string s1) (symbol->string s2))) the target in which the pattern first occurs as a substring . E.g. ( ( substring - search - maker " test " ) " This is a test string " ) - > 10 Based on " A Very Fast Substring Search Algorithm " , , CACM v33 , # 8 , August 1990 . (define (substring-search-maker pattern-string) (define num-chars-in-charset 256) (define (build-shift-vector pattern-string) (let* ( (pat-len (string-length pattern-string)) (shift-vec (make-vector num-chars-in-charset (+ pat-len 1))) (max-pat-index (- pat-len 1)) ) (let loop ( (index 0) ) (vector-set! shift-vec (char->integer (string-ref pattern-string index)) (- pat-len index) ) (if (< index max-pat-index) (loop (+ index 1)) shift-vec) ) ) ) (let ( (shift-vec (build-shift-vector pattern-string)) (pat-len (string-length pattern-string)) ) (lambda (target-string) (let* ( (tar-len (string-length target-string)) (max-tar-index (- tar-len 1)) (max-pat-index (- pat-len 1)) ) (let outer ( (start-index 0) ) (if (> (+ pat-len start-index) tar-len) #f (let inner ( (p-ind 0) (t-ind start-index) ) (cond ) ((char=? (string-ref pattern-string p-ind) (string-ref target-string t-ind)) (if (= p-ind max-pat-index) ) ) (else (outer (+ start-index (vector-ref shift-vec (char->integer (string-ref target-string (+ start-index pat-len) ) ) ) ) ) ) ) ) ) ) )
8b8ee5dbc0e8440d5fe99e64e80276c7f0998174a72ed8b978755de3e4c86b02
soenkehahn/getopt-generics
CustomOption.hs
{-# LANGUAGE DeriveDataTypeable #-} module CustomOption where import WithCli data File = File FilePath deriving (Show, Typeable) instance Argument File where argumentType Proxy = "custom-file-type" parseArgument f = Just (File f) instance HasArguments File where argumentsParser = atomicArgumentsParser main :: IO () main = withCli run run :: File -> IO () run = print
null
https://raw.githubusercontent.com/soenkehahn/getopt-generics/735319c8146043f704d17f06b7bbfa41d84fe3e6/docs/CustomOption.hs
haskell
# LANGUAGE DeriveDataTypeable #
module CustomOption where import WithCli data File = File FilePath deriving (Show, Typeable) instance Argument File where argumentType Proxy = "custom-file-type" parseArgument f = Just (File f) instance HasArguments File where argumentsParser = atomicArgumentsParser main :: IO () main = withCli run run :: File -> IO () run = print
a29baa3ef16bf78baab9335d032f3594d75f90e1106997e48bbe8baca776e1d7
nedap/formatting-stack
ns_aliases.clj
(ns unit.formatting-stack.linters.ns-aliases (:require [clojure.test :refer [are deftest]] [formatting-stack.linters.ns-aliases :as sut])) (deftest name-and-alias (are [input expected] (= expected (sut/name-and-alias input)) '[foo], ['foo nil] '[foo :refer :all], ['foo nil] '[foo :refer :all :as bar], ['foo 'bar] '[foo :as bar :refer :all], ['foo 'bar] '[foo :as bar], ['foo 'bar] '["foo" :as bar], ["foo" 'bar])) (deftest derived? (are [ns-name _as alias expected] (= expected (sut/derived? alias :from ns-name)) 'com.enterprise.foo.bar :as 'bar, true 'com.enterprise.foo.bar :as 'foo.bar, true 'com.enterprise.foo.bar :as 'enterprise.foo.bar, true 'com.enterprise.foo.bar :as 'com.enterprise.foo.bar, true 'com.enterprise.foo.bar :as 'com.enterprise.foo, false 'com.enterprise.foo.bar :as 'com.enterprise, false 'com.enterprise.foo.bar :as 'com, false 'com.enterprise.foo.bar :as 'enterprise, false 'com.enterprise.foo.bar :as 'foo, false 'com.enterprise.foo.bar :as 'b, false 'net.xyz.core :as 'xyz true 'net.xyz.core :as 'net.xyz true 'net.xyz.alpha :as 'xyz true 'net.xyz.alpha :as 'net.xyz true 'net.xyz.alpha.core :as 'xyz true 'net.xyz.alpha.core :as 'net.xyz true 'net.xyz.core.alpha :as 'xyz true 'net.xyz.core.alpha :as 'net.xyz true 'buddy.core.keys :as 'buddy.keys true 'buddy.core.keys :as 'buddy.core.keys true 'buddy.core.keys :as 'keys.buddy false 'clj-http :as 'http true 'clj-http :as 'htta false 'clj-time.core :as 'time true 'clj-time.core :as 'tima false 'clj-time.format :as 'time.format true 'clj-time.format :as 'time.farmat false)) (deftest acceptable-require-clause? (are [whitelist input expected] (= expected (sut/acceptable-require-clause? whitelist input)) sut/default-acceptable-aliases-whitelist 'foo true sut/default-acceptable-aliases-whitelist '[foo] true sut/default-acceptable-aliases-whitelist '[foo :as foo] true sut/default-acceptable-aliases-whitelist '[foo :as bar] false sut/default-acceptable-aliases-whitelist '[foo :as sut] true {} '[foo :as sut] false sut/default-acceptable-aliases-whitelist '[datomic.api :as d] true {} '[datomic.api :as d] false))
null
https://raw.githubusercontent.com/nedap/formatting-stack/c43e74d5409e9338f208457bb8928ce437381a3f/test/unit/formatting_stack/linters/ns_aliases.clj
clojure
(ns unit.formatting-stack.linters.ns-aliases (:require [clojure.test :refer [are deftest]] [formatting-stack.linters.ns-aliases :as sut])) (deftest name-and-alias (are [input expected] (= expected (sut/name-and-alias input)) '[foo], ['foo nil] '[foo :refer :all], ['foo nil] '[foo :refer :all :as bar], ['foo 'bar] '[foo :as bar :refer :all], ['foo 'bar] '[foo :as bar], ['foo 'bar] '["foo" :as bar], ["foo" 'bar])) (deftest derived? (are [ns-name _as alias expected] (= expected (sut/derived? alias :from ns-name)) 'com.enterprise.foo.bar :as 'bar, true 'com.enterprise.foo.bar :as 'foo.bar, true 'com.enterprise.foo.bar :as 'enterprise.foo.bar, true 'com.enterprise.foo.bar :as 'com.enterprise.foo.bar, true 'com.enterprise.foo.bar :as 'com.enterprise.foo, false 'com.enterprise.foo.bar :as 'com.enterprise, false 'com.enterprise.foo.bar :as 'com, false 'com.enterprise.foo.bar :as 'enterprise, false 'com.enterprise.foo.bar :as 'foo, false 'com.enterprise.foo.bar :as 'b, false 'net.xyz.core :as 'xyz true 'net.xyz.core :as 'net.xyz true 'net.xyz.alpha :as 'xyz true 'net.xyz.alpha :as 'net.xyz true 'net.xyz.alpha.core :as 'xyz true 'net.xyz.alpha.core :as 'net.xyz true 'net.xyz.core.alpha :as 'xyz true 'net.xyz.core.alpha :as 'net.xyz true 'buddy.core.keys :as 'buddy.keys true 'buddy.core.keys :as 'buddy.core.keys true 'buddy.core.keys :as 'keys.buddy false 'clj-http :as 'http true 'clj-http :as 'htta false 'clj-time.core :as 'time true 'clj-time.core :as 'tima false 'clj-time.format :as 'time.format true 'clj-time.format :as 'time.farmat false)) (deftest acceptable-require-clause? (are [whitelist input expected] (= expected (sut/acceptable-require-clause? whitelist input)) sut/default-acceptable-aliases-whitelist 'foo true sut/default-acceptable-aliases-whitelist '[foo] true sut/default-acceptable-aliases-whitelist '[foo :as foo] true sut/default-acceptable-aliases-whitelist '[foo :as bar] false sut/default-acceptable-aliases-whitelist '[foo :as sut] true {} '[foo :as sut] false sut/default-acceptable-aliases-whitelist '[datomic.api :as d] true {} '[datomic.api :as d] false))
2608052430488ea8ec0c1ddb8f8e5cc42e178b4b4d34a349f0d24bcb7af76bf6
rsharifnasab/my-learning
Main.hs
Copyright 2019 Google LLC -- Licensed under the Apache License , Version 2.0 ( the " License " ) ; -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- -2.0 -- -- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. # LANGUAGE CPP , LambdaCase , StandaloneDeriving # # OPTIONS_GHC -fno - warn - type - defaults # # OPTIONS_GHC -fno - warn - missing - signatures # # OPTIONS_GHC -fno - warn - orphans # import Control.Exception import Control.Monad import Data.List (intercalate) import System.Console.GetOpt (ArgDescr(ReqArg, NoArg) , ArgOrder(Permute), OptDescr(Option) , getOpt, usageInfo ) import System.Environment (getArgs) import System.Exit import System.IO (Handle, hPutStr, hPutStrLn, stderr, stdout) import System.Posix.IO (stdOutput) import System.Posix.Terminal (queryTerminal) import System.Timeout import Text.Printf #ifdef SOLUTION import qualified Solution as C #else import qualified Codelab as C #endif deriving instance Eq C.Minutes deriving instance Show C.Minutes -- term color type TermColor = String kR = "\x1b[31;1m" kG = "\x1b[32;1m" putTag :: String -> TermColor -> IO () putTag = hPutTag stdout hPutTag :: Handle -> String -> TermColor -> IO () hPutTag h tag color = do isTTY <- queryTerminal stdOutput if isTTY then hPutStr h $ "[" ++ color ++ tag ++ "\x1b[0m]" else hPutStr h $ "[" ++ tag ++ "]" -- options newtype Section = Section Int deriving Eq instance Bounded Section where minBound = Section 1 maxBound = Section 6 instance Ord Section where compare (Section s1) (Section s2) = compare s1 s2 instance Enum Section where toEnum = Section fromEnum (Section i) = i validSection :: Section -> Bool validSection s = s >= minBound && s <= maxBound newtype Options = Options { optSections :: [Section] } options :: [OptDescr (Options -> IO Options)] options = [ Option ['s'] ["section"] (ReqArg (\v opts -> do let i = read v unless (validSection (Section i)) $ do hPutTag stderr "Error" kR hPutStrLn stderr $ " Invalid section number: " ++ v let (Section from, Section to) = (minBound, maxBound) hPrintf stderr "Valid section numbers: %d..%d\n" from to exitFailure return $ opts { optSections = optSections opts ++ [Section i] } ) "<id>" ) "Include section <id> in the run", Option ['h'] ["help"] (NoArg (\_ -> do hPutStrLn stderr (usageInfo usageHeader options) exitSuccess )) "Show this help message" ] usageHeader :: String usageHeader = "Usage: ./main [-h] [-s|--section <id>] [--help]" -- tests ifError :: (String -> a) -> ErrorCall -> a #if __GLASGOW_HASKELL__ < 800 ifError f (ErrorCall s) = f s #else ifError f (ErrorCallWithLocation s _) = f s #endif timeLimit :: Int 10 ^ 6 microseconds = 1 second test :: (Show a, Eq a) => String -> a -> a -> IO Bool test name expected actual = do let checkEq = if expected == actual then True <$ onSuccess else False <$ onError runTest = timeout timeLimit $ catch checkEq $ ifError $ (False <$) . onFailure void $ printf "%-42s" name result <- runTest >>= maybe (False <$ onTimeout) return putStrLn "" return result where onSuccess = putTag "OK" kG >> printf " got: %s" (show actual) onError = putTag "KO" kR >> printf " want: %s; got: %s" (show expected) (show actual) onFailure s = putTag "!!" kR >> printf " error: %s" s onTimeout = putTag "??" kR >> putStr " (timeout)" testI :: String -> Int -> Int -> IO Bool testI = test -- main tests :: [Section] -> [IO Bool] tests sections = let display s = True <$ putStrLn s in intercalate [display ""] $ flip map sections $ \case Section 1 -> [ display "#### Section 1" , test "add 1 2" 3 $ C.add 1 2 , test "subtract 7 2" 5 $ C.subtract 7 2 , test "double 3" 6 $ C.double 3 , test "multiply 3 11" 33 $ C.multiply 3 11 , test "divide 9 2" 4.5 $ C.divide 9 2 , test "divide 8 4" 2 $ C.divide 8 4 , test "factorial 30" (product [1..30]) $ C.factorial 30 , test "gcd 12 4" 4 $ C.gcd 12 4 , test "gcd 17 7" 1 $ C.gcd 17 7 ] Section 2 -> [ display "#### Section 2" , test "hours (Minutes 271)" 4 $ C.hours (C.Minutes 271) , test "hours (Minutes 15)" 0 $ C.hours (C.Minutes 15) , test "timeDistance (Minutes 15) (Minutes 25)" (C.Minutes 10) $ C.timeDistance (C.Minutes 15) (C.Minutes 25) , test "timeDistance (Minutes 99) (Minutes 47)" (C.Minutes 52) $ C.timeDistance (C.Minutes 99) (C.Minutes 47) , test "pointDistance (1, 1) (1, 3)" 2 $ C.pointDistance (1, 1) (1, 3) , test "pointDistance (3, 4) (0, 0)" 5 $ C.pointDistance (3, 4) (0, 0) ] Section 3 -> [ display "#### Section 3" , test "null []" True $ C.null [] , test "null [8,0,6]" False $ C.null [8,0,6] , testI "head [8,0,6]" 8 $ C.head [8,0,6] , test "tail [8,0,6]" [0,6] $ C.tail [8,0,6] ] Section 4 -> [ display "#### Section 4" , testI "length []" 0 $ C.length [] , testI "length [8,0,6]" 3 $ C.length [8,0,6] , test "and []" True $ C.and [] , test "and [True]" True $ C.and [True] , test "and [False]" False $ C.and [False] , test "and [True, True]" True $ C.and [True, True] , test "and [True, False]" False $ C.and [True, False] , test "and [False, True]" False $ C.and [False, True] , test "and [False, False]" False $ C.and [False, False] , test "and [True, True, True]" True $ C.and [True, True, True] , test "or []" False $ C.or [] , test "or [True]" True $ C.or [True] , test "or [False]" False $ C.or [False] , test "or [True, True]" True $ C.or [True, True] , test "or [True, False]" True $ C.or [True, False] , test "or [False, True]" True $ C.or [False, True] , test "or [False, False]" False $ C.or [False, False] , test "or [False, False, True]" True $ C.or [False, False, True] , test "[8,0] ++ [ ]" [8,0] $ [8,0] C.++ [] , test "[ ] ++ [6,4]" [6,4] $ [ ] C.++ [6,4] , test "[8,0] ++ [6,4]" [8,0,6,4] $ [8,0] C.++ [6,4] ] Section 5 -> [ display "#### Section 5" , test "map (+1) []" [] $ C.map (+1) [] , test "map (+1) [8,0,6,4]" [9,1,7,5] $ C.map (+1) [8,0,6,4] , test "filter (>5) []" [] $ C.filter (>5) [] , test "filter (>5) [8,0,6,4]" [8,6] $ C.filter (>5) [8,0,6,4] , testI "foldl (-) 1 [10]" (-9) $ C.foldl (-) 1 [10] , testI "foldl (-) 0 [1,2,3,4]" (-10) $ C.foldl (-) 0 [1,2,3,4] , test "foldl (++) \"_\" [\"A\", \"B\", \"C\"]" "_ABC" $ C.foldl (++) "_" ["A","B","C"] , testI "foldr (-) 1 [10]" 9 $ C.foldr (-) 1 [10] , testI "foldr (-) 0 [1,2,3,4]" (-2) $ C.foldr (-) 0 [1,2,3,4] , test "foldr (++) \"_\" [\"A\", \"B\", \"C\"]" "ABC_" $ C.foldr (++) "_" ["A","B","C"] ] Section 6 -> [ display "#### Section 6" , test "safeHead []" Nothing $ C.safeHead ([] :: [Int]) , test "safeHead [8,0,6]" (Just 8) $ C.safeHead [8,0,6] , test "isNothing (Just 42)" False $ C.isNothing (Just 42) , test "isNothing Nothing" True $ C.isNothing Nothing , testI "fromMaybe 0 (Just 40)" 40 $ C.fromMaybe 0 (Just 40) , testI "fromMaybe 0 Nothing" 0 $ C.fromMaybe 0 Nothing , testI "maybe 0 (+2) (Just 40)" 42 $ C.maybe 0 (+2) (Just 40) , testI "maybe 0 (+2) Nothing" 0 $ C.maybe 0 (+2) Nothing ] Section unexpected -> [ display $ "Unexpected section requested: " ++ show unexpected ] parseOpts :: IO Options parseOpts = do args <- getArgs case getOpt Permute options args of (o, [], []) -> do let defaultOptions = Options { optSections = [] } opts <- foldM (flip id) defaultOptions o let opts' = opts { optSections = if null $ optSections opts then [minBound .. maxBound] else optSections opts } return opts' (_, nonOptions@(_:_), _) -> do hPrintf stderr " Unexpected non-option argument(s): %s\n" (intercalate ", " $ map show nonOptions) hPutStrLn stderr $ usageInfo usageHeader options exitFailure (_, _, errs@(_:_)) -> do hPutStrLn stderr (concat errs ++ usageInfo usageHeader options) exitFailure main :: IO () main = do opts <- parseOpts results <- sequence $ tests (optSections opts) let failing = length . filter not $ results when (failing > 0) exitFailure
null
https://raw.githubusercontent.com/rsharifnasab/my-learning/8555583a772c96e334e3fdace5a295a21c31ea8b/haskell/google-haskell/haskell_101/Main.hs
haskell
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. term color options tests main
Copyright 2019 Google LLC Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , # LANGUAGE CPP , LambdaCase , StandaloneDeriving # # OPTIONS_GHC -fno - warn - type - defaults # # OPTIONS_GHC -fno - warn - missing - signatures # # OPTIONS_GHC -fno - warn - orphans # import Control.Exception import Control.Monad import Data.List (intercalate) import System.Console.GetOpt (ArgDescr(ReqArg, NoArg) , ArgOrder(Permute), OptDescr(Option) , getOpt, usageInfo ) import System.Environment (getArgs) import System.Exit import System.IO (Handle, hPutStr, hPutStrLn, stderr, stdout) import System.Posix.IO (stdOutput) import System.Posix.Terminal (queryTerminal) import System.Timeout import Text.Printf #ifdef SOLUTION import qualified Solution as C #else import qualified Codelab as C #endif deriving instance Eq C.Minutes deriving instance Show C.Minutes type TermColor = String kR = "\x1b[31;1m" kG = "\x1b[32;1m" putTag :: String -> TermColor -> IO () putTag = hPutTag stdout hPutTag :: Handle -> String -> TermColor -> IO () hPutTag h tag color = do isTTY <- queryTerminal stdOutput if isTTY then hPutStr h $ "[" ++ color ++ tag ++ "\x1b[0m]" else hPutStr h $ "[" ++ tag ++ "]" newtype Section = Section Int deriving Eq instance Bounded Section where minBound = Section 1 maxBound = Section 6 instance Ord Section where compare (Section s1) (Section s2) = compare s1 s2 instance Enum Section where toEnum = Section fromEnum (Section i) = i validSection :: Section -> Bool validSection s = s >= minBound && s <= maxBound newtype Options = Options { optSections :: [Section] } options :: [OptDescr (Options -> IO Options)] options = [ Option ['s'] ["section"] (ReqArg (\v opts -> do let i = read v unless (validSection (Section i)) $ do hPutTag stderr "Error" kR hPutStrLn stderr $ " Invalid section number: " ++ v let (Section from, Section to) = (minBound, maxBound) hPrintf stderr "Valid section numbers: %d..%d\n" from to exitFailure return $ opts { optSections = optSections opts ++ [Section i] } ) "<id>" ) "Include section <id> in the run", Option ['h'] ["help"] (NoArg (\_ -> do hPutStrLn stderr (usageInfo usageHeader options) exitSuccess )) "Show this help message" ] usageHeader :: String usageHeader = "Usage: ./main [-h] [-s|--section <id>] [--help]" ifError :: (String -> a) -> ErrorCall -> a #if __GLASGOW_HASKELL__ < 800 ifError f (ErrorCall s) = f s #else ifError f (ErrorCallWithLocation s _) = f s #endif timeLimit :: Int 10 ^ 6 microseconds = 1 second test :: (Show a, Eq a) => String -> a -> a -> IO Bool test name expected actual = do let checkEq = if expected == actual then True <$ onSuccess else False <$ onError runTest = timeout timeLimit $ catch checkEq $ ifError $ (False <$) . onFailure void $ printf "%-42s" name result <- runTest >>= maybe (False <$ onTimeout) return putStrLn "" return result where onSuccess = putTag "OK" kG >> printf " got: %s" (show actual) onError = putTag "KO" kR >> printf " want: %s; got: %s" (show expected) (show actual) onFailure s = putTag "!!" kR >> printf " error: %s" s onTimeout = putTag "??" kR >> putStr " (timeout)" testI :: String -> Int -> Int -> IO Bool testI = test tests :: [Section] -> [IO Bool] tests sections = let display s = True <$ putStrLn s in intercalate [display ""] $ flip map sections $ \case Section 1 -> [ display "#### Section 1" , test "add 1 2" 3 $ C.add 1 2 , test "subtract 7 2" 5 $ C.subtract 7 2 , test "double 3" 6 $ C.double 3 , test "multiply 3 11" 33 $ C.multiply 3 11 , test "divide 9 2" 4.5 $ C.divide 9 2 , test "divide 8 4" 2 $ C.divide 8 4 , test "factorial 30" (product [1..30]) $ C.factorial 30 , test "gcd 12 4" 4 $ C.gcd 12 4 , test "gcd 17 7" 1 $ C.gcd 17 7 ] Section 2 -> [ display "#### Section 2" , test "hours (Minutes 271)" 4 $ C.hours (C.Minutes 271) , test "hours (Minutes 15)" 0 $ C.hours (C.Minutes 15) , test "timeDistance (Minutes 15) (Minutes 25)" (C.Minutes 10) $ C.timeDistance (C.Minutes 15) (C.Minutes 25) , test "timeDistance (Minutes 99) (Minutes 47)" (C.Minutes 52) $ C.timeDistance (C.Minutes 99) (C.Minutes 47) , test "pointDistance (1, 1) (1, 3)" 2 $ C.pointDistance (1, 1) (1, 3) , test "pointDistance (3, 4) (0, 0)" 5 $ C.pointDistance (3, 4) (0, 0) ] Section 3 -> [ display "#### Section 3" , test "null []" True $ C.null [] , test "null [8,0,6]" False $ C.null [8,0,6] , testI "head [8,0,6]" 8 $ C.head [8,0,6] , test "tail [8,0,6]" [0,6] $ C.tail [8,0,6] ] Section 4 -> [ display "#### Section 4" , testI "length []" 0 $ C.length [] , testI "length [8,0,6]" 3 $ C.length [8,0,6] , test "and []" True $ C.and [] , test "and [True]" True $ C.and [True] , test "and [False]" False $ C.and [False] , test "and [True, True]" True $ C.and [True, True] , test "and [True, False]" False $ C.and [True, False] , test "and [False, True]" False $ C.and [False, True] , test "and [False, False]" False $ C.and [False, False] , test "and [True, True, True]" True $ C.and [True, True, True] , test "or []" False $ C.or [] , test "or [True]" True $ C.or [True] , test "or [False]" False $ C.or [False] , test "or [True, True]" True $ C.or [True, True] , test "or [True, False]" True $ C.or [True, False] , test "or [False, True]" True $ C.or [False, True] , test "or [False, False]" False $ C.or [False, False] , test "or [False, False, True]" True $ C.or [False, False, True] , test "[8,0] ++ [ ]" [8,0] $ [8,0] C.++ [] , test "[ ] ++ [6,4]" [6,4] $ [ ] C.++ [6,4] , test "[8,0] ++ [6,4]" [8,0,6,4] $ [8,0] C.++ [6,4] ] Section 5 -> [ display "#### Section 5" , test "map (+1) []" [] $ C.map (+1) [] , test "map (+1) [8,0,6,4]" [9,1,7,5] $ C.map (+1) [8,0,6,4] , test "filter (>5) []" [] $ C.filter (>5) [] , test "filter (>5) [8,0,6,4]" [8,6] $ C.filter (>5) [8,0,6,4] , testI "foldl (-) 1 [10]" (-9) $ C.foldl (-) 1 [10] , testI "foldl (-) 0 [1,2,3,4]" (-10) $ C.foldl (-) 0 [1,2,3,4] , test "foldl (++) \"_\" [\"A\", \"B\", \"C\"]" "_ABC" $ C.foldl (++) "_" ["A","B","C"] , testI "foldr (-) 1 [10]" 9 $ C.foldr (-) 1 [10] , testI "foldr (-) 0 [1,2,3,4]" (-2) $ C.foldr (-) 0 [1,2,3,4] , test "foldr (++) \"_\" [\"A\", \"B\", \"C\"]" "ABC_" $ C.foldr (++) "_" ["A","B","C"] ] Section 6 -> [ display "#### Section 6" , test "safeHead []" Nothing $ C.safeHead ([] :: [Int]) , test "safeHead [8,0,6]" (Just 8) $ C.safeHead [8,0,6] , test "isNothing (Just 42)" False $ C.isNothing (Just 42) , test "isNothing Nothing" True $ C.isNothing Nothing , testI "fromMaybe 0 (Just 40)" 40 $ C.fromMaybe 0 (Just 40) , testI "fromMaybe 0 Nothing" 0 $ C.fromMaybe 0 Nothing , testI "maybe 0 (+2) (Just 40)" 42 $ C.maybe 0 (+2) (Just 40) , testI "maybe 0 (+2) Nothing" 0 $ C.maybe 0 (+2) Nothing ] Section unexpected -> [ display $ "Unexpected section requested: " ++ show unexpected ] parseOpts :: IO Options parseOpts = do args <- getArgs case getOpt Permute options args of (o, [], []) -> do let defaultOptions = Options { optSections = [] } opts <- foldM (flip id) defaultOptions o let opts' = opts { optSections = if null $ optSections opts then [minBound .. maxBound] else optSections opts } return opts' (_, nonOptions@(_:_), _) -> do hPrintf stderr " Unexpected non-option argument(s): %s\n" (intercalate ", " $ map show nonOptions) hPutStrLn stderr $ usageInfo usageHeader options exitFailure (_, _, errs@(_:_)) -> do hPutStrLn stderr (concat errs ++ usageInfo usageHeader options) exitFailure main :: IO () main = do opts <- parseOpts results <- sequence $ tests (optSections opts) let failing = length . filter not $ results when (failing > 0) exitFailure
b7f7f014e04aefee38a6b876a652dae46003d68650ef16c4c94ca56fc4ab7c4a
xvw/preface
monad_plus.mli
(** Functors that generate a suite for a [Monad_plus]. *) module Suite (R : Model.COVARIANT_1) (F : Preface_specs.MONAD_PLUS with type 'a t = 'a R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE module Suite_monoidal (R : Model.COVARIANT_1) (F : Preface_specs.MONAD_PLUS with type 'a t = 'a R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE module Suite_left_absorption (R : Model.COVARIANT_1) (F : Preface_specs.MONAD_PLUS with type 'a t = 'a R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE module Suite_left_distributivity (R : Model.COVARIANT_1) (F : Preface_specs.MONAD_PLUS with type 'a t = 'a R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE module Suite_left_catch (R : Model.COVARIANT_1) (F : Preface_specs.MONAD_PLUS with type 'a t = 'a R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE
null
https://raw.githubusercontent.com/xvw/preface/84a297e1ee2967ad4341dca875da8d2dc6d7638c/lib/preface_qcheck/monad_plus.mli
ocaml
* Functors that generate a suite for a [Monad_plus].
module Suite (R : Model.COVARIANT_1) (F : Preface_specs.MONAD_PLUS with type 'a t = 'a R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE module Suite_monoidal (R : Model.COVARIANT_1) (F : Preface_specs.MONAD_PLUS with type 'a t = 'a R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE module Suite_left_absorption (R : Model.COVARIANT_1) (F : Preface_specs.MONAD_PLUS with type 'a t = 'a R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE module Suite_left_distributivity (R : Model.COVARIANT_1) (F : Preface_specs.MONAD_PLUS with type 'a t = 'a R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE module Suite_left_catch (R : Model.COVARIANT_1) (F : Preface_specs.MONAD_PLUS with type 'a t = 'a R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) : Model.SUITE
52d77d9d027eceec04bce1f6e353b44079d19cdfa1f18d30a6a82939c3a69b88
tmfg/mmtis-national-access-point
user.cljs
(ns ote.views.user "User's own info view" (:require [reagent.core :as r] [ote.ui.form :as form] [ote.db.user :as user] [ote.localization :refer [tr tr-key]] [ote.ui.buttons :as buttons] [ote.app.controller.login :as lc] [clojure.string :as str] [ote.ui.list-header :as list-header] [ote.ui.notification :as notification] [ote.app.controller.front-page :as fp] [stylefy.core :as stylefy] [ote.style.base :as style-base])) (defn merge-user-data [user form-data] (merge (select-keys user #{:username :name :email}) form-data)) (defn user "Edit own user info" [e! app] (r/create-class {:component-did-mount #(e! (lc/->UserSettingsInit false)) :component-will-unmount #(e! (lc/->UserSettingsInit false)) :reagent-render (fn [e! {:keys [form-data email-taken password-incorrect? edit-response] :as user}] [:div.user-edit.col-xs-12.col-sm-8.col-md-8.col-lg-6 [list-header/header app (tr [:common-texts :user-menu-profile])] (if (:success? edit-response) ;; After submitting a successful email change action display only info box and action button [:div (when (:email-changed? edit-response) [:div {:style {:margin-bottom "2rem"}} [notification/notification {:text (str (tr [:user :change-email-confirmation-sent]) " " (:new-email edit-response)) :type :success}]]) [:a (merge {:href (str "#/own-services") :on-click #(do (.preventDefault %) (e! (fp/->ChangePage :own-services nil)))} (stylefy/use-style style-base/blue-link-with-icon)) (tr [:front-page :move-to-services-page])]] ;; When arriving to view or after a failed form submission: display form. [form/form {:update! #(e! (lc/->UpdateUser %)) :name->label (tr-key [:register :fields]) :footer-fn (fn [data] [:div {:style {:margin-top "1em"}} [buttons/save {:on-click #(e! (lc/->SaveUser (merge-user-data user (form/without-form-metadata data)))) :disabled (form/disable-save? data)} (tr [:buttons :save])] [buttons/cancel {:on-click #(e! (lc/->UserSettingsInit true))} (tr [:buttons :cancel])]])} [(form/group {:expandable? false :columns 3 :layout :raw :card? false} {:name :name :type :string :required? true :full-width? true :placeholder (tr [:register :placeholder :name]) :should-update-check form/always-update} {:name :email :type :string :autocomplete "email" :required? true :full-width? true :placeholder (tr [:register :placeholder :email]) :validate [(fn [data _] (when (not (user/email-valid? data)) (tr [:common-texts :required-field]))) (fn [data _] (when (and email-taken (email-taken data)) (tr [:register :errors :email-taken])))] :should-update-check form/always-update} (when (and (not (clojure.string/blank? (:email form-data))) (not= (:email form-data) (:email app))) (form/info (tr [:user :change-email-warning]))) (form/subtitle :h3 (tr [:register :change-password]) {:margin-top "3rem"}) {:name :password :type :string :password? true :label (tr [:register :fields :new-password]) :full-width? true :validate [(fn [data _] (when (and (not (str/blank? data)) (not (user/password-valid? data))) (tr [:register :errors :password-not-valid])))] :should-update-check form/always-update} {:name :confirm :type :string :password? true :full-width? true :validate [(fn [data row] (when (not= data (:password row)) (tr [:register :errors :passwords-must-match])))] :should-update-check form/always-update} ;; Show current password field if it is required for update (form/subtitle :h3 (tr [:register :confirm-changes]) {:margin-top "3rem"}) {:name :current-password :type :string :password? true :full-width? true :required? (seq (::form/modified form-data)) :validate [(fn [_ _] (when password-incorrect? (tr [:login :error :incorrect-password])))]})] (merge-user-data user form-data)])])}))
null
https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/a86cc890ffa1fe4f773083be5d2556e87a93d975/ote/src/cljs/ote/views/user.cljs
clojure
After submitting a successful email change action display only info box and action button When arriving to view or after a failed form submission: display form. Show current password field if it is required for update
(ns ote.views.user "User's own info view" (:require [reagent.core :as r] [ote.ui.form :as form] [ote.db.user :as user] [ote.localization :refer [tr tr-key]] [ote.ui.buttons :as buttons] [ote.app.controller.login :as lc] [clojure.string :as str] [ote.ui.list-header :as list-header] [ote.ui.notification :as notification] [ote.app.controller.front-page :as fp] [stylefy.core :as stylefy] [ote.style.base :as style-base])) (defn merge-user-data [user form-data] (merge (select-keys user #{:username :name :email}) form-data)) (defn user "Edit own user info" [e! app] (r/create-class {:component-did-mount #(e! (lc/->UserSettingsInit false)) :component-will-unmount #(e! (lc/->UserSettingsInit false)) :reagent-render (fn [e! {:keys [form-data email-taken password-incorrect? edit-response] :as user}] [:div.user-edit.col-xs-12.col-sm-8.col-md-8.col-lg-6 [list-header/header app (tr [:common-texts :user-menu-profile])] (if (:success? edit-response) [:div (when (:email-changed? edit-response) [:div {:style {:margin-bottom "2rem"}} [notification/notification {:text (str (tr [:user :change-email-confirmation-sent]) " " (:new-email edit-response)) :type :success}]]) [:a (merge {:href (str "#/own-services") :on-click #(do (.preventDefault %) (e! (fp/->ChangePage :own-services nil)))} (stylefy/use-style style-base/blue-link-with-icon)) (tr [:front-page :move-to-services-page])]] [form/form {:update! #(e! (lc/->UpdateUser %)) :name->label (tr-key [:register :fields]) :footer-fn (fn [data] [:div {:style {:margin-top "1em"}} [buttons/save {:on-click #(e! (lc/->SaveUser (merge-user-data user (form/without-form-metadata data)))) :disabled (form/disable-save? data)} (tr [:buttons :save])] [buttons/cancel {:on-click #(e! (lc/->UserSettingsInit true))} (tr [:buttons :cancel])]])} [(form/group {:expandable? false :columns 3 :layout :raw :card? false} {:name :name :type :string :required? true :full-width? true :placeholder (tr [:register :placeholder :name]) :should-update-check form/always-update} {:name :email :type :string :autocomplete "email" :required? true :full-width? true :placeholder (tr [:register :placeholder :email]) :validate [(fn [data _] (when (not (user/email-valid? data)) (tr [:common-texts :required-field]))) (fn [data _] (when (and email-taken (email-taken data)) (tr [:register :errors :email-taken])))] :should-update-check form/always-update} (when (and (not (clojure.string/blank? (:email form-data))) (not= (:email form-data) (:email app))) (form/info (tr [:user :change-email-warning]))) (form/subtitle :h3 (tr [:register :change-password]) {:margin-top "3rem"}) {:name :password :type :string :password? true :label (tr [:register :fields :new-password]) :full-width? true :validate [(fn [data _] (when (and (not (str/blank? data)) (not (user/password-valid? data))) (tr [:register :errors :password-not-valid])))] :should-update-check form/always-update} {:name :confirm :type :string :password? true :full-width? true :validate [(fn [data row] (when (not= data (:password row)) (tr [:register :errors :passwords-must-match])))] :should-update-check form/always-update} (form/subtitle :h3 (tr [:register :confirm-changes]) {:margin-top "3rem"}) {:name :current-password :type :string :password? true :full-width? true :required? (seq (::form/modified form-data)) :validate [(fn [_ _] (when password-incorrect? (tr [:login :error :incorrect-password])))]})] (merge-user-data user form-data)])])}))
2520954f95c145a9ec59a6cca64d27930481f0c0db9500c20587fa1e838d59bd
GaloisInc/json
Parsec.hs
| Parse JSON values using the Parsec combinators . module Text.JSON.Parsec ( p_value , p_null , p_boolean , p_array , p_string , p_object , p_number , p_js_string , p_js_object , p_jvalue , module Text.ParserCombinators.Parsec ) where import Text.JSON.Types import Text.ParserCombinators.Parsec import Control.Monad import Data.Char import Numeric p_value :: CharParser () JSValue p_value = spaces **> p_jvalue tok :: CharParser () a -> CharParser () a tok p = p <** spaces p_jvalue :: CharParser () JSValue p_jvalue = (JSNull <$$ p_null) <|> (JSBool <$$> p_boolean) <|> (JSArray <$$> p_array) <|> (JSString <$$> p_js_string) <|> (JSObject <$$> p_js_object) <|> (JSRational False <$$> p_number) <?> "JSON value" p_null :: CharParser () () p_null = tok (string "null") >> return () p_boolean :: CharParser () Bool p_boolean = tok ( (True <$$ string "true") <|> (False <$$ string "false") ) p_array :: CharParser () [JSValue] p_array = between (tok (char '[')) (tok (char ']')) $ p_jvalue `sepBy` tok (char ',') p_string :: CharParser () String p_string = between (tok (char '"')) (tok (char '"')) (many p_char) where p_char = (char '\\' >> p_esc) <|> (satisfy (\x -> x /= '"' && x /= '\\')) p_esc = ('"' <$$ char '"') <|> ('\\' <$$ char '\\') <|> ('/' <$$ char '/') <|> ('\b' <$$ char 'b') <|> ('\f' <$$ char 'f') <|> ('\n' <$$ char 'n') <|> ('\r' <$$ char 'r') <|> ('\t' <$$ char 't') <|> (char 'u' **> p_uni) <?> "escape character" p_uni = check =<< count 4 (satisfy isHexDigit) where check x | code <= max_char = return (toEnum code) | otherwise = mzero where code = fst $ head $ readHex x max_char = fromEnum (maxBound :: Char) p_object :: CharParser () [(String,JSValue)] p_object = between (tok (char '{')) (tok (char '}')) $ p_field `sepBy` tok (char ',') where p_field = (,) <$$> (p_string <** tok (char ':')) <**> p_jvalue p_number :: CharParser () Rational p_number = tok $ do s <- getInput case readSigned readFloat s of [(n,s1)] -> n <$$ setInput s1 _ -> mzero p_js_string :: CharParser () JSString p_js_string = toJSString <$$> p_string p_js_object :: CharParser () (JSObject JSValue) p_js_object = toJSObject <$$> p_object -------------------------------------------------------------------------------- XXX : Because Parsec is not Applicative yet ... (<**>) :: CharParser () (a -> b) -> CharParser () a -> CharParser () b (<**>) = ap (**>) :: CharParser () a -> CharParser () b -> CharParser () b (**>) = (>>) (<**) :: CharParser () a -> CharParser () b -> CharParser () a m <** n = do x <- m; _ <- n; return x (<$$>) :: (a -> b) -> CharParser () a -> CharParser () b (<$$>) = fmap (<$$) :: a -> CharParser () b -> CharParser () a x <$$ m = m >> return x
null
https://raw.githubusercontent.com/GaloisInc/json/329bbce8fd68a04a5377f48102c37d28160b246b/Text/JSON/Parsec.hs
haskell
------------------------------------------------------------------------------
| Parse JSON values using the Parsec combinators . module Text.JSON.Parsec ( p_value , p_null , p_boolean , p_array , p_string , p_object , p_number , p_js_string , p_js_object , p_jvalue , module Text.ParserCombinators.Parsec ) where import Text.JSON.Types import Text.ParserCombinators.Parsec import Control.Monad import Data.Char import Numeric p_value :: CharParser () JSValue p_value = spaces **> p_jvalue tok :: CharParser () a -> CharParser () a tok p = p <** spaces p_jvalue :: CharParser () JSValue p_jvalue = (JSNull <$$ p_null) <|> (JSBool <$$> p_boolean) <|> (JSArray <$$> p_array) <|> (JSString <$$> p_js_string) <|> (JSObject <$$> p_js_object) <|> (JSRational False <$$> p_number) <?> "JSON value" p_null :: CharParser () () p_null = tok (string "null") >> return () p_boolean :: CharParser () Bool p_boolean = tok ( (True <$$ string "true") <|> (False <$$ string "false") ) p_array :: CharParser () [JSValue] p_array = between (tok (char '[')) (tok (char ']')) $ p_jvalue `sepBy` tok (char ',') p_string :: CharParser () String p_string = between (tok (char '"')) (tok (char '"')) (many p_char) where p_char = (char '\\' >> p_esc) <|> (satisfy (\x -> x /= '"' && x /= '\\')) p_esc = ('"' <$$ char '"') <|> ('\\' <$$ char '\\') <|> ('/' <$$ char '/') <|> ('\b' <$$ char 'b') <|> ('\f' <$$ char 'f') <|> ('\n' <$$ char 'n') <|> ('\r' <$$ char 'r') <|> ('\t' <$$ char 't') <|> (char 'u' **> p_uni) <?> "escape character" p_uni = check =<< count 4 (satisfy isHexDigit) where check x | code <= max_char = return (toEnum code) | otherwise = mzero where code = fst $ head $ readHex x max_char = fromEnum (maxBound :: Char) p_object :: CharParser () [(String,JSValue)] p_object = between (tok (char '{')) (tok (char '}')) $ p_field `sepBy` tok (char ',') where p_field = (,) <$$> (p_string <** tok (char ':')) <**> p_jvalue p_number :: CharParser () Rational p_number = tok $ do s <- getInput case readSigned readFloat s of [(n,s1)] -> n <$$ setInput s1 _ -> mzero p_js_string :: CharParser () JSString p_js_string = toJSString <$$> p_string p_js_object :: CharParser () (JSObject JSValue) p_js_object = toJSObject <$$> p_object XXX : Because Parsec is not Applicative yet ... (<**>) :: CharParser () (a -> b) -> CharParser () a -> CharParser () b (<**>) = ap (**>) :: CharParser () a -> CharParser () b -> CharParser () b (**>) = (>>) (<**) :: CharParser () a -> CharParser () b -> CharParser () a m <** n = do x <- m; _ <- n; return x (<$$>) :: (a -> b) -> CharParser () a -> CharParser () b (<$$>) = fmap (<$$) :: a -> CharParser () b -> CharParser () a x <$$ m = m >> return x
12d4b59d251c048b024344a60467792f54dbc780b40272f5cd74bc8f3fdd94ea
gatlin/psilo
Syntax.hs
module Lib.Syntax ( Symbol , builtin_syms , CoreExpr , CoreAst(..) , TopLevel(..) , SurfaceExpr , SurfaceAst(..) , aInt , aFloat , aBool , aId , aApp , aFun , aIf , aDef , AnnotatedExpr , annotated , TypeLit(..) , fromTypeLit , LiftedExpr(..) , liftExpr , showSignatures ) where import Lib.Syntax.Annotated import Lib.Syntax.Core import Lib.Syntax.Lifted import Lib.Syntax.Surface import Lib.Syntax.Symbol import Lib.Syntax.TopLevel import Lib.Types.Class import Lib.Types.Kind import Lib.Types.Scheme import Lib.Types.Type import Lib.Types.TypeEnv (TypeEnv (..), generalize) import Control.Comonad.Cofree import Control.Monad (join) import Control.Monad.Free import Control.Monad.State import Data.Map (Map) import qualified Data.Map as M
null
https://raw.githubusercontent.com/gatlin/psilo/ed2aa5e357011bbb0a566c201dbfb87edb0e3209/src/Lib/Syntax.hs
haskell
module Lib.Syntax ( Symbol , builtin_syms , CoreExpr , CoreAst(..) , TopLevel(..) , SurfaceExpr , SurfaceAst(..) , aInt , aFloat , aBool , aId , aApp , aFun , aIf , aDef , AnnotatedExpr , annotated , TypeLit(..) , fromTypeLit , LiftedExpr(..) , liftExpr , showSignatures ) where import Lib.Syntax.Annotated import Lib.Syntax.Core import Lib.Syntax.Lifted import Lib.Syntax.Surface import Lib.Syntax.Symbol import Lib.Syntax.TopLevel import Lib.Types.Class import Lib.Types.Kind import Lib.Types.Scheme import Lib.Types.Type import Lib.Types.TypeEnv (TypeEnv (..), generalize) import Control.Comonad.Cofree import Control.Monad (join) import Control.Monad.Free import Control.Monad.State import Data.Map (Map) import qualified Data.Map as M
40f392776a7ed114d7ad9966a0d8256194372116c5692fa54805a083e40957a4
dmitryvk/sbcl-win32-threads
debug-info.lisp
;;;; structures used for recording debugger information This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!C") ;;;; flags for compiled debug variables FIXME : old CMU CL representation follows : ;;; Compiled debug variables are in a packed binary representation in the ;;; DEBUG-FUN-VARS: ;;; single byte of boolean flags: uninterned name ;;; packaged name ;;; environment-live ;;; has distinct save location ;;; has ID (name not unique in this fun) ;;; minimal debug-info argument (name generated as ARG-0, ...) ;;; deleted: placeholder for unused minimal argument ;;; [name length in bytes (as var-length integer), if not minimal] ;;; [...name bytes..., if not minimal] ;;; [if packaged, var-length integer that is package name length] ;;; ...package name bytes...] ;;; [If has ID, ID as var-length integer] SC - Offset of primary location ( as var - length integer ) [ If has save SC , SC - OFFSET of save location ( as var - length integer ) ] FIXME : The first two are no longer used in SBCL . ;;;(defconstant compiled-debug-var-uninterned #b00000001) ( defconstant compiled - debug - var - packaged # b00000010 ) (def!constant compiled-debug-var-environment-live #b00000100) (def!constant compiled-debug-var-save-loc-p #b00001000) (def!constant compiled-debug-var-id-p #b00010000) (def!constant compiled-debug-var-minimal-p #b00100000) (def!constant compiled-debug-var-deleted-p #b01000000) ;;;; compiled debug blocks ;;;; ;;;; Compiled debug blocks are in a packed binary representation in the ;;;; DEBUG-FUN-BLOCKS: ;;;; number of successors + bit flags (single byte) ;;;; elsewhere-p ;;;; ...ordinal number of each successor in the function's blocks vector... ;;;; number of locations in this block kind of first location ( single byte ) delta from previous PC ( or from 0 if first location in function . ) [ offset of first top level form , if no function TLF - NUMBER ] form number of first source form first live mask ( length in bytes determined by number of VARIABLES ) ;;;; ...more <kind, delta, top level form offset, form-number, live-set> ;;;; tuples... (defconstant-eqx compiled-debug-block-nsucc-byte (byte 2 0) #'equalp) (def!constant compiled-debug-block-elsewhere-p #b00000100) (defconstant-eqx compiled-code-location-kind-byte (byte 4 0) #'equalp) (defparameter *compiled-code-location-kinds* #(:unknown-return :known-return :internal-error :non-local-exit :block-start :call-site :single-value-return :non-local-entry :step-before-vop)) ;;;; DEBUG-FUN objects (def!struct (debug-fun (:constructor nil))) (def!struct (compiled-debug-fun (:include debug-fun) #-sb-xc-host (:pure t)) : Courtesy of more than a decade of , ah , organic growth in CMU CL , there are two distinct -- but coupled -- mechanisms to finding the name of a function . The slot here is one mechanism ( used in CMU CL to look up names in the debugger , e.g. in BACKTRACE ) . The other mechanism is the NAME slot in function primitive objects ( used in CMU CL to look up names elsewhere , e.g. in CL : FUNCTION - LAMBDA - EXPRESSION and in CL : DESCRIBE ) . ;; ;; They're coupled by the way that DEBUG-FUN objects are looked up. ;; A list of DEBUG-FUN objects is maintained for each COMPONENT. To ;; figure out which DEBUG-FUN object corresponds to your FUNCTION object , you compare the name values of each . -- WHN 2001 - 12 - 20 (name (missing-arg) :type (or simple-string cons symbol)) ;; The kind of function (same as FUNCTIONAL-KIND): (kind nil :type (member nil :optional :external :toplevel :cleanup)) ;; a description of variable locations for this function, in alphabetical ;; order by name; or NIL if no information is available ;; ;; The variable entries are alphabetically ordered. This ordering is used in lifetime info to refer to variables : the first entry is 0 , the second entry is 1 , etc . Variable numbers are * not * the ;; byte index at which the representation of the location starts. ;; ;; Each entry is: * a FLAGS value , which is a FIXNUM with various ;; COMPILED-DEBUG-FUN-FOO bits set ;; * the symbol which names this variable, unless debug info ;; is minimal * the variable ID , when it has one * SC - offset of primary location , if it has one * SC - offset of save location , if it has one (vars nil :type (or simple-vector null)) ;; a vector of the packed binary representation of the ;; COMPILED-DEBUG-BLOCKs in this function, in the order that the blocks were emitted . The first block is the start of the ;; function. This slot may be NIL to save space. ;; ;; FIXME: The "packed binary representation" description in the ;; comment above is the same as the description of the old representation of VARIABLES which does n't work properly in SBCL ;; (because it doesn't transform correctly under package renaming). ;; Check whether this slot's data might have the same problem that ;; that slot's data did. (blocks nil :type (or (simple-array (unsigned-byte 8) (*)) null)) ;; If all code locations in this function are in the same top level ;; form, then this is the number of that form, otherwise NIL. If NIL , then each code location represented in the BLOCKS specifies the TLF number . (tlf-number nil :type (or index null)) ;; a vector describing the variables that the argument values are ;; stored in within this function. The locations are represented by ;; the ordinal number of the entry in the VARIABLES slot value. The ;; locations are in the order that the arguments are actually passed ;; in, but special marker symbols can be interspersed to indicate ;; the original call syntax: ;; ;; DELETED ;; There was an argument to the function in this position, but it was ;; deleted due to lack of references. The value cannot be recovered. ;; ;; SUPPLIED-P ;; The following location is the supplied-p value for the preceding ;; keyword or optional. ;; ;; OPTIONAL-ARGS ;; Indicates that following unqualified args are optionals, not required. ;; ;; REST-ARG ;; The following location holds the list of rest args. ;; ;; MORE-ARG The following two locations are the more arg context and count . ;; ;; <any other symbol> ;; The following location is the value of the &KEY argument with the ;; specified name. ;; ;; This may be NIL to save space. If no symbols are present, then ;; this will be represented with an I-vector with sufficiently large ;; element type. If this is :MINIMAL, then this means that the ;; VARIABLES are all required arguments, and are in the order they ;; appear in the VARIABLES vector. In other words, :MINIMAL stands ;; in for a vector where every element holds its index. (arguments nil :type (or (simple-array * (*)) (member :minimal nil))) There are three alternatives for this slot : ;; a VECTOR ;; A vector of SC-OFFSETS describing the return locations. The ;; vector element type is chosen to hold the largest element. ;; ;; :STANDARD ;; The function returns using the standard unknown-values convention. ;; ;; :FIXED ;; The function returns using the fixed-values convention, but ;; in order to save space, we elected not to store a vector. (returns :fixed :type (or (simple-array * (*)) (member :standard :fixed))) SC - OFFSETs describing where the return PC and return FP are kept . (return-pc (missing-arg) :type sc-offset) (old-fp (missing-arg) :type sc-offset) SC - OFFSET for the number stack FP in this function , or NIL if no ;; NFP allocated. (nfp nil :type (or sc-offset null)) ;; The earliest PC in this function at which the environment is properly ;; initialized (arguments moved from passing locations, etc.) (start-pc (missing-arg) :type index) ;; The start of elsewhere code for this function (if any.) (elsewhere-pc (missing-arg) :type index)) ;;;; minimal debug function ;;; The minimal debug info format compactly represents debug-info for some ;;; cases where the other debug info (variables, blocks) is small enough so ;;; that the per-function overhead becomes relatively large. The minimal ;;; debug-info format can represent any function at level 0, and any fixed-arg function at level 1 . ;;; ;;; In the minimal format, the debug functions and function map are ;;; packed into a single byte-vector which is placed in the ;;; COMPILED-DEBUG-INFO-FUN-MAP. Because of this, all functions in a ;;; component must be representable in minimal format for any function ;;; to actually be dumped in minimal format. The vector is a sequence ;;; of records in this format: ;;; name representation + kind + return convention (single byte) ;;; bit flags (single byte) setf , nfp , variables ;;; [package name length (as var-length int), if name is packaged] ;;; [...package name bytes, if name is packaged] ;;; [name length (as var-length int), if there is a name] ;;; [...name bytes, if there is a name] ;;; [variables length (as var-length int), if variables flag] ;;; [...bytes holding variable descriptions] If variables are dumped ( level 1 ) , then the variables are all ;;; arguments (in order) with the minimal-arg bit set. ;;; [If returns is specified, then the number of return values] ;;; [...sequence of var-length ints holding sc-offsets of the return ;;; value locations, if fixed return values are specified.] ;;; return-pc location sc-offset (as var-length int) ;;; old-fp location sc-offset (as var-length int) ;;; [nfp location sc-offset (as var-length int), if nfp flag] ;;; code-start-pc (as a var-length int) ;;; This field implicitly encodes start of this function's code in the ;;; function map, as a delta from the previous function's code start. If the first function in the component , then this is the delta from ;;; 0 (i.e. the absolute offset.) ;;; start-pc (as a var-length int) ;;; This encodes the environment start PC as an offset from the ;;; code-start PC. ;;; elsewhere-pc ;;; This encodes the elsewhere code start for this function, as a delta ;;; from the previous function's elsewhere code start. (i.e. the ;;; encoding is the same as for code-start-pc.) # # # For functions with XEPs , name could be represented more simply ;;; and compactly as some sort of info about with how to find the ;;; function entry that this is a function for. Actually, you really ;;; hardly need any info. You can just chain through the functions in ;;; the component until you find the right one. Well, I guess you need ;;; to at least know which function is an XEP for the real function ;;; (which would be useful info anyway). ;;;; DEBUG SOURCE There is one per compiled file and one per function compiled at ;;; toplevel or loaded from source. (def!struct (debug-source #-sb-xc-host (:pure t)) ( This is one of those structures where IWBNI we had multiple inheritance . The first four slots describe compilation of a file , the fifth and sixth compilation of a form processed by EVAL , and the seventh and eigth all compilation units ; and these ;; are orthogonal concerns that can combine independently.) ;; When the DEBUG-SOURCE describes a file, the file's namestring. Otherwise , NIL . (namestring nil :type (or null string)) ;; the universal time that the source was written, or NIL if ;; unavailable (created nil :type (or unsigned-byte null)) the source path root number of the first form read from this ;; source (i.e. the total number of forms converted previously in ;; this compilation). (Note: this will always be 0 so long as the SOURCE - INFO structure has exactly one FILE - INFO . ) (source-root 0 :type index) The FILE - POSITIONs of the truly top level forms read from this ;; file (if applicable). The vector element type will be chosen to ;; hold the largest element. (start-positions nil :type (or (simple-array * (*)) null)) For functions processed by EVAL ( including EVAL - WHEN and LOAD on ;; a source file), the source form. (form nil :type list) ;; This is the function whose source is the form. (function nil) ;; the universal time that the source was compiled (compiled (missing-arg) :type unsigned-byte) ;; Additional information from (WITH-COMPILATION-UNIT (:SOURCE-PLIST ...)) (plist *source-plist*)) ;;;; DEBUG-INFO structures (def!struct debug-info ;; Some string describing something about the code in this component. (name (missing-arg) :type t) ;; A list of DEBUG-SOURCE structures describing where the code for this ;; component came from, in the order that they were read. (source nil)) (defconstant +debug-info-source-index+ (let* ((dd (find-defstruct-description 'debug-info)) (slots (dd-slots dd)) bug 117 bogowarning (find 'source slots :key #'dsd-name)))) (dsd-index source))) (def!struct (compiled-debug-info (:include debug-info) #-sb-xc-host (:pure t)) ;; a SIMPLE-VECTOR of alternating DEBUG-FUN objects and fixnum ;; PCs, used to map PCs to functions, so that we can figure out what ;; function we were running in. Each function is valid between the ;; PC before it (inclusive) and the PC after it (exclusive). The PCs are in sorted order , to allow binary search . We omit the first ;; and last PC, since their values are 0 and the length of the code ;; vector. ;; : PC 's ca n't always be represented by FIXNUMs , unless we 're ;; always careful to put our code in low memory. Is that how it ;; works? Would this break if we used a more general memory map? -- WHN 20000120 (fun-map (missing-arg) :type simple-vector :read-only t)) (defvar *!initial-debug-sources*) (defun !debug-info-cold-init () (let ((now (get-universal-time))) (dolist (debug-source *!initial-debug-sources*) (let* ((namestring (debug-source-namestring debug-source)) (timestamp (file-write-date namestring))) (setf (debug-source-created debug-source) timestamp (debug-source-compiled debug-source) now)))))
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/code/debug-info.lisp
lisp
structures used for recording debugger information more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. flags for compiled debug variables Compiled debug variables are in a packed binary representation in the DEBUG-FUN-VARS: single byte of boolean flags: packaged name environment-live has distinct save location has ID (name not unique in this fun) minimal debug-info argument (name generated as ARG-0, ...) deleted: placeholder for unused minimal argument [name length in bytes (as var-length integer), if not minimal] [...name bytes..., if not minimal] [if packaged, var-length integer that is package name length] ...package name bytes...] [If has ID, ID as var-length integer] (defconstant compiled-debug-var-uninterned #b00000001) compiled debug blocks Compiled debug blocks are in a packed binary representation in the DEBUG-FUN-BLOCKS: number of successors + bit flags (single byte) elsewhere-p ...ordinal number of each successor in the function's blocks vector... number of locations in this block ...more <kind, delta, top level form offset, form-number, live-set> tuples... DEBUG-FUN objects They're coupled by the way that DEBUG-FUN objects are looked up. A list of DEBUG-FUN objects is maintained for each COMPONENT. To figure out which DEBUG-FUN object corresponds to your FUNCTION The kind of function (same as FUNCTIONAL-KIND): a description of variable locations for this function, in alphabetical order by name; or NIL if no information is available The variable entries are alphabetically ordered. This ordering is byte index at which the representation of the location starts. Each entry is: COMPILED-DEBUG-FUN-FOO bits set * the symbol which names this variable, unless debug info is minimal a vector of the packed binary representation of the COMPILED-DEBUG-BLOCKs in this function, in the order that the function. This slot may be NIL to save space. FIXME: The "packed binary representation" description in the comment above is the same as the description of the old (because it doesn't transform correctly under package renaming). Check whether this slot's data might have the same problem that that slot's data did. If all code locations in this function are in the same top level form, then this is the number of that form, otherwise NIL. If a vector describing the variables that the argument values are stored in within this function. The locations are represented by the ordinal number of the entry in the VARIABLES slot value. The locations are in the order that the arguments are actually passed in, but special marker symbols can be interspersed to indicate the original call syntax: DELETED There was an argument to the function in this position, but it was deleted due to lack of references. The value cannot be recovered. SUPPLIED-P The following location is the supplied-p value for the preceding keyword or optional. OPTIONAL-ARGS Indicates that following unqualified args are optionals, not required. REST-ARG The following location holds the list of rest args. MORE-ARG <any other symbol> The following location is the value of the &KEY argument with the specified name. This may be NIL to save space. If no symbols are present, then this will be represented with an I-vector with sufficiently large element type. If this is :MINIMAL, then this means that the VARIABLES are all required arguments, and are in the order they appear in the VARIABLES vector. In other words, :MINIMAL stands in for a vector where every element holds its index. A vector of SC-OFFSETS describing the return locations. The vector element type is chosen to hold the largest element. :STANDARD The function returns using the standard unknown-values convention. :FIXED The function returns using the fixed-values convention, but in order to save space, we elected not to store a vector. NFP allocated. The earliest PC in this function at which the environment is properly initialized (arguments moved from passing locations, etc.) The start of elsewhere code for this function (if any.) minimal debug function The minimal debug info format compactly represents debug-info for some cases where the other debug info (variables, blocks) is small enough so that the per-function overhead becomes relatively large. The minimal debug-info format can represent any function at level 0, and any fixed-arg In the minimal format, the debug functions and function map are packed into a single byte-vector which is placed in the COMPILED-DEBUG-INFO-FUN-MAP. Because of this, all functions in a component must be representable in minimal format for any function to actually be dumped in minimal format. The vector is a sequence of records in this format: name representation + kind + return convention (single byte) bit flags (single byte) [package name length (as var-length int), if name is packaged] [...package name bytes, if name is packaged] [name length (as var-length int), if there is a name] [...name bytes, if there is a name] [variables length (as var-length int), if variables flag] [...bytes holding variable descriptions] arguments (in order) with the minimal-arg bit set. [If returns is specified, then the number of return values] [...sequence of var-length ints holding sc-offsets of the return value locations, if fixed return values are specified.] return-pc location sc-offset (as var-length int) old-fp location sc-offset (as var-length int) [nfp location sc-offset (as var-length int), if nfp flag] code-start-pc (as a var-length int) This field implicitly encodes start of this function's code in the function map, as a delta from the previous function's code start. 0 (i.e. the absolute offset.) start-pc (as a var-length int) This encodes the environment start PC as an offset from the code-start PC. elsewhere-pc This encodes the elsewhere code start for this function, as a delta from the previous function's elsewhere code start. (i.e. the encoding is the same as for code-start-pc.) and compactly as some sort of info about with how to find the function entry that this is a function for. Actually, you really hardly need any info. You can just chain through the functions in the component until you find the right one. Well, I guess you need to at least know which function is an XEP for the real function (which would be useful info anyway). DEBUG SOURCE toplevel or loaded from source. and these are orthogonal concerns that can combine independently.) When the DEBUG-SOURCE describes a file, the file's namestring. the universal time that the source was written, or NIL if unavailable source (i.e. the total number of forms converted previously in this compilation). (Note: this will always be 0 so long as the file (if applicable). The vector element type will be chosen to hold the largest element. a source file), the source form. This is the function whose source is the form. the universal time that the source was compiled Additional information from (WITH-COMPILATION-UNIT (:SOURCE-PLIST ...)) DEBUG-INFO structures Some string describing something about the code in this component. A list of DEBUG-SOURCE structures describing where the code for this component came from, in the order that they were read. a SIMPLE-VECTOR of alternating DEBUG-FUN objects and fixnum PCs, used to map PCs to functions, so that we can figure out what function we were running in. Each function is valid between the PC before it (inclusive) and the PC after it (exclusive). The PCs and last PC, since their values are 0 and the length of the code vector. always careful to put our code in low memory. Is that how it works? Would this break if we used a more general memory map? --
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!C") FIXME : old CMU CL representation follows : uninterned name SC - Offset of primary location ( as var - length integer ) [ If has save SC , SC - OFFSET of save location ( as var - length integer ) ] FIXME : The first two are no longer used in SBCL . ( defconstant compiled - debug - var - packaged # b00000010 ) (def!constant compiled-debug-var-environment-live #b00000100) (def!constant compiled-debug-var-save-loc-p #b00001000) (def!constant compiled-debug-var-id-p #b00010000) (def!constant compiled-debug-var-minimal-p #b00100000) (def!constant compiled-debug-var-deleted-p #b01000000) kind of first location ( single byte ) delta from previous PC ( or from 0 if first location in function . ) [ offset of first top level form , if no function TLF - NUMBER ] form number of first source form first live mask ( length in bytes determined by number of VARIABLES ) (defconstant-eqx compiled-debug-block-nsucc-byte (byte 2 0) #'equalp) (def!constant compiled-debug-block-elsewhere-p #b00000100) (defconstant-eqx compiled-code-location-kind-byte (byte 4 0) #'equalp) (defparameter *compiled-code-location-kinds* #(:unknown-return :known-return :internal-error :non-local-exit :block-start :call-site :single-value-return :non-local-entry :step-before-vop)) (def!struct (debug-fun (:constructor nil))) (def!struct (compiled-debug-fun (:include debug-fun) #-sb-xc-host (:pure t)) : Courtesy of more than a decade of , ah , organic growth in CMU CL , there are two distinct -- but coupled -- mechanisms to finding the name of a function . The slot here is one mechanism ( used in CMU CL to look up names in the debugger , e.g. in BACKTRACE ) . The other mechanism is the NAME slot in function primitive objects ( used in CMU CL to look up names elsewhere , e.g. in CL : FUNCTION - LAMBDA - EXPRESSION and in CL : DESCRIBE ) . object , you compare the name values of each . -- WHN 2001 - 12 - 20 (name (missing-arg) :type (or simple-string cons symbol)) (kind nil :type (member nil :optional :external :toplevel :cleanup)) used in lifetime info to refer to variables : the first entry is 0 , the second entry is 1 , etc . Variable numbers are * not * the * a FLAGS value , which is a FIXNUM with various * the variable ID , when it has one * SC - offset of primary location , if it has one * SC - offset of save location , if it has one (vars nil :type (or simple-vector null)) blocks were emitted . The first block is the start of the representation of VARIABLES which does n't work properly in SBCL (blocks nil :type (or (simple-array (unsigned-byte 8) (*)) null)) NIL , then each code location represented in the BLOCKS specifies the TLF number . (tlf-number nil :type (or index null)) The following two locations are the more arg context and count . (arguments nil :type (or (simple-array * (*)) (member :minimal nil))) There are three alternatives for this slot : a VECTOR (returns :fixed :type (or (simple-array * (*)) (member :standard :fixed))) SC - OFFSETs describing where the return PC and return FP are kept . (return-pc (missing-arg) :type sc-offset) (old-fp (missing-arg) :type sc-offset) SC - OFFSET for the number stack FP in this function , or NIL if no (nfp nil :type (or sc-offset null)) (start-pc (missing-arg) :type index) (elsewhere-pc (missing-arg) :type index)) function at level 1 . setf , nfp , variables If variables are dumped ( level 1 ) , then the variables are all If the first function in the component , then this is the delta from # # # For functions with XEPs , name could be represented more simply There is one per compiled file and one per function compiled at (def!struct (debug-source #-sb-xc-host (:pure t)) ( This is one of those structures where IWBNI we had multiple inheritance . The first four slots describe compilation of a file , the fifth and sixth compilation of a form processed by Otherwise , NIL . (namestring nil :type (or null string)) (created nil :type (or unsigned-byte null)) the source path root number of the first form read from this SOURCE - INFO structure has exactly one FILE - INFO . ) (source-root 0 :type index) The FILE - POSITIONs of the truly top level forms read from this (start-positions nil :type (or (simple-array * (*)) null)) For functions processed by EVAL ( including EVAL - WHEN and LOAD on (form nil :type list) (function nil) (compiled (missing-arg) :type unsigned-byte) (plist *source-plist*)) (def!struct debug-info (name (missing-arg) :type t) (source nil)) (defconstant +debug-info-source-index+ (let* ((dd (find-defstruct-description 'debug-info)) (slots (dd-slots dd)) bug 117 bogowarning (find 'source slots :key #'dsd-name)))) (dsd-index source))) (def!struct (compiled-debug-info (:include debug-info) #-sb-xc-host (:pure t)) are in sorted order , to allow binary search . We omit the first : PC 's ca n't always be represented by FIXNUMs , unless we 're WHN 20000120 (fun-map (missing-arg) :type simple-vector :read-only t)) (defvar *!initial-debug-sources*) (defun !debug-info-cold-init () (let ((now (get-universal-time))) (dolist (debug-source *!initial-debug-sources*) (let* ((namestring (debug-source-namestring debug-source)) (timestamp (file-write-date namestring))) (setf (debug-source-created debug-source) timestamp (debug-source-compiled debug-source) now)))))
c3f6b51e9220a952e26d7c2499ae4360c078f142482e379a11219bbd3e862802
mishoo/queen.lisp
pgn.lisp
(in-package #:queen) (defmethod parse-pgn ((in stream)) (with-parse-stream in (labels ((read-sym () (read-while #'alnum?)) (read-header () (let (name value) (skip #\[) (setf name (read-sym)) (skip-whitespace) (setf value (read-string)) (skip #\]) (cons name value))) (read-result () (if (eql #\* (peek)) (progn (next) "*") (look-ahead 3 (lambda (chars) (unless (member nil chars) (let ((str (coerce chars 'string))) (cond ((string= "1-0" str) "1-0") ((string= "0-1" str) "0-1") ((string= "1/2" str) (skip "-1/2") "1/2-1/2")))))))) (read-moves (game) (let ((data '())) (flet ((move () (let* ((movestr (read-while #'non-whitespace?)) (valid (game-parse-san game movestr))) (skip-whitespace) (cond ((null valid) (error "Invalid move (~A)" movestr)) ((< 1 (length valid)) (error "Ambiguous move (~A)" movestr))) (game-move game (car valid)) (push (cons :move (car valid)) data))) (comment1 () (skip #\;) (read-while (lambda (ch) (not (eql #\Newline ch))))) (comment2 () (skip #\{) (prog1 (read-while (lambda (ch) (not (eql #\} ch)))) (skip #\})))) (loop while (peek) do (skip-whitespace) (or (awhen (read-result) (push (cons :result it) data) (return (nreverse data))) (when (eql (peek) #\;) (push (cons :comment (comment1)) data)) (when (eql (peek) #\{) (push (cons :comment (comment2)) data)) (progn (when (read-number) (skip #\.) (when (eql #\. (peek)) (skip "..")) (skip-whitespace)) (move))) (skip-whitespace) finally (return (nreverse data))))))) (skip-whitespace) (let* ((headers (loop while (eql #\[ (peek)) collect (prog1 (read-header) (skip-whitespace)))) (game (make-instance 'game)) (start-fen (assoc "fen" headers :test #'string-equal))) (reset-from-fen game (if start-fen (cdr start-fen) +FEN-START+)) `(:headers ,headers :moves ,(read-moves game) :game ,game))))) (defmethod parse-pgn ((pgn string)) (with-input-from-string (in pgn) (parse-pgn in)))
null
https://raw.githubusercontent.com/mishoo/queen.lisp/395535fcbd24fa463b32e17a35a4c12fdc7e2277/pgn.lisp
lisp
) )
(in-package #:queen) (defmethod parse-pgn ((in stream)) (with-parse-stream in (labels ((read-sym () (read-while #'alnum?)) (read-header () (let (name value) (skip #\[) (setf name (read-sym)) (skip-whitespace) (setf value (read-string)) (skip #\]) (cons name value))) (read-result () (if (eql #\* (peek)) (progn (next) "*") (look-ahead 3 (lambda (chars) (unless (member nil chars) (let ((str (coerce chars 'string))) (cond ((string= "1-0" str) "1-0") ((string= "0-1" str) "0-1") ((string= "1/2" str) (skip "-1/2") "1/2-1/2")))))))) (read-moves (game) (let ((data '())) (flet ((move () (let* ((movestr (read-while #'non-whitespace?)) (valid (game-parse-san game movestr))) (skip-whitespace) (cond ((null valid) (error "Invalid move (~A)" movestr)) ((< 1 (length valid)) (error "Ambiguous move (~A)" movestr))) (game-move game (car valid)) (push (cons :move (car valid)) data))) (comment1 () (read-while (lambda (ch) (not (eql #\Newline ch))))) (comment2 () (skip #\{) (prog1 (read-while (lambda (ch) (not (eql #\} ch)))) (skip #\})))) (loop while (peek) do (skip-whitespace) (or (awhen (read-result) (push (cons :result it) data) (return (nreverse data))) (push (cons :comment (comment1)) data)) (when (eql (peek) #\{) (push (cons :comment (comment2)) data)) (progn (when (read-number) (skip #\.) (when (eql #\. (peek)) (skip "..")) (skip-whitespace)) (move))) (skip-whitespace) finally (return (nreverse data))))))) (skip-whitespace) (let* ((headers (loop while (eql #\[ (peek)) collect (prog1 (read-header) (skip-whitespace)))) (game (make-instance 'game)) (start-fen (assoc "fen" headers :test #'string-equal))) (reset-from-fen game (if start-fen (cdr start-fen) +FEN-START+)) `(:headers ,headers :moves ,(read-moves game) :game ,game))))) (defmethod parse-pgn ((pgn string)) (with-input-from-string (in pgn) (parse-pgn in)))
81709160c150fc57241943f45ad740a0e215c6daf30095307283636612e416d9
khibino/haskell-relational-record
SQL.hs
-- | -- Module : Database.Relational.SQL Copyright : 2013 - 2019 -- License : BSD3 -- -- Maintainer : -- Stability : experimental -- Portability : unknown -- -- This module defines finalized SQL definitions which convert from relational queries. module Database.Relational.SQL ( -- * Typed query statement Query (..), unsafeTypedQuery, relationalQuery_, relationalQuery', relationalQuery, relationalQuerySQL, -- * Typed update statement KeyUpdate (..), unsafeTypedKeyUpdate, typedKeyUpdate, typedKeyUpdateTable, keyUpdate, Update (..), unsafeTypedUpdate, typedUpdate', update', update, updateNoPH, typedUpdateAllColumn, updateAllColumn', updateAllColumn, updateAllColumnNoPH, updateSQL, -- * Typed insert statement Insert (..), untypeChunkInsert, chunkSizeOfInsert, unsafeTypedInsert', unsafeTypedInsert, typedInsert', insert, typedInsertValue', insertValue', insertValue, insertValueNoPH, insertValueList', insertValueList, InsertQuery (..), unsafeTypedInsertQuery, typedInsertQuery', insertQuery', insertQuery, insertQuerySQL, -- * Typed delete statement Delete (..), unsafeTypedDelete, typedDelete', delete', delete, deleteNoPH, deleteSQL, -- * Generalized interfaces UntypeableNoFetch (..), -- * Deprecated typedUpdate, typedInsert, typedInsertValue, typedInsertQuery, typedDelete, derivedKeyUpdate, derivedUpdate', derivedUpdate, derivedUpdateAllColumn', derivedUpdateAllColumn, derivedInsert, derivedInsertValue', derivedInsertValue, derivedInsertQuery, derivedDelete', derivedDelete, ) where import Data.Monoid ((<>), mconcat) import Data.Functor.ProductIsomorphic (peRight) import Language.SQL.Keyword (Keyword) import Database.Record (PersistableWidth) import Database.Relational.Internal.Config (Config, defaultConfig) import Database.Relational.Internal.ContextType (Flat) import Database.Relational.Internal.String (showStringSQL) import Database.Relational.Typed.Table (Table, TableDerivable, derivedTable) import Database.Relational.Typed.Record (Record) import Database.Relational.Monad.BaseType (Relation, sqlFromRelationWith) import Database.Relational.Monad.Restrict (Restrict) import Database.Relational.Monad.Assign (Assign) import Database.Relational.Monad.Register (Register) import Database.Relational.Relation (tableFromRelation) import Database.Relational.Effect (liftTargetAllColumn', deleteFromRestrict, updateFromAssign, piRegister, chunkInsertFromRegister, insertFromRegister, chunkInsertFromRecords,) import Database.Relational.Pi (Pi) import Database.Relational.ProjectableClass (LiteralSQL) import Database.Relational.Projectable (PlaceHolders, unitPH) import Database.Relational.SimpleSql (insertPrefixSQL, updateOtherThanKeySQL, ) -- | Query type with place-holder parameter 'p' and query result type 'a'. newtype Query p a = Query { untypeQuery :: String } -- | Unsafely make typed 'Query' from SQL string. unsafeTypedQuery :: String -- ^ Query SQL to type -> Query p a -- ^ Typed result unsafeTypedQuery = Query -- | Show query SQL string instance Show (Query p a) where show = untypeQuery -- | From 'Relation' into untyped SQL query string. relationalQuerySQL :: Config -> Relation p r -> [Keyword] -> String relationalQuerySQL config rel qsuf = showStringSQL $ sqlFromRelationWith rel config <> mconcat qsuf -- | From 'Relation' into typed 'Query' with suffix SQL words. relationalQuery_ :: Config -> Relation p r -- ^ relation to finalize building ^ suffix SQL words . for example , ` [ FOR , UPDATE ] ` , ` [ FETCH , FIRST , " 3 " , ROWS , ONLY ] ` ... -> Query p r -- ^ finalized query relationalQuery_ config rel qsuf = unsafeTypedQuery $ relationalQuerySQL config rel qsuf -- | From 'Relation' into typed 'Query' with suffix SQL words. relationalQuery' :: Relation p r -- ^ relation to finalize building ^ suffix SQL words . for example , ` [ FOR , UPDATE ] ` , ` [ FETCH , FIRST , " 3 " , ROWS , ONLY ] ` ... -> Query p r -- ^ finalized query relationalQuery' = relationalQuery_ defaultConfig -- | From 'Relation' into typed 'Query'. relationalQuery :: Relation p r -- ^ relation to finalize building -> Query p r -- ^ finalized query relationalQuery = (`relationalQuery'` []) -- | Update type with key type 'p' and update record type 'a'. -- Columns to update are record columns other than key columns, -- So place-holder parameter type is the same as record type 'a'. data KeyUpdate p a = KeyUpdate { updateKey :: Pi a p , untypeKeyUpdate :: String } | Unsafely make typed ' KeyUpdate ' from SQL string . unsafeTypedKeyUpdate :: Pi a p -> String -> KeyUpdate p a unsafeTypedKeyUpdate = KeyUpdate | Make typed ' KeyUpdate ' from ' Table ' and key columns selector ' Pi ' . typedKeyUpdate :: Table a -> Pi a p -> KeyUpdate p a typedKeyUpdate tbl key = unsafeTypedKeyUpdate key $ updateOtherThanKeySQL tbl key | Make typed ' KeyUpdate ' object using derived info specified by ' Relation ' type . typedKeyUpdateTable :: TableDerivable r => Relation () r -> Pi r p -> KeyUpdate p r typedKeyUpdateTable = typedKeyUpdate . tableFromRelation keyUpdate ' Config parameter is not yet required for KeyUpdate . | Make typed ' KeyUpdate ' from derived table and key columns selector ' Pi ' . keyUpdate :: TableDerivable r => Pi r p -> KeyUpdate p r keyUpdate = typedKeyUpdate derivedTable # DEPRECATED derivedKeyUpdate " use keyUpdate instead of this . " # | Make typed ' KeyUpdate ' from derived table and key columns selector ' Pi ' . derivedKeyUpdate :: TableDerivable r => Pi r p -> KeyUpdate p r derivedKeyUpdate = keyUpdate -- | Show update SQL string instance Show (KeyUpdate p a) where show = untypeKeyUpdate -- | Update type with place-holder parameter 'p'. newtype Update p = Update { untypeUpdate :: String } -- | Unsafely make typed 'Update' from SQL string. unsafeTypedUpdate :: String -> Update p unsafeTypedUpdate = Update -- | Make untyped update SQL string from 'Table' and 'Assign' computation. updateSQL :: Config -> Table r -> (Record Flat r -> Assign r (PlaceHolders p)) -> String updateSQL config tbl ut = showStringSQL $ updateFromAssign config tbl ut -- | Make typed 'Update' from 'Config', 'Table' and 'Assign' computation. typedUpdate' :: Config -> Table r -> (Record Flat r -> Assign r (PlaceHolders p)) -> Update p typedUpdate' config tbl ut = unsafeTypedUpdate $ updateSQL config tbl ut {-# DEPRECATED typedUpdate "use `typedUpdate' defaultConfig` instead of this." #-} -- | Make typed 'Update' using 'defaultConfig', 'Table' and 'Assign' computation. typedUpdate :: Table r -> (Record Flat r -> Assign r (PlaceHolders p)) -> Update p typedUpdate = typedUpdate' defaultConfig targetTable :: TableDerivable r => (Record Flat r -> Assign r (PlaceHolders p)) -> Table r targetTable = const derivedTable -- | Make typed 'Update' from 'Config', derived table and 'Assign' computation. update' :: TableDerivable r => Config -> (Record Flat r -> Assign r (PlaceHolders p)) -> Update p update' config ac = typedUpdate' config (targetTable ac) ac {-# DEPRECATED derivedUpdate' "use `update'` instead of this." #-} -- | Make typed 'Update' from 'Config', derived table and 'Assign' computation. derivedUpdate' :: TableDerivable r => Config -> (Record Flat r -> Assign r (PlaceHolders p)) -> Update p derivedUpdate' = update' -- | Make typed 'Update' from 'defaultConfig', derived table and 'Assign' computation. update :: TableDerivable r => (Record Flat r -> Assign r (PlaceHolders p)) -> Update p update = update' defaultConfig | Make typed ' Update ' from ' defaultConfig ' , derived table and ' Assign ' computation with ) placeholder . updateNoPH :: TableDerivable r => (Record Flat r -> Assign r ()) -> Update () updateNoPH af = update $ (>> return unitPH) . af {-# DEPRECATED derivedUpdate "use `update` instead of this." #-} -- | Make typed 'Update' from 'defaultConfig', derived table and 'Assign' computation. derivedUpdate :: TableDerivable r => (Record Flat r -> Assign r (PlaceHolders p)) -> Update p derivedUpdate = update -- | Make typed 'Update' from 'Config', 'Table' and 'Restrict' computation. -- Update target is all column. typedUpdateAllColumn' :: PersistableWidth r => Config -> Table r -> (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) typedUpdateAllColumn' config tbl r = typedUpdate' config tbl $ liftTargetAllColumn' r -- | Make typed 'Update' from 'Table' and 'Restrict' computation. -- Update target is all column. typedUpdateAllColumn :: PersistableWidth r => Table r -> (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) typedUpdateAllColumn = typedUpdateAllColumn' defaultConfig -- | Make typed 'Update' from 'Config', derived table and 'Restrict' computation. -- Update target is all column. updateAllColumn' :: (PersistableWidth r, TableDerivable r) => Config -> (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) updateAllColumn' config = typedUpdateAllColumn' config derivedTable {-# DEPRECATED derivedUpdateAllColumn' "use `updateAllColumn'` instead of this." #-} -- | Deprecated. use 'updateAllColumn''. derivedUpdateAllColumn' :: (PersistableWidth r, TableDerivable r) => Config -> (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) derivedUpdateAllColumn' = updateAllColumn' -- | Make typed 'Update' from 'defaultConfig', derived table and 'Restrict' computation. -- Update target is all column. updateAllColumn :: (PersistableWidth r, TableDerivable r) => (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) updateAllColumn = updateAllColumn' defaultConfig -- | Make typed 'Update' from 'defaultConfig', derived table and 'Restrict' computation -- without placeholder other than target table columns. -- Update target is all column. updateAllColumnNoPH :: (PersistableWidth r, TableDerivable r) => (Record Flat r -> Restrict ()) -> Update r updateAllColumnNoPH = typedUpdate' defaultConfig derivedTable . (fmap peRight .) . liftTargetAllColumn' . ((>> return unitPH) .) {-# DEPRECATED derivedUpdateAllColumn "use `updateAllColumn` instead of this." #-} -- | Deprecated. use 'updateAllColumn'. derivedUpdateAllColumn :: (PersistableWidth r, TableDerivable r) => (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) derivedUpdateAllColumn = updateAllColumn -- | Show update SQL string instance Show (Update p) where show = untypeUpdate -- | Insert type to insert record type 'a'. data Insert a = Insert { untypeInsert :: String , chunkedInsert :: Maybe (String, Int) } -- | Statement to use chunked insert untypeChunkInsert :: Insert a -> String untypeChunkInsert ins = maybe (untypeInsert ins) fst $ chunkedInsert ins -- | Size to use chunked insert chunkSizeOfInsert :: Insert a -> Int chunkSizeOfInsert = maybe 1 snd . chunkedInsert -- | Unsafely make typed 'Insert' from single insert and chunked insert SQL. unsafeTypedInsert' :: String -> String -> Int -> Insert a unsafeTypedInsert' s = curry (Insert s . Just) -- | Unsafely make typed 'Insert' from single insert SQL. unsafeTypedInsert :: String -> Insert a unsafeTypedInsert s = Insert s Nothing -- | Make typed 'Insert' from 'Table' and columns selector 'Pi' with configuration parameter. typedInsert' :: PersistableWidth r => Config -> Table r -> Pi r r' -> Insert r' typedInsert' config tbl = typedInsertValue' config tbl . piRegister {-# DEPRECATED typedInsert "use `typedInsert' defaultConfig` instead of this." #-} -- | Make typed 'Insert' from 'Table' and columns selector 'Pi'. typedInsert :: PersistableWidth r => Table r -> Pi r r' -> Insert r' typedInsert = typedInsert' defaultConfig -- | Table type inferred 'Insert'. insert :: (PersistableWidth r, TableDerivable r) => Pi r r' -> Insert r' insert = typedInsert' defaultConfig derivedTable {-# DEPRECATED derivedInsert "use `insert` instead of this." #-} -- | Table type inferred 'Insert'. derivedInsert :: (PersistableWidth r, TableDerivable r) => Pi r r' -> Insert r' derivedInsert = insert -- | Make typed 'Insert' from 'Config', 'Table' and monadic builded 'Register' object. typedInsertValue' :: Config -> Table r -> Register r (PlaceHolders p) -> Insert p typedInsertValue' config tbl it = unsafeTypedInsert' (showStringSQL $ insertFromRegister config tbl it) (showStringSQL ci) n where (ci, n) = chunkInsertFromRegister config tbl it {-# DEPRECATED typedInsertValue "use `typedInsertValue' defaultConfig` instead of this." #-} -- | Make typed 'Insert' from 'Table' and monadic builded 'Register' object. typedInsertValue :: Table r -> Register r (PlaceHolders p) -> Insert p typedInsertValue = typedInsertValue' defaultConfig -- | Make typed 'Insert' from 'Config', derived table and monadic builded 'Register' object. insertValue' :: TableDerivable r => Config -> Register r (PlaceHolders p) -> Insert p insertValue' config rs = typedInsertValue' config (rt rs) rs where rt :: TableDerivable r => Register r (PlaceHolders p) -> Table r rt = const derivedTable # DEPRECATED derivedInsertValue ' " use ` insertValue ' ` instead of this . " # -- | Make typed 'Insert' from 'Config', derived table and monadic builded 'Register' object. derivedInsertValue' :: TableDerivable r => Config -> Register r (PlaceHolders p) -> Insert p derivedInsertValue' = insertValue' -- | Make typed 'Insert' from 'defaultConfig', derived table and monadic builded 'Register' object. insertValue :: TableDerivable r => Register r (PlaceHolders p) -> Insert p insertValue = insertValue' defaultConfig | Make typed ' Insert ' from ' defaultConfig ' , derived table and monadic builded ' Register ' object with ) placeholder . insertValueNoPH :: TableDerivable r => Register r () -> Insert () insertValueNoPH = insertValue . (>> return unitPH) {-# DEPRECATED derivedInsertValue "use `insertValue` instead of this." #-} -- | Make typed 'Insert' from 'defaultConfig', derived table and monadic builded 'Register' object. derivedInsertValue :: TableDerivable r => Register r (PlaceHolders p) -> Insert p derivedInsertValue = insertValue -- | Make typed 'Insert' list from 'Config' and records list. insertValueList' :: (TableDerivable r, LiteralSQL r') => Config -> Pi r r' -> [r'] -> [Insert ()] insertValueList' config pi' = map (unsafeTypedInsert . showStringSQL) . chunkInsertFromRecords config derivedTable pi' -- | Make typed 'Insert' list from records list. insertValueList :: (TableDerivable r, LiteralSQL r') => Pi r r' -> [r'] -> [Insert ()] insertValueList = insertValueList' defaultConfig -- | Show insert SQL string. instance Show (Insert a) where show = untypeInsert | InsertQuery type . newtype InsertQuery p = InsertQuery { untypeInsertQuery :: String } | Unsafely make typed ' InsertQuery ' from SQL string . unsafeTypedInsertQuery :: String -> InsertQuery p unsafeTypedInsertQuery = InsertQuery -- | Make untyped insert select SQL string from 'Table', 'Pi' and 'Relation'. insertQuerySQL :: Config -> Table r -> Pi r r' -> Relation p r' -> String insertQuerySQL config tbl pi' rel = showStringSQL $ insertPrefixSQL pi' tbl <> sqlFromRelationWith rel config | Make typed ' InsertQuery ' from columns selector ' Table ' , ' Pi ' and ' Relation ' with configuration parameter . typedInsertQuery' :: Config -> Table r -> Pi r r' -> Relation p r' -> InsertQuery p typedInsertQuery' config tbl pi' rel = unsafeTypedInsertQuery $ insertQuerySQL config tbl pi' rel {-# DEPRECATED typedInsertQuery "use `typedInsertQuery' defaultConfig` instead of this." #-} | Make typed ' InsertQuery ' from columns selector ' Table ' , ' Pi ' and ' Relation ' . typedInsertQuery :: Table r -> Pi r r' -> Relation p r' -> InsertQuery p typedInsertQuery = typedInsertQuery' defaultConfig | Table type inferred ' InsertQuery ' . insertQuery' :: TableDerivable r => Config -> Pi r r' -> Relation p r' -> InsertQuery p insertQuery' config = typedInsertQuery' config derivedTable | Table type inferred ' InsertQuery ' with ' defaultConfig ' . insertQuery :: TableDerivable r => Pi r r' -> Relation p r' -> InsertQuery p insertQuery = insertQuery' defaultConfig {-# DEPRECATED derivedInsertQuery "use `insertQuery` instead of this." #-} | Table type inferred ' InsertQuery ' . derivedInsertQuery :: TableDerivable r => Pi r r' -> Relation p r' -> InsertQuery p derivedInsertQuery = insertQuery -- | Show insert SQL string. instance Show (InsertQuery p) where show = untypeInsertQuery -- | Delete type with place-holder parameter 'p'. newtype Delete p = Delete { untypeDelete :: String } -- | Unsafely make typed 'Delete' from SQL string. unsafeTypedDelete :: String -> Delete p unsafeTypedDelete = Delete -- | Make untyped delete SQL string from 'Table' and 'Restrict' computation. deleteSQL :: Config -> Table r -> (Record Flat r -> Restrict (PlaceHolders p)) -> String deleteSQL config tbl r = showStringSQL $ deleteFromRestrict config tbl r -- | Make typed 'Delete' from 'Config', 'Table' and 'Restrict' computation. typedDelete' :: Config -> Table r -> (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p typedDelete' config tbl r = unsafeTypedDelete $ deleteSQL config tbl r {-# DEPRECATED typedDelete "use `typedDelete' defaultConfig` instead of this." #-} -- | Make typed 'Delete' from 'Table' and 'Restrict' computation. typedDelete :: Table r -> (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p typedDelete = typedDelete' defaultConfig restrictedTable :: TableDerivable r => (Record Flat r -> Restrict (PlaceHolders p)) -> Table r restrictedTable = const derivedTable -- | Make typed 'Delete' from 'Config', derived table and 'Restrict' computation. delete' :: TableDerivable r => Config -> (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p delete' config rc = typedDelete' config (restrictedTable rc) rc {-# DEPRECATED derivedDelete' "use `delete'` instead of this." #-} -- | Make typed 'Delete' from 'Config', derived table and 'Restrict' computation. derivedDelete' :: TableDerivable r => Config -> (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p derivedDelete' = delete' -- | Make typed 'Delete' from 'defaultConfig', derived table and 'Restrict' computation. delete :: TableDerivable r => (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p delete = delete' defaultConfig | Make typed ' Delete ' from ' defaultConfig ' , derived table and ' Restrict ' computation with ) placeholder . deleteNoPH :: TableDerivable r => (Record Flat r -> Restrict ()) -> Delete () deleteNoPH rf = delete $ (>> return unitPH) . rf {-# DEPRECATED derivedDelete "use `delete` instead of this." #-} -- | Make typed 'Delete' from 'defaultConfig', derived table and 'Restrict' computation. derivedDelete :: TableDerivable r => (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p derivedDelete = delete -- | Show delete SQL string instance Show (Delete p) where show = untypeDelete | Untype interface for typed no - result type statments -- with single type parameter which represents place-holder parameter 'p'. class UntypeableNoFetch s where untypeNoFetch :: s p -> String instance UntypeableNoFetch Insert where untypeNoFetch = untypeInsert instance UntypeableNoFetch InsertQuery where untypeNoFetch = untypeInsertQuery instance UntypeableNoFetch Update where untypeNoFetch = untypeUpdate instance UntypeableNoFetch Delete where untypeNoFetch = untypeDelete
null
https://raw.githubusercontent.com/khibino/haskell-relational-record/759b3d7cea207e64d2bd1cf195125182f73d2a52/relational-query/src/Database/Relational/SQL.hs
haskell
| Module : Database.Relational.SQL License : BSD3 Maintainer : Stability : experimental Portability : unknown This module defines finalized SQL definitions which convert from relational queries. * Typed query statement * Typed update statement * Typed insert statement * Typed delete statement * Generalized interfaces * Deprecated | Query type with place-holder parameter 'p' and query result type 'a'. | Unsafely make typed 'Query' from SQL string. ^ Query SQL to type ^ Typed result | Show query SQL string | From 'Relation' into untyped SQL query string. | From 'Relation' into typed 'Query' with suffix SQL words. ^ relation to finalize building ^ finalized query | From 'Relation' into typed 'Query' with suffix SQL words. ^ relation to finalize building ^ finalized query | From 'Relation' into typed 'Query'. ^ relation to finalize building ^ finalized query | Update type with key type 'p' and update record type 'a'. Columns to update are record columns other than key columns, So place-holder parameter type is the same as record type 'a'. | Show update SQL string | Update type with place-holder parameter 'p'. | Unsafely make typed 'Update' from SQL string. | Make untyped update SQL string from 'Table' and 'Assign' computation. | Make typed 'Update' from 'Config', 'Table' and 'Assign' computation. # DEPRECATED typedUpdate "use `typedUpdate' defaultConfig` instead of this." # | Make typed 'Update' using 'defaultConfig', 'Table' and 'Assign' computation. | Make typed 'Update' from 'Config', derived table and 'Assign' computation. # DEPRECATED derivedUpdate' "use `update'` instead of this." # | Make typed 'Update' from 'Config', derived table and 'Assign' computation. | Make typed 'Update' from 'defaultConfig', derived table and 'Assign' computation. # DEPRECATED derivedUpdate "use `update` instead of this." # | Make typed 'Update' from 'defaultConfig', derived table and 'Assign' computation. | Make typed 'Update' from 'Config', 'Table' and 'Restrict' computation. Update target is all column. | Make typed 'Update' from 'Table' and 'Restrict' computation. Update target is all column. | Make typed 'Update' from 'Config', derived table and 'Restrict' computation. Update target is all column. # DEPRECATED derivedUpdateAllColumn' "use `updateAllColumn'` instead of this." # | Deprecated. use 'updateAllColumn''. | Make typed 'Update' from 'defaultConfig', derived table and 'Restrict' computation. Update target is all column. | Make typed 'Update' from 'defaultConfig', derived table and 'Restrict' computation without placeholder other than target table columns. Update target is all column. # DEPRECATED derivedUpdateAllColumn "use `updateAllColumn` instead of this." # | Deprecated. use 'updateAllColumn'. | Show update SQL string | Insert type to insert record type 'a'. | Statement to use chunked insert | Size to use chunked insert | Unsafely make typed 'Insert' from single insert and chunked insert SQL. | Unsafely make typed 'Insert' from single insert SQL. | Make typed 'Insert' from 'Table' and columns selector 'Pi' with configuration parameter. # DEPRECATED typedInsert "use `typedInsert' defaultConfig` instead of this." # | Make typed 'Insert' from 'Table' and columns selector 'Pi'. | Table type inferred 'Insert'. # DEPRECATED derivedInsert "use `insert` instead of this." # | Table type inferred 'Insert'. | Make typed 'Insert' from 'Config', 'Table' and monadic builded 'Register' object. # DEPRECATED typedInsertValue "use `typedInsertValue' defaultConfig` instead of this." # | Make typed 'Insert' from 'Table' and monadic builded 'Register' object. | Make typed 'Insert' from 'Config', derived table and monadic builded 'Register' object. | Make typed 'Insert' from 'Config', derived table and monadic builded 'Register' object. | Make typed 'Insert' from 'defaultConfig', derived table and monadic builded 'Register' object. # DEPRECATED derivedInsertValue "use `insertValue` instead of this." # | Make typed 'Insert' from 'defaultConfig', derived table and monadic builded 'Register' object. | Make typed 'Insert' list from 'Config' and records list. | Make typed 'Insert' list from records list. | Show insert SQL string. | Make untyped insert select SQL string from 'Table', 'Pi' and 'Relation'. # DEPRECATED typedInsertQuery "use `typedInsertQuery' defaultConfig` instead of this." # # DEPRECATED derivedInsertQuery "use `insertQuery` instead of this." # | Show insert SQL string. | Delete type with place-holder parameter 'p'. | Unsafely make typed 'Delete' from SQL string. | Make untyped delete SQL string from 'Table' and 'Restrict' computation. | Make typed 'Delete' from 'Config', 'Table' and 'Restrict' computation. # DEPRECATED typedDelete "use `typedDelete' defaultConfig` instead of this." # | Make typed 'Delete' from 'Table' and 'Restrict' computation. | Make typed 'Delete' from 'Config', derived table and 'Restrict' computation. # DEPRECATED derivedDelete' "use `delete'` instead of this." # | Make typed 'Delete' from 'Config', derived table and 'Restrict' computation. | Make typed 'Delete' from 'defaultConfig', derived table and 'Restrict' computation. # DEPRECATED derivedDelete "use `delete` instead of this." # | Make typed 'Delete' from 'defaultConfig', derived table and 'Restrict' computation. | Show delete SQL string with single type parameter which represents place-holder parameter 'p'.
Copyright : 2013 - 2019 module Database.Relational.SQL ( Query (..), unsafeTypedQuery, relationalQuery_, relationalQuery', relationalQuery, relationalQuerySQL, KeyUpdate (..), unsafeTypedKeyUpdate, typedKeyUpdate, typedKeyUpdateTable, keyUpdate, Update (..), unsafeTypedUpdate, typedUpdate', update', update, updateNoPH, typedUpdateAllColumn, updateAllColumn', updateAllColumn, updateAllColumnNoPH, updateSQL, Insert (..), untypeChunkInsert, chunkSizeOfInsert, unsafeTypedInsert', unsafeTypedInsert, typedInsert', insert, typedInsertValue', insertValue', insertValue, insertValueNoPH, insertValueList', insertValueList, InsertQuery (..), unsafeTypedInsertQuery, typedInsertQuery', insertQuery', insertQuery, insertQuerySQL, Delete (..), unsafeTypedDelete, typedDelete', delete', delete, deleteNoPH, deleteSQL, UntypeableNoFetch (..), typedUpdate, typedInsert, typedInsertValue, typedInsertQuery, typedDelete, derivedKeyUpdate, derivedUpdate', derivedUpdate, derivedUpdateAllColumn', derivedUpdateAllColumn, derivedInsert, derivedInsertValue', derivedInsertValue, derivedInsertQuery, derivedDelete', derivedDelete, ) where import Data.Monoid ((<>), mconcat) import Data.Functor.ProductIsomorphic (peRight) import Language.SQL.Keyword (Keyword) import Database.Record (PersistableWidth) import Database.Relational.Internal.Config (Config, defaultConfig) import Database.Relational.Internal.ContextType (Flat) import Database.Relational.Internal.String (showStringSQL) import Database.Relational.Typed.Table (Table, TableDerivable, derivedTable) import Database.Relational.Typed.Record (Record) import Database.Relational.Monad.BaseType (Relation, sqlFromRelationWith) import Database.Relational.Monad.Restrict (Restrict) import Database.Relational.Monad.Assign (Assign) import Database.Relational.Monad.Register (Register) import Database.Relational.Relation (tableFromRelation) import Database.Relational.Effect (liftTargetAllColumn', deleteFromRestrict, updateFromAssign, piRegister, chunkInsertFromRegister, insertFromRegister, chunkInsertFromRecords,) import Database.Relational.Pi (Pi) import Database.Relational.ProjectableClass (LiteralSQL) import Database.Relational.Projectable (PlaceHolders, unitPH) import Database.Relational.SimpleSql (insertPrefixSQL, updateOtherThanKeySQL, ) newtype Query p a = Query { untypeQuery :: String } unsafeTypedQuery = Query instance Show (Query p a) where show = untypeQuery relationalQuerySQL :: Config -> Relation p r -> [Keyword] -> String relationalQuerySQL config rel qsuf = showStringSQL $ sqlFromRelationWith rel config <> mconcat qsuf relationalQuery_ :: Config ^ suffix SQL words . for example , ` [ FOR , UPDATE ] ` , ` [ FETCH , FIRST , " 3 " , ROWS , ONLY ] ` ... relationalQuery_ config rel qsuf = unsafeTypedQuery $ relationalQuerySQL config rel qsuf ^ suffix SQL words . for example , ` [ FOR , UPDATE ] ` , ` [ FETCH , FIRST , " 3 " , ROWS , ONLY ] ` ... relationalQuery' = relationalQuery_ defaultConfig relationalQuery = (`relationalQuery'` []) data KeyUpdate p a = KeyUpdate { updateKey :: Pi a p , untypeKeyUpdate :: String } | Unsafely make typed ' KeyUpdate ' from SQL string . unsafeTypedKeyUpdate :: Pi a p -> String -> KeyUpdate p a unsafeTypedKeyUpdate = KeyUpdate | Make typed ' KeyUpdate ' from ' Table ' and key columns selector ' Pi ' . typedKeyUpdate :: Table a -> Pi a p -> KeyUpdate p a typedKeyUpdate tbl key = unsafeTypedKeyUpdate key $ updateOtherThanKeySQL tbl key | Make typed ' KeyUpdate ' object using derived info specified by ' Relation ' type . typedKeyUpdateTable :: TableDerivable r => Relation () r -> Pi r p -> KeyUpdate p r typedKeyUpdateTable = typedKeyUpdate . tableFromRelation keyUpdate ' Config parameter is not yet required for KeyUpdate . | Make typed ' KeyUpdate ' from derived table and key columns selector ' Pi ' . keyUpdate :: TableDerivable r => Pi r p -> KeyUpdate p r keyUpdate = typedKeyUpdate derivedTable # DEPRECATED derivedKeyUpdate " use keyUpdate instead of this . " # | Make typed ' KeyUpdate ' from derived table and key columns selector ' Pi ' . derivedKeyUpdate :: TableDerivable r => Pi r p -> KeyUpdate p r derivedKeyUpdate = keyUpdate instance Show (KeyUpdate p a) where show = untypeKeyUpdate newtype Update p = Update { untypeUpdate :: String } unsafeTypedUpdate :: String -> Update p unsafeTypedUpdate = Update updateSQL :: Config -> Table r -> (Record Flat r -> Assign r (PlaceHolders p)) -> String updateSQL config tbl ut = showStringSQL $ updateFromAssign config tbl ut typedUpdate' :: Config -> Table r -> (Record Flat r -> Assign r (PlaceHolders p)) -> Update p typedUpdate' config tbl ut = unsafeTypedUpdate $ updateSQL config tbl ut typedUpdate :: Table r -> (Record Flat r -> Assign r (PlaceHolders p)) -> Update p typedUpdate = typedUpdate' defaultConfig targetTable :: TableDerivable r => (Record Flat r -> Assign r (PlaceHolders p)) -> Table r targetTable = const derivedTable update' :: TableDerivable r => Config -> (Record Flat r -> Assign r (PlaceHolders p)) -> Update p update' config ac = typedUpdate' config (targetTable ac) ac derivedUpdate' :: TableDerivable r => Config -> (Record Flat r -> Assign r (PlaceHolders p)) -> Update p derivedUpdate' = update' update :: TableDerivable r => (Record Flat r -> Assign r (PlaceHolders p)) -> Update p update = update' defaultConfig | Make typed ' Update ' from ' defaultConfig ' , derived table and ' Assign ' computation with ) placeholder . updateNoPH :: TableDerivable r => (Record Flat r -> Assign r ()) -> Update () updateNoPH af = update $ (>> return unitPH) . af derivedUpdate :: TableDerivable r => (Record Flat r -> Assign r (PlaceHolders p)) -> Update p derivedUpdate = update typedUpdateAllColumn' :: PersistableWidth r => Config -> Table r -> (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) typedUpdateAllColumn' config tbl r = typedUpdate' config tbl $ liftTargetAllColumn' r typedUpdateAllColumn :: PersistableWidth r => Table r -> (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) typedUpdateAllColumn = typedUpdateAllColumn' defaultConfig updateAllColumn' :: (PersistableWidth r, TableDerivable r) => Config -> (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) updateAllColumn' config = typedUpdateAllColumn' config derivedTable derivedUpdateAllColumn' :: (PersistableWidth r, TableDerivable r) => Config -> (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) derivedUpdateAllColumn' = updateAllColumn' updateAllColumn :: (PersistableWidth r, TableDerivable r) => (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) updateAllColumn = updateAllColumn' defaultConfig updateAllColumnNoPH :: (PersistableWidth r, TableDerivable r) => (Record Flat r -> Restrict ()) -> Update r updateAllColumnNoPH = typedUpdate' defaultConfig derivedTable . (fmap peRight .) . liftTargetAllColumn' . ((>> return unitPH) .) derivedUpdateAllColumn :: (PersistableWidth r, TableDerivable r) => (Record Flat r -> Restrict (PlaceHolders p)) -> Update (r, p) derivedUpdateAllColumn = updateAllColumn instance Show (Update p) where show = untypeUpdate data Insert a = Insert { untypeInsert :: String , chunkedInsert :: Maybe (String, Int) } untypeChunkInsert :: Insert a -> String untypeChunkInsert ins = maybe (untypeInsert ins) fst $ chunkedInsert ins chunkSizeOfInsert :: Insert a -> Int chunkSizeOfInsert = maybe 1 snd . chunkedInsert unsafeTypedInsert' :: String -> String -> Int -> Insert a unsafeTypedInsert' s = curry (Insert s . Just) unsafeTypedInsert :: String -> Insert a unsafeTypedInsert s = Insert s Nothing typedInsert' :: PersistableWidth r => Config -> Table r -> Pi r r' -> Insert r' typedInsert' config tbl = typedInsertValue' config tbl . piRegister typedInsert :: PersistableWidth r => Table r -> Pi r r' -> Insert r' typedInsert = typedInsert' defaultConfig insert :: (PersistableWidth r, TableDerivable r) => Pi r r' -> Insert r' insert = typedInsert' defaultConfig derivedTable derivedInsert :: (PersistableWidth r, TableDerivable r) => Pi r r' -> Insert r' derivedInsert = insert typedInsertValue' :: Config -> Table r -> Register r (PlaceHolders p) -> Insert p typedInsertValue' config tbl it = unsafeTypedInsert' (showStringSQL $ insertFromRegister config tbl it) (showStringSQL ci) n where (ci, n) = chunkInsertFromRegister config tbl it typedInsertValue :: Table r -> Register r (PlaceHolders p) -> Insert p typedInsertValue = typedInsertValue' defaultConfig insertValue' :: TableDerivable r => Config -> Register r (PlaceHolders p) -> Insert p insertValue' config rs = typedInsertValue' config (rt rs) rs where rt :: TableDerivable r => Register r (PlaceHolders p) -> Table r rt = const derivedTable # DEPRECATED derivedInsertValue ' " use ` insertValue ' ` instead of this . " # derivedInsertValue' :: TableDerivable r => Config -> Register r (PlaceHolders p) -> Insert p derivedInsertValue' = insertValue' insertValue :: TableDerivable r => Register r (PlaceHolders p) -> Insert p insertValue = insertValue' defaultConfig | Make typed ' Insert ' from ' defaultConfig ' , derived table and monadic builded ' Register ' object with ) placeholder . insertValueNoPH :: TableDerivable r => Register r () -> Insert () insertValueNoPH = insertValue . (>> return unitPH) derivedInsertValue :: TableDerivable r => Register r (PlaceHolders p) -> Insert p derivedInsertValue = insertValue insertValueList' :: (TableDerivable r, LiteralSQL r') => Config -> Pi r r' -> [r'] -> [Insert ()] insertValueList' config pi' = map (unsafeTypedInsert . showStringSQL) . chunkInsertFromRecords config derivedTable pi' insertValueList :: (TableDerivable r, LiteralSQL r') => Pi r r' -> [r'] -> [Insert ()] insertValueList = insertValueList' defaultConfig instance Show (Insert a) where show = untypeInsert | InsertQuery type . newtype InsertQuery p = InsertQuery { untypeInsertQuery :: String } | Unsafely make typed ' InsertQuery ' from SQL string . unsafeTypedInsertQuery :: String -> InsertQuery p unsafeTypedInsertQuery = InsertQuery insertQuerySQL :: Config -> Table r -> Pi r r' -> Relation p r' -> String insertQuerySQL config tbl pi' rel = showStringSQL $ insertPrefixSQL pi' tbl <> sqlFromRelationWith rel config | Make typed ' InsertQuery ' from columns selector ' Table ' , ' Pi ' and ' Relation ' with configuration parameter . typedInsertQuery' :: Config -> Table r -> Pi r r' -> Relation p r' -> InsertQuery p typedInsertQuery' config tbl pi' rel = unsafeTypedInsertQuery $ insertQuerySQL config tbl pi' rel | Make typed ' InsertQuery ' from columns selector ' Table ' , ' Pi ' and ' Relation ' . typedInsertQuery :: Table r -> Pi r r' -> Relation p r' -> InsertQuery p typedInsertQuery = typedInsertQuery' defaultConfig | Table type inferred ' InsertQuery ' . insertQuery' :: TableDerivable r => Config -> Pi r r' -> Relation p r' -> InsertQuery p insertQuery' config = typedInsertQuery' config derivedTable | Table type inferred ' InsertQuery ' with ' defaultConfig ' . insertQuery :: TableDerivable r => Pi r r' -> Relation p r' -> InsertQuery p insertQuery = insertQuery' defaultConfig | Table type inferred ' InsertQuery ' . derivedInsertQuery :: TableDerivable r => Pi r r' -> Relation p r' -> InsertQuery p derivedInsertQuery = insertQuery instance Show (InsertQuery p) where show = untypeInsertQuery newtype Delete p = Delete { untypeDelete :: String } unsafeTypedDelete :: String -> Delete p unsafeTypedDelete = Delete deleteSQL :: Config -> Table r -> (Record Flat r -> Restrict (PlaceHolders p)) -> String deleteSQL config tbl r = showStringSQL $ deleteFromRestrict config tbl r typedDelete' :: Config -> Table r -> (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p typedDelete' config tbl r = unsafeTypedDelete $ deleteSQL config tbl r typedDelete :: Table r -> (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p typedDelete = typedDelete' defaultConfig restrictedTable :: TableDerivable r => (Record Flat r -> Restrict (PlaceHolders p)) -> Table r restrictedTable = const derivedTable delete' :: TableDerivable r => Config -> (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p delete' config rc = typedDelete' config (restrictedTable rc) rc derivedDelete' :: TableDerivable r => Config -> (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p derivedDelete' = delete' delete :: TableDerivable r => (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p delete = delete' defaultConfig | Make typed ' Delete ' from ' defaultConfig ' , derived table and ' Restrict ' computation with ) placeholder . deleteNoPH :: TableDerivable r => (Record Flat r -> Restrict ()) -> Delete () deleteNoPH rf = delete $ (>> return unitPH) . rf derivedDelete :: TableDerivable r => (Record Flat r -> Restrict (PlaceHolders p)) -> Delete p derivedDelete = delete instance Show (Delete p) where show = untypeDelete | Untype interface for typed no - result type statments class UntypeableNoFetch s where untypeNoFetch :: s p -> String instance UntypeableNoFetch Insert where untypeNoFetch = untypeInsert instance UntypeableNoFetch InsertQuery where untypeNoFetch = untypeInsertQuery instance UntypeableNoFetch Update where untypeNoFetch = untypeUpdate instance UntypeableNoFetch Delete where untypeNoFetch = untypeDelete
0c42ccd5f8cf7905a1778a870f6bc577fc663b39e47942c135dcae073743d6ed
haskell-github/github
GitDiff.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} module Main where import Common import qualified GitHub.Endpoints.Repos.Commits as Github import qualified Data.Text.IO as Text main :: IO () main = do possibleDiff <- Github.diff "thoughtbot" "paperclip" "41f685f6e01396936bb8cd98e7cca517e2c7d96b" "HEAD" either (fail . show) (Text.putStrLn . showDiff) possibleDiff Check special case : when a file only changes file permissions in the commits , GitHub returns a null " sha " field for that file . -- See -fleischman/repo-change-file-permission diffFillNullSha <- Github.diff "scott-fleischman" "repo-change-file-permission" "80fdf8f83fcd8181411919fbf47394b878c591a0" "77a95bbebeb78f4fb25c6a10c3c940b6fe1caa27" either (fail . show) (const $ Text.putStrLn "Successfully parsed diff with a file with a null sha") diffFillNullSha where showDiff diff = foldl (\x y -> x <> "\n\n" <> y) "" $ concatMap (maybe [] pure . Github.filePatch) $ Github.diffFiles diff
null
https://raw.githubusercontent.com/haskell-github/github/81d9b658c33a706f18418211a78d2690752518a4/samples/Repos/Commits/GitDiff.hs
haskell
# LANGUAGE OverloadedStrings # See -fleischman/repo-change-file-permission
# LANGUAGE NoImplicitPrelude # module Main where import Common import qualified GitHub.Endpoints.Repos.Commits as Github import qualified Data.Text.IO as Text main :: IO () main = do possibleDiff <- Github.diff "thoughtbot" "paperclip" "41f685f6e01396936bb8cd98e7cca517e2c7d96b" "HEAD" either (fail . show) (Text.putStrLn . showDiff) possibleDiff Check special case : when a file only changes file permissions in the commits , GitHub returns a null " sha " field for that file . diffFillNullSha <- Github.diff "scott-fleischman" "repo-change-file-permission" "80fdf8f83fcd8181411919fbf47394b878c591a0" "77a95bbebeb78f4fb25c6a10c3c940b6fe1caa27" either (fail . show) (const $ Text.putStrLn "Successfully parsed diff with a file with a null sha") diffFillNullSha where showDiff diff = foldl (\x y -> x <> "\n\n" <> y) "" $ concatMap (maybe [] pure . Github.filePatch) $ Github.diffFiles diff
4d20278afb182366ba64ccea155b597d13ffa730a34a233c05502585d0dbf75b
gregcman/sucle
image-utility.lisp
(defpackage #:img (:use #:cl) (:shadow #:load) (:export #:w #:h #:load)) (in-package #:img) (defparameter *flip-image-p* nil) (defparameter *normalize-to-rgba-unsigned-byte-8* t) (defun load (path &key (flip *flip-image-p*) (normalize-to-rgba-unsigned-byte-8 *normalize-to-rgba-unsigned-byte-8*)) "Return an image loaded from `path`. When `flip` is t, flip the rows of the image from top to bottom. Default is nil. If `normalize-to-rgba-unsigned-byte-8` is t, coerce the array, which may have various formats, such as black and white, rgb, or be of type 1,2,4,8,16,32 ubyte, to an array with depth 4 and type unsigned-byte 8. This conversion makes some assumptions. Default is t." (let ((array (opticl:read-image-file path))) (when flip (setf array (%flip-image array))) (when normalize-to-rgba-unsigned-byte-8 (setf array (normalize-to-rgba-undigned-byte-8 array))) array)) ;;[FIXME]image-width and image-height create garbage with cons cells? (defun w (image) "Return the width of the image." (array-dimension image 0)) (defun h (image) "Return the height of the image." (array-dimension image 1)) (defun %flip-image (image) "Destructively flip the image in place." (let ((dims (array-dimensions image))) (let ((height (pop dims)) (longjumps (reduce #'* dims))) (declare (type fixnum height longjumps)) (let ((magic (* longjumps (- height 1)))) (loop for h below (* longjumps (- height (floor height 2))) by longjumps do (loop for w below longjumps do (rotatef (row-major-aref image (+ (- magic h) w)) (row-major-aref image (+ h w)))))))) image) (defun normalize-to-rgba-undigned-byte-8 (opticl-data) "Coerce the `opticl-data`, which may have various formats, such as black and white, rgb, or be of 1,2,4,8,16,32 ubyte, to an array with depth 4 and type unsigned-byte 8. This conversion makes some assumptions. Default is t." (let ((dimensions (array-dimensions opticl-data)) (type (array-element-type opticl-data))) (when (or (not (eq 'unsigned-byte (first type))) (member type '(single-float double-float fixnum))) (error "type not supported")) (let ((channels (or (third dimensions) 1)) (width (first dimensions)) (height (second dimensions))) (if (and (equal type '(unsigned-byte 8)) (= channels 4)) Its in the rgba unsigned - byte 8 format , so just exit without converting opticl-data (let ((new (make-array (list width height 4) :element-type '(unsigned-byte 8)))) ;;[FIXME]bits not correct? 32 - > 8 = ash n -24 16 - > 8 = ash n -8 8 - > 8 = identity n 4 - > 8 = 15 - > 255 = * n 255/15 = * n 17 2 - > 8 = 3 - > 255 = * n 85 1 - > 8 = 1 - > 255 = * n 255 (flet ((u32->8 (n) (declare (optimize (speed 3) (safety 0))) (declare (type (unsigned-byte 32) n)) (ash n -24)) (u16->8 (n) (declare (optimize (speed 3) (safety 0))) (declare (type (unsigned-byte 16) n)) (ash n -8)) (u8->8 (n) n) (u4->8 (n) (declare (optimize (speed 3) (safety 0))) (declare (type (unsigned-byte 4) n)) (* n 17)) (u2->8 (n) (declare (optimize (speed 3) (safety 0))) (declare (type (unsigned-byte 2) n)) (* n 85)) (u1->8 (n) (declare (optimize (speed 3) (safety 0))) (declare (type (unsigned-byte 1) n)) (* n 255))) (let ((convert-fun (ecase (second type) (32 #'u32->8) (16 #'u16->8) (8 #'u8->8) (4 #'u4->8) (2 #'u2->8) (1 #'u1->8)))) (flet ((convert-value (value) (funcall convert-fun value))) (flet ((dump-pixels-1 (w h) (let ((gray (convert-value (aref opticl-data w h)))) ;;[FIXME]include alpha channel or not? (values gray gray gray 255))) (dump-pixels-2 (w h) (let ((gray (convert-value (aref opticl-data w h 0))) (alpha (convert-value (aref opticl-data w h 1)))) (values gray gray gray alpha))) (dump-pixels-3 (w h) (values (convert-value (aref opticl-data w h 0)) (convert-value (aref opticl-data w h 1)) (convert-value (aref opticl-data w h 2)) 255)) (dump-pixels-4 (w h) (values (convert-value (aref opticl-data w h 0)) (convert-value (aref opticl-data w h 1)) (convert-value (aref opticl-data w h 2)) (convert-value (aref opticl-data w h 3))))) (let ((dump-pixels-fun (ecase channels (1 #'dump-pixels-1) (2 #'dump-pixels-2) (3 #'dump-pixels-3) (4 #'dump-pixels-4)))) (dotimes (w width) (dotimes (h height) (multiple-value-bind (r g b a) (funcall dump-pixels-fun w h) (let ((base (* 4 (+ h (* height w))))) (setf (row-major-aref new (+ base 0)) r (row-major-aref new (+ base 1)) g (row-major-aref new (+ base 2)) b (row-major-aref new (+ base 3)) a)))))))))) new))))) a - > a a a 1.0 or a a a a ? ;;ra -> r r r a rgb - > r g b 1.0 rgba - > r g b a
null
https://raw.githubusercontent.com/gregcman/sucle/258be4ac4daaceea06a55f893227584d3772bb47/src/image-utility/image-utility.lisp
lisp
[FIXME]image-width and image-height create garbage with cons cells? [FIXME]bits not correct? [FIXME]include alpha channel or not? ra -> r r r a
(defpackage #:img (:use #:cl) (:shadow #:load) (:export #:w #:h #:load)) (in-package #:img) (defparameter *flip-image-p* nil) (defparameter *normalize-to-rgba-unsigned-byte-8* t) (defun load (path &key (flip *flip-image-p*) (normalize-to-rgba-unsigned-byte-8 *normalize-to-rgba-unsigned-byte-8*)) "Return an image loaded from `path`. When `flip` is t, flip the rows of the image from top to bottom. Default is nil. If `normalize-to-rgba-unsigned-byte-8` is t, coerce the array, which may have various formats, such as black and white, rgb, or be of type 1,2,4,8,16,32 ubyte, to an array with depth 4 and type unsigned-byte 8. This conversion makes some assumptions. Default is t." (let ((array (opticl:read-image-file path))) (when flip (setf array (%flip-image array))) (when normalize-to-rgba-unsigned-byte-8 (setf array (normalize-to-rgba-undigned-byte-8 array))) array)) (defun w (image) "Return the width of the image." (array-dimension image 0)) (defun h (image) "Return the height of the image." (array-dimension image 1)) (defun %flip-image (image) "Destructively flip the image in place." (let ((dims (array-dimensions image))) (let ((height (pop dims)) (longjumps (reduce #'* dims))) (declare (type fixnum height longjumps)) (let ((magic (* longjumps (- height 1)))) (loop for h below (* longjumps (- height (floor height 2))) by longjumps do (loop for w below longjumps do (rotatef (row-major-aref image (+ (- magic h) w)) (row-major-aref image (+ h w)))))))) image) (defun normalize-to-rgba-undigned-byte-8 (opticl-data) "Coerce the `opticl-data`, which may have various formats, such as black and white, rgb, or be of 1,2,4,8,16,32 ubyte, to an array with depth 4 and type unsigned-byte 8. This conversion makes some assumptions. Default is t." (let ((dimensions (array-dimensions opticl-data)) (type (array-element-type opticl-data))) (when (or (not (eq 'unsigned-byte (first type))) (member type '(single-float double-float fixnum))) (error "type not supported")) (let ((channels (or (third dimensions) 1)) (width (first dimensions)) (height (second dimensions))) (if (and (equal type '(unsigned-byte 8)) (= channels 4)) Its in the rgba unsigned - byte 8 format , so just exit without converting opticl-data (let ((new (make-array (list width height 4) :element-type '(unsigned-byte 8)))) 32 - > 8 = ash n -24 16 - > 8 = ash n -8 8 - > 8 = identity n 4 - > 8 = 15 - > 255 = * n 255/15 = * n 17 2 - > 8 = 3 - > 255 = * n 85 1 - > 8 = 1 - > 255 = * n 255 (flet ((u32->8 (n) (declare (optimize (speed 3) (safety 0))) (declare (type (unsigned-byte 32) n)) (ash n -24)) (u16->8 (n) (declare (optimize (speed 3) (safety 0))) (declare (type (unsigned-byte 16) n)) (ash n -8)) (u8->8 (n) n) (u4->8 (n) (declare (optimize (speed 3) (safety 0))) (declare (type (unsigned-byte 4) n)) (* n 17)) (u2->8 (n) (declare (optimize (speed 3) (safety 0))) (declare (type (unsigned-byte 2) n)) (* n 85)) (u1->8 (n) (declare (optimize (speed 3) (safety 0))) (declare (type (unsigned-byte 1) n)) (* n 255))) (let ((convert-fun (ecase (second type) (32 #'u32->8) (16 #'u16->8) (8 #'u8->8) (4 #'u4->8) (2 #'u2->8) (1 #'u1->8)))) (flet ((convert-value (value) (funcall convert-fun value))) (flet ((dump-pixels-1 (w h) (let ((gray (convert-value (aref opticl-data w h)))) (values gray gray gray 255))) (dump-pixels-2 (w h) (let ((gray (convert-value (aref opticl-data w h 0))) (alpha (convert-value (aref opticl-data w h 1)))) (values gray gray gray alpha))) (dump-pixels-3 (w h) (values (convert-value (aref opticl-data w h 0)) (convert-value (aref opticl-data w h 1)) (convert-value (aref opticl-data w h 2)) 255)) (dump-pixels-4 (w h) (values (convert-value (aref opticl-data w h 0)) (convert-value (aref opticl-data w h 1)) (convert-value (aref opticl-data w h 2)) (convert-value (aref opticl-data w h 3))))) (let ((dump-pixels-fun (ecase channels (1 #'dump-pixels-1) (2 #'dump-pixels-2) (3 #'dump-pixels-3) (4 #'dump-pixels-4)))) (dotimes (w width) (dotimes (h height) (multiple-value-bind (r g b a) (funcall dump-pixels-fun w h) (let ((base (* 4 (+ h (* height w))))) (setf (row-major-aref new (+ base 0)) r (row-major-aref new (+ base 1)) g (row-major-aref new (+ base 2)) b (row-major-aref new (+ base 3)) a)))))))))) new))))) a - > a a a 1.0 or a a a a ? rgb - > r g b 1.0 rgba - > r g b a
09534b2bd290bea133b1950a7b3fc4c90918a1917770a43d65a43e423b42d77f
ianmbloom/gudni
Deknob.hs
# LANGUAGE ScopedTypeVariables # ----------------------------------------------------------------------------- -- | -- Module : Graphics.Gudni.Raster.Constants Copyright : ( c ) 2019 -- License : BSD-style (see the file libraries/base/LICENSE) -- Maintainer : -- Stability : experimental -- Portability : portable -- -- Functions for removing "knobs" which are vertical curves that cannot be easily -- rasterized. module Graphics.Gudni.Raster.Deknob ( Bezier (..) , replaceKnobs ) where import Linear import Graphics.Gudni.Figure import qualified Data.Vector as V import Control.Lens import Control.Loop -- * Remove Knobs -- Knobs are segments of a curve where the curve point is outside of the horizontal range of the anchor points. -- In other words the curve bulges out in the x direction. It must be split into two curves that do not bulge out by finding the on curve point that is as close as possible -- to the verticle tangent point. | Constant for bifercating exactly in half . sPLIT :: (Fractional s, Num s) => s sPLIT = 1 / 2 -- | Find the point along the line from v0 v1 with the distance proportional by t. between :: Num s => s -> Point2 s -> Point2 s -> Point2 s between t v0 v1 = (v0 ^* (1-t)) ^+^ (v1 ^* t) | Given two onCurve points and a controlPoint . Find two control points and an on - curve point between them by according to the parameter t. curvePoint :: Num s => s -> Point2 s -> Point2 s -> Point2 s -> Bezier s curvePoint t v0 control v1 = let mid0 = between t v0 control mid1 = between t control v1 onCurve = between t mid0 mid1 in (Bez mid0 onCurve mid1) -- | Return true if a is left of b in screen space. isLeftOf :: (Show s, Num s, Ord s, Num s, Iota s) => Point2 s -> Point2 s -> Bool a `isLeftOf` b = a ^. pX < b ^. pX -- | Return true if a is right of b in screen space. isRightOf :: (Show s, Num s, Ord s, Num s, Iota s) => Point2 s -> Point2 s -> Bool a `isRightOf` b = a ^. pX > b ^. pX | Find a new onCurve point and two new control points that divide the curve based on the convex function . findSplit :: forall s . (Show s, Fractional s, Ord s, Num s, Iota s) => (Point2 s -> Point2 s -> Bool) -> s -> Bezier s -> Bezier s findSplit staysRelativeTo t (Bez v0 control v1) = search 0.0 1.0 t where -- | Given a range of parameters along the curve determine if the are close enough to split the curve. search :: s -> s -> s -> Bezier s search bottom top t -- So if the top and bottom parameters are close enough, return the points to divide the curve. | top - bottom <= iota = Bez mid0 onCurve mid1 Otherwise if the mid0 control point is still convex move the paramters to toward the top parameter and split again . | mid1 `staysRelativeTo` onCurve = search t top topSplit -- search closer to v0 Otherwise if the mid1 control point is still convex move the paramters to toward the bottom parameter and split again . if the mid1 control point is still convex . search bottom t bottomSplit -- search closer to v1 -- Otherwise it's not convex anymore so split it | otherwise = Bez mid0 onCurve mid1 where (Bez mid0 onCurve mid1) = curvePoint t v0 control v1 topSplit = (t + ((top - t) / 2)) bottomSplit = (bottom + ((t - bottom) / 2)) vector2 :: a -> a -> V.Vector a vector2 a b = V.singleton a `V.snoc` b -- | If a curve is a knob, split it. fixKnob :: (Show s, Fractional s, Ord s, Num s, Iota s) => Bezier s -> V.Vector (Bezier s) fixKnob (Bez v0 control v1) = -- If both sides are convex in the left direction. if control `isLeftOf` v0 && control `isLeftOf` v1 This is a left bulging knob . Split it while one part maintains that bulge . let (Bez mid0 onCurve mid1) = findSplit isLeftOf sPLIT (Bez v0 control v1) And return the two resulting curves . in vector2 (Bez v0 mid0 onCurve) (Bez onCurve mid1 v1) else-- Else if both sides are convex in the right direction if control `isRightOf` v0 && control `isRightOf` v1 This is a right bulging knob . Split it while one part maintains that bulge direction . let (Bez mid0 onCurve mid1) = findSplit isRightOf sPLIT (Bez v0 control v1) And return the two resulting curves . in vector2 (Bez v0 mid0 onCurve) (Bez onCurve mid1 v1) else -- Otherwise return the curve unharmed. V.singleton (Bez v0 control v1) replaceKnobs :: (Show s, Fractional s, Ord s, Num s, Iota s) => V.Vector (Bezier s) -> V.Vector (Bezier s) replaceKnobs triples = let len = V.length triples in V.concatMap fixKnob triples
null
https://raw.githubusercontent.com/ianmbloom/gudni/fa69f1bf08c194effca05753afe5455ebae51234/src/Graphics/Gudni/Raster/Deknob.hs
haskell
--------------------------------------------------------------------------- | Module : Graphics.Gudni.Raster.Constants License : BSD-style (see the file libraries/base/LICENSE) Stability : experimental Portability : portable Functions for removing "knobs" which are vertical curves that cannot be easily rasterized. * Remove Knobs Knobs are segments of a curve where the curve point is outside of the horizontal range of the anchor points. In other words the curve bulges out in the x direction. to the verticle tangent point. | Find the point along the line from v0 v1 with the distance proportional by t. | Return true if a is left of b in screen space. | Return true if a is right of b in screen space. | Given a range of parameters along the curve determine if the are close enough to split the curve. So if the top and bottom parameters are close enough, return the points to divide the curve. search closer to v0 search closer to v1 Otherwise it's not convex anymore so split it | If a curve is a knob, split it. If both sides are convex in the left direction. Else if both sides are convex in the right direction Otherwise return the curve unharmed.
# LANGUAGE ScopedTypeVariables # Copyright : ( c ) 2019 Maintainer : module Graphics.Gudni.Raster.Deknob ( Bezier (..) , replaceKnobs ) where import Linear import Graphics.Gudni.Figure import qualified Data.Vector as V import Control.Lens import Control.Loop It must be split into two curves that do not bulge out by finding the on curve point that is as close as possible | Constant for bifercating exactly in half . sPLIT :: (Fractional s, Num s) => s sPLIT = 1 / 2 between :: Num s => s -> Point2 s -> Point2 s -> Point2 s between t v0 v1 = (v0 ^* (1-t)) ^+^ (v1 ^* t) | Given two onCurve points and a controlPoint . Find two control points and an on - curve point between them by according to the parameter t. curvePoint :: Num s => s -> Point2 s -> Point2 s -> Point2 s -> Bezier s curvePoint t v0 control v1 = let mid0 = between t v0 control mid1 = between t control v1 onCurve = between t mid0 mid1 in (Bez mid0 onCurve mid1) isLeftOf :: (Show s, Num s, Ord s, Num s, Iota s) => Point2 s -> Point2 s -> Bool a `isLeftOf` b = a ^. pX < b ^. pX isRightOf :: (Show s, Num s, Ord s, Num s, Iota s) => Point2 s -> Point2 s -> Bool a `isRightOf` b = a ^. pX > b ^. pX | Find a new onCurve point and two new control points that divide the curve based on the convex function . findSplit :: forall s . (Show s, Fractional s, Ord s, Num s, Iota s) => (Point2 s -> Point2 s -> Bool) -> s -> Bezier s -> Bezier s findSplit staysRelativeTo t (Bez v0 control v1) = search 0.0 1.0 t where search :: s -> s -> s -> Bezier s search bottom top t | top - bottom <= iota = Bez mid0 onCurve mid1 Otherwise if the mid0 control point is still convex move the paramters to toward the top parameter and split again . | mid1 `staysRelativeTo` onCurve = Otherwise if the mid1 control point is still convex move the paramters to toward the bottom parameter and split again . if the mid1 control point is still convex . | otherwise = Bez mid0 onCurve mid1 where (Bez mid0 onCurve mid1) = curvePoint t v0 control v1 topSplit = (t + ((top - t) / 2)) bottomSplit = (bottom + ((t - bottom) / 2)) vector2 :: a -> a -> V.Vector a vector2 a b = V.singleton a `V.snoc` b fixKnob :: (Show s, Fractional s, Ord s, Num s, Iota s) => Bezier s -> V.Vector (Bezier s) fixKnob (Bez v0 control v1) = if control `isLeftOf` v0 && control `isLeftOf` v1 This is a left bulging knob . Split it while one part maintains that bulge . let (Bez mid0 onCurve mid1) = findSplit isLeftOf sPLIT (Bez v0 control v1) And return the two resulting curves . in vector2 (Bez v0 mid0 onCurve) (Bez onCurve mid1 v1) if control `isRightOf` v0 && control `isRightOf` v1 This is a right bulging knob . Split it while one part maintains that bulge direction . let (Bez mid0 onCurve mid1) = findSplit isRightOf sPLIT (Bez v0 control v1) And return the two resulting curves . in vector2 (Bez v0 mid0 onCurve) (Bez onCurve mid1 v1) V.singleton (Bez v0 control v1) replaceKnobs :: (Show s, Fractional s, Ord s, Num s, Iota s) => V.Vector (Bezier s) -> V.Vector (Bezier s) replaceKnobs triples = let len = V.length triples in V.concatMap fixKnob triples
58bbffcea78014c2e48e0f26e9aaaa3f820750e1bfbb08bc99485f19b2e0b2ca
pandoc/pandoc-lua-marshal
QuoteType.hs
| Copyright : © 2021 - 2023 SPDX - License - Identifier : MIT Maintainer : > Marshaling / unmarshaling functions of ' QuoteType ' values . Copyright : © 2021-2023 Albert Krewinkel SPDX-License-Identifier : MIT Maintainer : Albert Krewinkel <tarleb+> Marshaling/unmarshaling functions of 'QuoteType' values. -} module Text.Pandoc.Lua.Marshal.QuoteType ( peekQuoteType , pushQuoteType ) where import HsLua import Text.Pandoc.Definition (QuoteType) | Retrieves a ' QuoteType ' value from a string . peekQuoteType :: Peeker e QuoteType peekQuoteType = peekRead | Pushes a ' QuoteType ' value as a string . pushQuoteType :: Pusher e QuoteType pushQuoteType = pushString . show
null
https://raw.githubusercontent.com/pandoc/pandoc-lua-marshal/e71315da1d377cf52cd94975c20ac04616c2d935/src/Text/Pandoc/Lua/Marshal/QuoteType.hs
haskell
| Copyright : © 2021 - 2023 SPDX - License - Identifier : MIT Maintainer : > Marshaling / unmarshaling functions of ' QuoteType ' values . Copyright : © 2021-2023 Albert Krewinkel SPDX-License-Identifier : MIT Maintainer : Albert Krewinkel <tarleb+> Marshaling/unmarshaling functions of 'QuoteType' values. -} module Text.Pandoc.Lua.Marshal.QuoteType ( peekQuoteType , pushQuoteType ) where import HsLua import Text.Pandoc.Definition (QuoteType) | Retrieves a ' QuoteType ' value from a string . peekQuoteType :: Peeker e QuoteType peekQuoteType = peekRead | Pushes a ' QuoteType ' value as a string . pushQuoteType :: Pusher e QuoteType pushQuoteType = pushString . show
cf1454aa343efb13822427e05750d2e2fb7c9d52402e3dba98892bd4c6cea056
s-expressionists/Eclector
utilities.lisp
(cl:in-package #:eclector.reader.test) (def-suite* :eclector.reader.utilities :in :eclector.reader) (test convert-according-to-readtable-case/smoke "Smoke test for the CONVERT-ACCORDING-TO-READTABLE-CASE function." (mapc (lambda (foo) (destructuring-bind (token escape-ranges case expected) foo (let ((token (copy-seq token)) (eclector.reader:*readtable* (eclector.readtable:copy-readtable eclector.reader:*readtable*))) (setf (eclector.readtable:readtable-case eclector.reader:*readtable*) case) (is (string= expected (convert-according-to-readtable-case token escape-ranges)))))) '(("" () :upcase "") ("!" () :upcase "!") ("foo" () :upcase "FOO") ("foo" ((1 . 2)) :upcase "FoO") ("FOO" () :upcase "FOO") ("FOO" ((1 . 2)) :upcase "FOO") ("Foo" () :upcase "FOO") ("Foo" ((1 . 2)) :upcase "FoO") ("" () :downcase "") ("!" () :downcase "!") ("foo" () :downcase "foo") ("foo" ((1 . 2)) :downcase "foo") ("FOO" () :downcase "foo") ("FOO" ((1 . 2)) :downcase "fOo") ("Foo" () :downcase "foo") ("Foo" ((1 . 2)) :downcase "foo") ("" () :preserve "") ("!" () :preserve "!") ("foo" () :preserve "foo") ("foo" ((1 . 2)) :preserve "foo") ("FOO" () :preserve "FOO") ("FOO" ((1 . 2)) :preserve "FOO") ("Foo" () :preserve "Foo") ("Foo" ((1 . 2)) :preserve "Foo") ("" () :invert "") ("!" () :invert "!") ("!!!" ((1 . 2)) :invert "!!!") ("foo" () :invert "FOO") ("foo" ((1 . 2)) :invert "FoO") ("FOO" () :invert "foo") ("FOO" ((1 . 2)) :invert "fOo") ("Foo" () :invert "Foo") ("Foo" ((1 . 2)) :invert "Foo") ("foO" () :invert "foO") ("foO" ((1 . 2)) :invert "foO")))) (test skip-whitespace/smoke "Smoke test for the SKIP-WHITESPACE function." (mapc (lambda (input-and-expected) (destructuring-bind (input expected-value expected-position) input-and-expected (let* ((stream (make-string-input-stream input)) (value (skip-whitespace stream)) (position (file-position stream))) (is (equal expected-value value)) (is (eql expected-position position))))) '(("" nil 0) (" " t 1) ("foo" t 0) (" foo" t 1) (" foo" t 1)))) (test skip-whitespace*/smoke "Smoke test for the SKIP-WHITESPACE* function." (mapc (lambda (input-and-expected) (destructuring-bind (input expected-value expected-position) input-and-expected (let* ((stream (make-string-input-stream input)) (value (skip-whitespace* stream)) (position (file-position stream))) (is (equal expected-value value)) (is (eql expected-position position))))) '(("" nil 0) (" " nil 1) ("foo" t 0) (" foo" t 1) (" foo" t 2))))
null
https://raw.githubusercontent.com/s-expressionists/Eclector/07e314ec01944beb95a89e22b31a6b5e857330c4/test/reader/utilities.lisp
lisp
(cl:in-package #:eclector.reader.test) (def-suite* :eclector.reader.utilities :in :eclector.reader) (test convert-according-to-readtable-case/smoke "Smoke test for the CONVERT-ACCORDING-TO-READTABLE-CASE function." (mapc (lambda (foo) (destructuring-bind (token escape-ranges case expected) foo (let ((token (copy-seq token)) (eclector.reader:*readtable* (eclector.readtable:copy-readtable eclector.reader:*readtable*))) (setf (eclector.readtable:readtable-case eclector.reader:*readtable*) case) (is (string= expected (convert-according-to-readtable-case token escape-ranges)))))) '(("" () :upcase "") ("!" () :upcase "!") ("foo" () :upcase "FOO") ("foo" ((1 . 2)) :upcase "FoO") ("FOO" () :upcase "FOO") ("FOO" ((1 . 2)) :upcase "FOO") ("Foo" () :upcase "FOO") ("Foo" ((1 . 2)) :upcase "FoO") ("" () :downcase "") ("!" () :downcase "!") ("foo" () :downcase "foo") ("foo" ((1 . 2)) :downcase "foo") ("FOO" () :downcase "foo") ("FOO" ((1 . 2)) :downcase "fOo") ("Foo" () :downcase "foo") ("Foo" ((1 . 2)) :downcase "foo") ("" () :preserve "") ("!" () :preserve "!") ("foo" () :preserve "foo") ("foo" ((1 . 2)) :preserve "foo") ("FOO" () :preserve "FOO") ("FOO" ((1 . 2)) :preserve "FOO") ("Foo" () :preserve "Foo") ("Foo" ((1 . 2)) :preserve "Foo") ("" () :invert "") ("!" () :invert "!") ("!!!" ((1 . 2)) :invert "!!!") ("foo" () :invert "FOO") ("foo" ((1 . 2)) :invert "FoO") ("FOO" () :invert "foo") ("FOO" ((1 . 2)) :invert "fOo") ("Foo" () :invert "Foo") ("Foo" ((1 . 2)) :invert "Foo") ("foO" () :invert "foO") ("foO" ((1 . 2)) :invert "foO")))) (test skip-whitespace/smoke "Smoke test for the SKIP-WHITESPACE function." (mapc (lambda (input-and-expected) (destructuring-bind (input expected-value expected-position) input-and-expected (let* ((stream (make-string-input-stream input)) (value (skip-whitespace stream)) (position (file-position stream))) (is (equal expected-value value)) (is (eql expected-position position))))) '(("" nil 0) (" " t 1) ("foo" t 0) (" foo" t 1) (" foo" t 1)))) (test skip-whitespace*/smoke "Smoke test for the SKIP-WHITESPACE* function." (mapc (lambda (input-and-expected) (destructuring-bind (input expected-value expected-position) input-and-expected (let* ((stream (make-string-input-stream input)) (value (skip-whitespace* stream)) (position (file-position stream))) (is (equal expected-value value)) (is (eql expected-position position))))) '(("" nil 0) (" " nil 1) ("foo" t 0) (" foo" t 1) (" foo" t 2))))
c129936d6ac9b73587805b275bcd2599e41bb4281f69b39db8cfdd59de5a4d88
otakar-smrz/elixir-fm
Derive.hs
-- | -- -- Module : Elixir.Derive Copyright : 2005 - 2016 -- License : GPL -- -- Maintainer : otakar-smrz users.sf.net -- Stability : provisional -- Portability : portable -- -- "ElixirFM" module Elixir.Derive where import Elixir.Template import Elixir.Patterns import Elixir.System import Elixir.Entity import Elixir.Pretty import Data.List instance (Show a, Template a) => Pretty [(String, [(TagsType, [(Form, Lexeme a)])])] where pretty = vcat . map pretty . filter (not . null . snd) instance (Show a, Template a) => Pretty (String, [(TagsType, [(Form, Lexeme a)])]) where pretty (x, y) = text x <> align ( vcat [ text "\t" <> pretty t <> hcat ( punctuate ( line <> text "\t" <> fill 10 empty ) [ joinText [show u, merge r (morphs e), show r, show (morphs e)] | (u, Lexeme r e) <- f ] ) | (t, f) <- y, not (null f) ] ) instance (Show a, Template a) => Pretty [(TagsType, [(Form, Lexeme a)])] where pretty = singleline pretty . filter (not . null . snd) instance (Show a, Template a) => Pretty (TagsType, [(Form, Lexeme a)]) where pretty (x, y) = pretty x <> (nest 10 . vcat) [ joinText [show u, merge r (morphs e), show r, show (morphs e)] | (u, Lexeme r e) <- y ] class Derive m p where derive :: (Morphing a a, Forming a, Rules a) => m a -> p -> [(TagsType, [(Form, Lexeme a)])] newtype Derived a = Derived [(TagsType, [(Form, Lexeme a)])] instance Show a => Show (Derived a) where show (Derived x) = show x instance (Show a, Template a) => Pretty (Derived a) where pretty (Derived x) = pretty x instance Derive Lexeme String where derive x y = derive x (convert y) instance Derive Lexeme a => Derive Lexeme [a] where derive x y = [ z | i <- y, z <- derive x i ] instance Derive Lexeme TagsTypes where derive x (TagsTypes y) = derive x y instance Derive Lexeme TagsType where derive x y = case expand y of TagsVerb z -> derive x (first z) TagsNoun z -> derive x (first z) TagsAdj z -> derive x (first z) _ -> [] instance Derive Lexeme TagsVerb where derive ( Lexeme r e ) x | ( not . isVerb ) ( entity e ) = [ ] derive (Lexeme r e) x = [ (y, z) | let y = TagsVerb [], let z = [ (f, z) | f <- [I ..], let ms = lookNoun (morphs e) (domain e) 'V' (nounStems f r), m <- nub ms, let z = Lexeme r (m `verb` (reflex e)) ] ] instance Derive Lexeme TagsNoun where derive ( Lexeme r e ) x | ( not . ) ( entity e ) = [ ] derive (Lexeme r e) x | isVerb (entity e) && (not . null) ms = [ (y, z) | let y = TagsNoun [], let z = [ (f, z) | f <- fs, m <- ms, let z = Lexeme r (m `noun` (reflex e)) ] ] where Verb fs _ _ _ ms _ _ = entity e derive (Lexeme r e) x = [ (y, z) | let y = TagsNoun [], let z = [ (f, z) | f <- [I ..], let ms = lookNoun (morphs e) (domain e) 'N' (nounStems f r), m <- nub ms, let z = Lexeme r (m `noun` (reflex e)) ] ] instance Derive Lexeme TagsAdj where derive ( Lexeme r e ) x | ( not . isAdj ) ( entity e ) = [ ] derive (Lexeme r e) x@(TagsAdjA _ v _ _ _ _) = [ (y, z) | let v' = vals v, v <- v', let y = TagsAdj [TagsAdjA [] [v] [] [] [] []], let z = [ (f, z) | f <- [I ..], let ms = lookNoun (morphs e) (domain e) (show' v) (nounStems f r), m <- nub ms, let z = Lexeme r (m `adj` (reflex e)) ] ] instance Derive Lexeme a => Derive Entry a where derive x = derive (Lexeme "" x) lookupForm :: (Morphing a a, Forming a, Eq a) => Root -> Entry a -> [Form] lookupForm r e = case entity e of Verb fs _ _ _ _ _ _ -> fs Noun _ _ _ -> [ f | f <- [I ..], or [ p == b || p == c || m == d | (_, b, c, d) <- nounStems f r ] ] Adj _ _ -> [ f | f <- [I ..], or [ p == b || p == c | (_, b, c, _) <- nounStems f r ] ] _ -> [] where p = pattern m m = morphs e lookVerb :: Eq a => a -> Tense -> Voice -> Bool -> Tense -> Voice -> Bool -> [VerbStems a] -> [a] lookVerb x t v b t' v' b' = map (findVerb t' v' b') . siftVerb x t v b siftVerb :: Eq a => a -> Tense -> Voice -> Bool -> [VerbStems a] -> [VerbStems a] siftVerb x Perfect Active True is = [ i | i@(Just (a, _, _, _), _, _, _, _) <- is, x == a ] siftVerb x Perfect Active _ is = [ i | i@(_ , a, _, _, _) <- is, x == a ] siftVerb x Perfect Passive True is = [ i | i@(Just (_, b, _, _), _, _, _, _) <- is, x == b ] siftVerb x Perfect Passive _ is = [ i | i@(_ , _, b, _, _) <- is, x == b ] siftVerb x _ Active True is = [ i | i@(Just (_, _, c, _), _, _, _, _) <- is, x == c ] siftVerb x _ Active _ is = [ i | i@(_ , _, _, c, _) <- is, x == c ] siftVerb x _ _ True is = [ i | i@(Just (_, _, _, d), _, _, _, _) <- is, x == d ] siftVerb x _ _ _ is = [ i | i@(_ , _, _, _, d) <- is, x == d ] findVerb :: Tense -> Voice -> Bool -> VerbStems a -> a findVerb Perfect Active True (Just (a, _, _, _), _, _, _, _) = a findVerb Perfect Active _ ( _ , a, _, _, _) = a findVerb Perfect Passive True (Just (_, b, _, _), _, _, _, _) = b findVerb Perfect Passive _ ( _ , _, b, _, _) = b findVerb _ Active True (Just (_, _, c, _), _, _, _, _) = c findVerb _ Active _ ( _ , _, _, c, _) = c findVerb _ _ True (Just (_, _, _, d), _, _, _, _) = d findVerb _ _ _ ( _ , _, _, _, d) = d lookNoun :: (Morphing a a, Eq a) => Morphs a -> TagsType -> Char -> [NounStems a] -> [Morphs a] lookNoun x y y' = map (findNoun y') . siftNoun x y siftNoun :: (Morphing a a, Eq a) => Morphs a -> TagsType -> [NounStems a] -> [NounStems a] siftNoun x (TagsVerb _) is = [ i | i@(a, _, _, _) <- is, x == morph a ] siftNoun x (TagsAdj _) is = [ i | i@(_, b, c, _) <- is, x == morph b || x == morph c ] siftNoun x (TagsNoun _) is = [ i | i@(_, b, c, d) <- is, x == morph b || x == morph c || x == d ] siftNoun _ _ _ = [] findNoun :: Morphing a a => Char -> NounStems a -> Morphs a findNoun 'V' (a, _, _, _) = morph a findNoun 'A' (_, b, _, _) = morph b findNoun 'P' (_, _, c, _) = morph c findNoun 'N' (_, _, _, d) = d
null
https://raw.githubusercontent.com/otakar-smrz/elixir-fm/fae5bab6dd53c15d25c1e147e7787b2c254aabf0/Haskell/ElixirFM/Elixir/Derive.hs
haskell
| Module : Elixir.Derive License : GPL Maintainer : otakar-smrz users.sf.net Stability : provisional Portability : portable "ElixirFM"
Copyright : 2005 - 2016 module Elixir.Derive where import Elixir.Template import Elixir.Patterns import Elixir.System import Elixir.Entity import Elixir.Pretty import Data.List instance (Show a, Template a) => Pretty [(String, [(TagsType, [(Form, Lexeme a)])])] where pretty = vcat . map pretty . filter (not . null . snd) instance (Show a, Template a) => Pretty (String, [(TagsType, [(Form, Lexeme a)])]) where pretty (x, y) = text x <> align ( vcat [ text "\t" <> pretty t <> hcat ( punctuate ( line <> text "\t" <> fill 10 empty ) [ joinText [show u, merge r (morphs e), show r, show (morphs e)] | (u, Lexeme r e) <- f ] ) | (t, f) <- y, not (null f) ] ) instance (Show a, Template a) => Pretty [(TagsType, [(Form, Lexeme a)])] where pretty = singleline pretty . filter (not . null . snd) instance (Show a, Template a) => Pretty (TagsType, [(Form, Lexeme a)]) where pretty (x, y) = pretty x <> (nest 10 . vcat) [ joinText [show u, merge r (morphs e), show r, show (morphs e)] | (u, Lexeme r e) <- y ] class Derive m p where derive :: (Morphing a a, Forming a, Rules a) => m a -> p -> [(TagsType, [(Form, Lexeme a)])] newtype Derived a = Derived [(TagsType, [(Form, Lexeme a)])] instance Show a => Show (Derived a) where show (Derived x) = show x instance (Show a, Template a) => Pretty (Derived a) where pretty (Derived x) = pretty x instance Derive Lexeme String where derive x y = derive x (convert y) instance Derive Lexeme a => Derive Lexeme [a] where derive x y = [ z | i <- y, z <- derive x i ] instance Derive Lexeme TagsTypes where derive x (TagsTypes y) = derive x y instance Derive Lexeme TagsType where derive x y = case expand y of TagsVerb z -> derive x (first z) TagsNoun z -> derive x (first z) TagsAdj z -> derive x (first z) _ -> [] instance Derive Lexeme TagsVerb where derive ( Lexeme r e ) x | ( not . isVerb ) ( entity e ) = [ ] derive (Lexeme r e) x = [ (y, z) | let y = TagsVerb [], let z = [ (f, z) | f <- [I ..], let ms = lookNoun (morphs e) (domain e) 'V' (nounStems f r), m <- nub ms, let z = Lexeme r (m `verb` (reflex e)) ] ] instance Derive Lexeme TagsNoun where derive ( Lexeme r e ) x | ( not . ) ( entity e ) = [ ] derive (Lexeme r e) x | isVerb (entity e) && (not . null) ms = [ (y, z) | let y = TagsNoun [], let z = [ (f, z) | f <- fs, m <- ms, let z = Lexeme r (m `noun` (reflex e)) ] ] where Verb fs _ _ _ ms _ _ = entity e derive (Lexeme r e) x = [ (y, z) | let y = TagsNoun [], let z = [ (f, z) | f <- [I ..], let ms = lookNoun (morphs e) (domain e) 'N' (nounStems f r), m <- nub ms, let z = Lexeme r (m `noun` (reflex e)) ] ] instance Derive Lexeme TagsAdj where derive ( Lexeme r e ) x | ( not . isAdj ) ( entity e ) = [ ] derive (Lexeme r e) x@(TagsAdjA _ v _ _ _ _) = [ (y, z) | let v' = vals v, v <- v', let y = TagsAdj [TagsAdjA [] [v] [] [] [] []], let z = [ (f, z) | f <- [I ..], let ms = lookNoun (morphs e) (domain e) (show' v) (nounStems f r), m <- nub ms, let z = Lexeme r (m `adj` (reflex e)) ] ] instance Derive Lexeme a => Derive Entry a where derive x = derive (Lexeme "" x) lookupForm :: (Morphing a a, Forming a, Eq a) => Root -> Entry a -> [Form] lookupForm r e = case entity e of Verb fs _ _ _ _ _ _ -> fs Noun _ _ _ -> [ f | f <- [I ..], or [ p == b || p == c || m == d | (_, b, c, d) <- nounStems f r ] ] Adj _ _ -> [ f | f <- [I ..], or [ p == b || p == c | (_, b, c, _) <- nounStems f r ] ] _ -> [] where p = pattern m m = morphs e lookVerb :: Eq a => a -> Tense -> Voice -> Bool -> Tense -> Voice -> Bool -> [VerbStems a] -> [a] lookVerb x t v b t' v' b' = map (findVerb t' v' b') . siftVerb x t v b siftVerb :: Eq a => a -> Tense -> Voice -> Bool -> [VerbStems a] -> [VerbStems a] siftVerb x Perfect Active True is = [ i | i@(Just (a, _, _, _), _, _, _, _) <- is, x == a ] siftVerb x Perfect Active _ is = [ i | i@(_ , a, _, _, _) <- is, x == a ] siftVerb x Perfect Passive True is = [ i | i@(Just (_, b, _, _), _, _, _, _) <- is, x == b ] siftVerb x Perfect Passive _ is = [ i | i@(_ , _, b, _, _) <- is, x == b ] siftVerb x _ Active True is = [ i | i@(Just (_, _, c, _), _, _, _, _) <- is, x == c ] siftVerb x _ Active _ is = [ i | i@(_ , _, _, c, _) <- is, x == c ] siftVerb x _ _ True is = [ i | i@(Just (_, _, _, d), _, _, _, _) <- is, x == d ] siftVerb x _ _ _ is = [ i | i@(_ , _, _, _, d) <- is, x == d ] findVerb :: Tense -> Voice -> Bool -> VerbStems a -> a findVerb Perfect Active True (Just (a, _, _, _), _, _, _, _) = a findVerb Perfect Active _ ( _ , a, _, _, _) = a findVerb Perfect Passive True (Just (_, b, _, _), _, _, _, _) = b findVerb Perfect Passive _ ( _ , _, b, _, _) = b findVerb _ Active True (Just (_, _, c, _), _, _, _, _) = c findVerb _ Active _ ( _ , _, _, c, _) = c findVerb _ _ True (Just (_, _, _, d), _, _, _, _) = d findVerb _ _ _ ( _ , _, _, _, d) = d lookNoun :: (Morphing a a, Eq a) => Morphs a -> TagsType -> Char -> [NounStems a] -> [Morphs a] lookNoun x y y' = map (findNoun y') . siftNoun x y siftNoun :: (Morphing a a, Eq a) => Morphs a -> TagsType -> [NounStems a] -> [NounStems a] siftNoun x (TagsVerb _) is = [ i | i@(a, _, _, _) <- is, x == morph a ] siftNoun x (TagsAdj _) is = [ i | i@(_, b, c, _) <- is, x == morph b || x == morph c ] siftNoun x (TagsNoun _) is = [ i | i@(_, b, c, d) <- is, x == morph b || x == morph c || x == d ] siftNoun _ _ _ = [] findNoun :: Morphing a a => Char -> NounStems a -> Morphs a findNoun 'V' (a, _, _, _) = morph a findNoun 'A' (_, b, _, _) = morph b findNoun 'P' (_, _, c, _) = morph c findNoun 'N' (_, _, _, d) = d
d609c9b5a892ea90719dca2fdc6ee9d8718be328e0c7d663c532cb79678d28f1
BinaryAnalysisPlatform/bap
bap_expi.mli
open Core_kernel[@@warning "-D"] open Monads.Std open Bap_common_types open Bap_bil open Bap_result open Bap_type_error open Bap_expi_types class context : Context.t module type S = Expi.S module Make(M : Monad.State.S2) : S with type ('a,'e) state = ('a,'e) M.t include S with type ('a,'e) state = ('a,'e) Monad.State.t val eval : exp -> value
null
https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/cbdf732d46c8e38df79d9942fc49bcb97915c657/lib/bap_types/bap_expi.mli
ocaml
open Core_kernel[@@warning "-D"] open Monads.Std open Bap_common_types open Bap_bil open Bap_result open Bap_type_error open Bap_expi_types class context : Context.t module type S = Expi.S module Make(M : Monad.State.S2) : S with type ('a,'e) state = ('a,'e) M.t include S with type ('a,'e) state = ('a,'e) Monad.State.t val eval : exp -> value
a5374f4515b73ccf30e219c80ae2d3e6bd55d89b6caed15ffe9706315245520a
spechub/Hets
IOS.hs
# LANGUAGE MultiParamTypeClasses , FlexibleInstances # | Module : ./Common / IOS.hs Description : An IO State Monad implementation Copyright : ( c ) , DFKI Bremen 2010 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : provisional Portability : non - portable ( various -fglasgow - exts extensions ) An IO State Monad implementation taken from -passau.de/cl/lehre/funcprog05/folien/s07.pdf Appearently the IOS type comes from as you can see in -archive.com//msg07405.html Module : ./Common/IOS.hs Description : An IO State Monad implementation Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : provisional Portability : non-portable (various -fglasgow-exts extensions) An IO State Monad implementation taken from -passau.de/cl/lehre/funcprog05/folien/s07.pdf Appearently the IOS type comes from John O'Donnell as you can see in -archive.com//msg07405.html -} module Common.IOS (IOS (..), runIOS, stmap) where import Control.Monad.Trans (MonadIO (..)) import Control.Monad.State (MonadState (..)) * IO State Monad -- | An IO State Monad data IOS s a = IOS { unIOS :: s -> IO (a, s) } getIOS :: IOS s s getIOS = IOS (\ s -> return (s, s)) setIOS :: s -> IOS s () setIOS s = IOS (\ _ -> return ((), s)) {- not needed modifyIOS :: (s->s) -> IOS s s modifyIOS f = IOS (\s -> return (s, f s)) -} runIOS :: s -> IOS s a -> IO (a, s) runIOS s cmd = unIOS cmd s -- | Like fmap but changes the state type, this needs map and unmap functions stmap :: (s -> s') -> (s' -> s) -> IOS s a -> IOS s' a stmap map' unmap ios = let f (a, b) = (a, map' b) in IOS (fmap f . unIOS ios . unmap) instance Monad (IOS s) where return x = IOS (\ s -> return (x, s)) m >>= f = IOS (\ s -> do { (x, s1) <- unIOS m s ; unIOS (f x) s1 } ) instance MonadIO (IOS s) where liftIO m = IOS (\ s -> do { a <- m; return (a, s) }) instance MonadState s (IOS s) where get = getIOS put = setIOS
null
https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/Common/IOS.hs
haskell
| An IO State Monad not needed modifyIOS :: (s->s) -> IOS s s modifyIOS f = IOS (\s -> return (s, f s)) | Like fmap but changes the state type, this needs map and unmap functions
# LANGUAGE MultiParamTypeClasses , FlexibleInstances # | Module : ./Common / IOS.hs Description : An IO State Monad implementation Copyright : ( c ) , DFKI Bremen 2010 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : provisional Portability : non - portable ( various -fglasgow - exts extensions ) An IO State Monad implementation taken from -passau.de/cl/lehre/funcprog05/folien/s07.pdf Appearently the IOS type comes from as you can see in -archive.com//msg07405.html Module : ./Common/IOS.hs Description : An IO State Monad implementation Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : provisional Portability : non-portable (various -fglasgow-exts extensions) An IO State Monad implementation taken from -passau.de/cl/lehre/funcprog05/folien/s07.pdf Appearently the IOS type comes from John O'Donnell as you can see in -archive.com//msg07405.html -} module Common.IOS (IOS (..), runIOS, stmap) where import Control.Monad.Trans (MonadIO (..)) import Control.Monad.State (MonadState (..)) * IO State Monad data IOS s a = IOS { unIOS :: s -> IO (a, s) } getIOS :: IOS s s getIOS = IOS (\ s -> return (s, s)) setIOS :: s -> IOS s () setIOS s = IOS (\ _ -> return ((), s)) runIOS :: s -> IOS s a -> IO (a, s) runIOS s cmd = unIOS cmd s stmap :: (s -> s') -> (s' -> s) -> IOS s a -> IOS s' a stmap map' unmap ios = let f (a, b) = (a, map' b) in IOS (fmap f . unIOS ios . unmap) instance Monad (IOS s) where return x = IOS (\ s -> return (x, s)) m >>= f = IOS (\ s -> do { (x, s1) <- unIOS m s ; unIOS (f x) s1 } ) instance MonadIO (IOS s) where liftIO m = IOS (\ s -> do { a <- m; return (a, s) }) instance MonadState s (IOS s) where get = getIOS put = setIOS
73805a5fb1d483e548c5f393ff3ce535bb4f1c4087efa41842682e2c4f2ff6c1
billstclair/trubanc-lisp
misc-types.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; misc-types.lisp --- Various tests on the type system. ;;; Copyright ( C ) 2005 - 2006 , loliveira(@)common - lisp.net > ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. ;;; (in-package #:cffi-tests) (defcfun ("my_strdup" strdup) :string+ptr (str :string)) (deftest misc-types.string+ptr (destructuring-bind (string pointer) (strdup "foo") (foreign-free pointer) string) "foo") #-(and) (deftest misc-types.string+ptr.ub8 (destructuring-bind (string pointer) (strdup (make-array 3 :element-type '(unsigned-byte 8) :initial-contents (map 'list #'char-code "foo"))) (foreign-free pointer) string) "foo") #-(and) (deftest misc-types.string.ub8.1 (let ((array (make-array 7 :element-type '(unsigned-byte 8) :initial-contents '(84 117 114 97 110 103 97)))) (with-foreign-string (foreign-string array) (foreign-string-to-lisp foreign-string))) "Turanga") #-(and) (deftest misc-types.string.ub8.2 (let ((str (foreign-string-alloc (make-array 7 :element-type '(unsigned-byte 8) :initial-contents '(84 117 114 97 110 103 97))))) (prog1 (foreign-string-to-lisp str) (foreign-string-free str))) "Turanga") (defcfun "equalequal" :boolean (a (:boolean :int)) (b (:boolean :unsigned-int))) (defcfun "bool_and" (:boolean :char) (a (:boolean :unsigned-char)) (b (:boolean :char))) (defcfun "bool_xor" (:boolean :unsigned-long) (a (:boolean :long)) (b (:boolean :unsigned-long))) (deftest misc-types.boolean.1 (list (equalequal nil nil) (equalequal t t) (equalequal t 23) (bool-and 'a 'b) (bool-and "foo" nil) (bool-xor t nil) (bool-xor nil nil)) (t t t t nil t nil)) ;;; Regression test: boolean type only worked with canonicalized ;;; built-in integer types. Should work for any type that canonicalizes ;;; to a built-in integer type. (defctype int-for-bool :int) (defcfun ("equalequal" equalequal2) :boolean (a (:boolean int-for-bool)) (b (:boolean :uint))) (deftest misc-types.boolean.2 (equalequal2 nil t) nil) (defctype my-string :string+ptr) (defun funkify (str) (concatenate 'string "MORE " (string-upcase str))) (defun 3rd-person (value) (list (concatenate 'string "Strdup says: " (first value)) (second value))) ;; (defctype funky-string ;; (:wrapper my-string ;; :to-c #'funkify ;; :from-c (lambda (value) ;; (list ( concatenate ' string " says : " ( first value ) ) ( second value ) ) ) ) ;; "A useful type.") (defctype funky-string (:wrapper my-string :to-c funkify :from-c 3rd-person)) (defcfun ("my_strdup" funky-strdup) funky-string (str funky-string)) (deftest misc-types.wrapper (destructuring-bind (string ptr) (funky-strdup "code") (foreign-free ptr) string) "Strdup says: MORE CODE") (deftest misc-types.sized-ints (mapcar #'foreign-type-size '(:int8 :uint8 :int16 :uint16 :int32 :uint32 :int64 :uint64)) (1 1 2 2 4 4 8 8)) (define-foreign-type error-error () () (:actual-type :int) (:simple-parser error-error)) (defmethod translate-to-foreign (value (type error-error)) (declare (ignore value)) (error "translate-to-foreign invoked.")) (defmethod translate-from-foreign (value (type error-error)) (declare (ignore value)) (error "translate-from-foreign invoked.")) (eval-when (:load-toplevel :compile-toplevel :execute) (defmethod expand-to-foreign (value (type error-error)) value) (defmethod expand-from-foreign (value (type error-error)) value)) (defcfun ("abs" expand-abs) error-error (n error-error)) (defcvar ("var_int" *expand-var-int*) error-error) (defcfun ("expect_int_sum" expand-expect-int-sum) :boolean (cb :pointer)) (defcallback expand-int-sum error-error ((x error-error) (y error-error)) (+ x y)) ;;; Ensure that macroexpansion-time translators are called where this is guaranteed ( defcfun , defcvar , foreign - funcall and ) (deftest misc-types.expand.1 (expand-abs -1) 1) #-cffi-sys::no-foreign-funcall (deftest misc-types.expand.2 (foreign-funcall "abs" error-error -1 error-error) 1) (deftest misc-types.expand.3 (let ((old (mem-ref (get-var-pointer '*expand-var-int*) :int))) (unwind-protect (progn (setf *expand-var-int* 42) *expand-var-int*) (setf (mem-ref (get-var-pointer '*expand-var-int*) :int) old))) 42) (deftest misc-types.expand.4 (expand-expect-int-sum (callback expand-int-sum)) t) (define-foreign-type translate-tracker () () (:actual-type :int) (:simple-parser translate-tracker)) (declaim (special .fto-called.)) (defmethod free-translated-object (value (type translate-tracker) param) (declare (ignore value param)) (setf .fto-called. t)) (define-foreign-type expand-tracker () () (:actual-type :int) (:simple-parser expand-tracker)) (defmethod free-translated-object (value (type expand-tracker) param) (declare (ignore value param)) (setf .fto-called. t)) (eval-when (:compile-toplevel :load-toplevel :execute) (defmethod expand-to-foreign (value (type expand-tracker)) (declare (ignore value)) (call-next-method))) (defcfun ("abs" ttracker-abs) :int (n translate-tracker)) (defcfun ("abs" etracker-abs) :int (n expand-tracker)) ;; free-translated-object must be called when there is no etf (deftest misc-types.expand.5 (let ((.fto-called. nil)) (ttracker-abs -1) .fto-called.) t) ;; free-translated-object must be called when there is an etf, but ;; they answer *runtime-translator-form* (deftest misc-types.expand.6 (let ((.fto-called. nil)) (etracker-abs -1) .fto-called.) t)
null
https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/systems/cffi_0.10.4/tests/misc-types.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- misc-types.lisp --- Various tests on the type system. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Regression test: boolean type only worked with canonicalized built-in integer types. Should work for any type that canonicalizes to a built-in integer type. (defctype funky-string (:wrapper my-string :to-c #'funkify :from-c (lambda (value) (list "A useful type.") Ensure that macroexpansion-time translators are called where this free-translated-object must be called when there is no etf free-translated-object must be called when there is an etf, but they answer *runtime-translator-form*
Copyright ( C ) 2005 - 2006 , loliveira(@)common - lisp.net > files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , (in-package #:cffi-tests) (defcfun ("my_strdup" strdup) :string+ptr (str :string)) (deftest misc-types.string+ptr (destructuring-bind (string pointer) (strdup "foo") (foreign-free pointer) string) "foo") #-(and) (deftest misc-types.string+ptr.ub8 (destructuring-bind (string pointer) (strdup (make-array 3 :element-type '(unsigned-byte 8) :initial-contents (map 'list #'char-code "foo"))) (foreign-free pointer) string) "foo") #-(and) (deftest misc-types.string.ub8.1 (let ((array (make-array 7 :element-type '(unsigned-byte 8) :initial-contents '(84 117 114 97 110 103 97)))) (with-foreign-string (foreign-string array) (foreign-string-to-lisp foreign-string))) "Turanga") #-(and) (deftest misc-types.string.ub8.2 (let ((str (foreign-string-alloc (make-array 7 :element-type '(unsigned-byte 8) :initial-contents '(84 117 114 97 110 103 97))))) (prog1 (foreign-string-to-lisp str) (foreign-string-free str))) "Turanga") (defcfun "equalequal" :boolean (a (:boolean :int)) (b (:boolean :unsigned-int))) (defcfun "bool_and" (:boolean :char) (a (:boolean :unsigned-char)) (b (:boolean :char))) (defcfun "bool_xor" (:boolean :unsigned-long) (a (:boolean :long)) (b (:boolean :unsigned-long))) (deftest misc-types.boolean.1 (list (equalequal nil nil) (equalequal t t) (equalequal t 23) (bool-and 'a 'b) (bool-and "foo" nil) (bool-xor t nil) (bool-xor nil nil)) (t t t t nil t nil)) (defctype int-for-bool :int) (defcfun ("equalequal" equalequal2) :boolean (a (:boolean int-for-bool)) (b (:boolean :uint))) (deftest misc-types.boolean.2 (equalequal2 nil t) nil) (defctype my-string :string+ptr) (defun funkify (str) (concatenate 'string "MORE " (string-upcase str))) (defun 3rd-person (value) (list (concatenate 'string "Strdup says: " (first value)) (second value))) ( concatenate ' string " says : " ( first value ) ) ( second value ) ) ) ) (defctype funky-string (:wrapper my-string :to-c funkify :from-c 3rd-person)) (defcfun ("my_strdup" funky-strdup) funky-string (str funky-string)) (deftest misc-types.wrapper (destructuring-bind (string ptr) (funky-strdup "code") (foreign-free ptr) string) "Strdup says: MORE CODE") (deftest misc-types.sized-ints (mapcar #'foreign-type-size '(:int8 :uint8 :int16 :uint16 :int32 :uint32 :int64 :uint64)) (1 1 2 2 4 4 8 8)) (define-foreign-type error-error () () (:actual-type :int) (:simple-parser error-error)) (defmethod translate-to-foreign (value (type error-error)) (declare (ignore value)) (error "translate-to-foreign invoked.")) (defmethod translate-from-foreign (value (type error-error)) (declare (ignore value)) (error "translate-from-foreign invoked.")) (eval-when (:load-toplevel :compile-toplevel :execute) (defmethod expand-to-foreign (value (type error-error)) value) (defmethod expand-from-foreign (value (type error-error)) value)) (defcfun ("abs" expand-abs) error-error (n error-error)) (defcvar ("var_int" *expand-var-int*) error-error) (defcfun ("expect_int_sum" expand-expect-int-sum) :boolean (cb :pointer)) (defcallback expand-int-sum error-error ((x error-error) (y error-error)) (+ x y)) is guaranteed ( defcfun , defcvar , foreign - funcall and ) (deftest misc-types.expand.1 (expand-abs -1) 1) #-cffi-sys::no-foreign-funcall (deftest misc-types.expand.2 (foreign-funcall "abs" error-error -1 error-error) 1) (deftest misc-types.expand.3 (let ((old (mem-ref (get-var-pointer '*expand-var-int*) :int))) (unwind-protect (progn (setf *expand-var-int* 42) *expand-var-int*) (setf (mem-ref (get-var-pointer '*expand-var-int*) :int) old))) 42) (deftest misc-types.expand.4 (expand-expect-int-sum (callback expand-int-sum)) t) (define-foreign-type translate-tracker () () (:actual-type :int) (:simple-parser translate-tracker)) (declaim (special .fto-called.)) (defmethod free-translated-object (value (type translate-tracker) param) (declare (ignore value param)) (setf .fto-called. t)) (define-foreign-type expand-tracker () () (:actual-type :int) (:simple-parser expand-tracker)) (defmethod free-translated-object (value (type expand-tracker) param) (declare (ignore value param)) (setf .fto-called. t)) (eval-when (:compile-toplevel :load-toplevel :execute) (defmethod expand-to-foreign (value (type expand-tracker)) (declare (ignore value)) (call-next-method))) (defcfun ("abs" ttracker-abs) :int (n translate-tracker)) (defcfun ("abs" etracker-abs) :int (n expand-tracker)) (deftest misc-types.expand.5 (let ((.fto-called. nil)) (ttracker-abs -1) .fto-called.) t) (deftest misc-types.expand.6 (let ((.fto-called. nil)) (etracker-abs -1) .fto-called.) t)
c4c0e5806ba92668a1ec788cc74e7d624b1d7982dc6fb2880a7932df3a66775c
sebastiaanvisser/ghc-goals
Main.hs
module Main where import Dep main :: IO () main = putStrLn $ map undefined test
null
https://raw.githubusercontent.com/sebastiaanvisser/ghc-goals/cf256c99c4b7e3b569bab3e6c10f0903a7c1eac4/tests/Main.hs
haskell
module Main where import Dep main :: IO () main = putStrLn $ map undefined test
a7a685b55e0f1d6ff52c0227c4a80444c5573234079f7fe0d8ec9bfd1dcdd775
basho-labs/mesos-erlang
erl_mesos_env.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2016 Basho Technologies Inc. All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file %% except in compliance with the License. You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- -module(erl_mesos_env). -export([get_value/1, get_value/2, get_converted_value/2, get_converted_value/3]). %% External functions. @equiv , undefined ) -spec get_value(atom()) -> term(). get_value(Name) -> get_value(Name, undefined). %% @doc Returns value. -spec get_value(atom(), term()) -> term(). get_value(Name, DefaultValue) -> case os:getenv("MESOS_" ++ string:to_upper(atom_to_list(Name))) of false -> DefaultValue; Value -> Value end. @equiv get_converted_value(Type , Name , undefined ) -spec get_converted_value(atom(), atom()) -> term(). get_converted_value(Type, Name) -> get_converted_value(Type, Name, undefined). %% @doc Returns converted value. -spec get_converted_value(atom(), atom(), term()) -> term(). get_converted_value(atom, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> list_to_atom(Value) end; get_converted_value(integer, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> list_to_integer(Value) end; get_converted_value(float, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> list_to_float(Value) end; get_converted_value(string, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> Value end; get_converted_value(binary, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> list_to_binary(Value) end; get_converted_value(interval, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> convert_interval(Value) end. Internal functions . %% @doc Convert interval to milli seconds. @private -spec convert_interval(string()) -> float(). convert_interval(IntervalValue) -> convert_interval(IntervalValue, [], false). %% @doc Convert interval to milli seconds. @private -spec convert_interval(string(), string(), boolean()) -> float(). convert_interval([$. = Char | Chars], IntervalChars, false) -> convert_interval(Chars, [Char | IntervalChars], true); convert_interval([Char | Chars], IntervalChars, Dot) when Char >= $0, Char =< $9 -> convert_interval(Chars, [Char | IntervalChars], Dot); convert_interval(UnitChars, IntervalChars, true) -> IntervalValue = list_to_float(lists:reverse(IntervalChars)), convert_interval(UnitChars, IntervalValue); convert_interval(UnitChars, IntervalChars, false) -> IntervalValue = float(list_to_integer(lists:reverse(IntervalChars))), convert_interval(UnitChars, IntervalValue). %% @doc Convert interval with unit to milli seconds. @private -spec convert_interval(string(), float()) -> float(). convert_interval("ns", IntervalValue) -> IntervalValue / 1000000; convert_interval("us", IntervalValue) -> IntervalValue / 1000; convert_interval("ms", IntervalValue) -> IntervalValue; convert_interval("secs", IntervalValue) -> IntervalValue * 1000; convert_interval("mins", IntervalValue) -> IntervalValue * 60000; convert_interval("hrs", IntervalValue) -> IntervalValue * 3600000; convert_interval("days", IntervalValue) -> IntervalValue * 86400000; convert_interval("weeks", IntervalValue) -> IntervalValue * 604800000.
null
https://raw.githubusercontent.com/basho-labs/mesos-erlang/b90bf62c2d614f12a0ac3cd55a915b3737198da5/src/erl_mesos_env.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- External functions. @doc Returns value. @doc Returns converted value. @doc Convert interval to milli seconds. @doc Convert interval to milli seconds. @doc Convert interval with unit to milli seconds.
Copyright ( c ) 2016 Basho Technologies Inc. All Rights Reserved . This file is provided to you under the Apache License , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(erl_mesos_env). -export([get_value/1, get_value/2, get_converted_value/2, get_converted_value/3]). @equiv , undefined ) -spec get_value(atom()) -> term(). get_value(Name) -> get_value(Name, undefined). -spec get_value(atom(), term()) -> term(). get_value(Name, DefaultValue) -> case os:getenv("MESOS_" ++ string:to_upper(atom_to_list(Name))) of false -> DefaultValue; Value -> Value end. @equiv get_converted_value(Type , Name , undefined ) -spec get_converted_value(atom(), atom()) -> term(). get_converted_value(Type, Name) -> get_converted_value(Type, Name, undefined). -spec get_converted_value(atom(), atom(), term()) -> term(). get_converted_value(atom, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> list_to_atom(Value) end; get_converted_value(integer, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> list_to_integer(Value) end; get_converted_value(float, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> list_to_float(Value) end; get_converted_value(string, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> Value end; get_converted_value(binary, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> list_to_binary(Value) end; get_converted_value(interval, Name, DefaultValue) -> case get_value(Name) of undefined -> DefaultValue; Value -> convert_interval(Value) end. Internal functions . @private -spec convert_interval(string()) -> float(). convert_interval(IntervalValue) -> convert_interval(IntervalValue, [], false). @private -spec convert_interval(string(), string(), boolean()) -> float(). convert_interval([$. = Char | Chars], IntervalChars, false) -> convert_interval(Chars, [Char | IntervalChars], true); convert_interval([Char | Chars], IntervalChars, Dot) when Char >= $0, Char =< $9 -> convert_interval(Chars, [Char | IntervalChars], Dot); convert_interval(UnitChars, IntervalChars, true) -> IntervalValue = list_to_float(lists:reverse(IntervalChars)), convert_interval(UnitChars, IntervalValue); convert_interval(UnitChars, IntervalChars, false) -> IntervalValue = float(list_to_integer(lists:reverse(IntervalChars))), convert_interval(UnitChars, IntervalValue). @private -spec convert_interval(string(), float()) -> float(). convert_interval("ns", IntervalValue) -> IntervalValue / 1000000; convert_interval("us", IntervalValue) -> IntervalValue / 1000; convert_interval("ms", IntervalValue) -> IntervalValue; convert_interval("secs", IntervalValue) -> IntervalValue * 1000; convert_interval("mins", IntervalValue) -> IntervalValue * 60000; convert_interval("hrs", IntervalValue) -> IntervalValue * 3600000; convert_interval("days", IntervalValue) -> IntervalValue * 86400000; convert_interval("weeks", IntervalValue) -> IntervalValue * 604800000.
fbef2416308c97764af4ed76b0bf7caca2a304378abe2f10f8b1b49a5ce322fa
rtoy/ansi-cl-tests
read-byte.lsp
;-*- Mode: Lisp -*- Author : Created : Sat Jan 17 17:30:49 2004 ;;;; Contains: Tests of READ-BYTE, WRITE-BYTE (in-package :cl-test) (deftest read-byte.1 (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)))) (values (write-byte 17 s) (close s) (progn (setq s (open "foo.txt" :direction :input :element-type '(unsigned-byte 8))) (read-byte s)) (close s))) 17 t 17 t) (deftest read-byte.2 (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)))) (values (close s) (progn (setq s (open "foo.txt" :direction :input :element-type '(unsigned-byte 8))) (read-byte s nil 'foo)) (read-byte s nil) (close s))) t foo nil t) (deftest read-byte.3 (loop with b1 = 0 and b2 = 0 for i from 1 to 32 do (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type `(unsigned-byte ,i)))) (write-byte (1- (ash 1 i)) s) (write-byte 1 s) (close s)) unless (let ((s (open "foo.txt" :direction :input :element-type `(unsigned-byte ,i)))) (prog1 (and (eql (setq b1 (read-byte s)) (1- (ash 1 i))) (eql (setq b2 (read-byte s)) 1)) (close s))) collect (list i b1 b2)) nil) (deftest read-byte.4 (loop with b1 = 0 and b2 = 0 for i from 33 to 200 by 7 do (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type `(unsigned-byte ,i)))) (write-byte (1- (ash 1 i)) s) (write-byte 1 s) (close s)) unless (let ((s (open "foo.txt" :direction :input :element-type `(unsigned-byte ,i)))) (prog1 (and (eql (setq b1 (read-byte s)) (1- (ash 1 i))) (eql (setq b2 (read-byte s)) 1)) (close s))) collect (list i b1 b2)) nil) ;;; Error tests (deftest read-byte.error.1 (signals-error (read-byte) program-error) t) (deftest read-byte.error.2 (progn (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type `(unsigned-byte 8)))) (close s)) (signals-error (let ((s (open "foo.txt" :direction :input :element-type '(unsigned-byte 8)))) (read-byte s)) end-of-file)) t) (deftest read-byte.error.3 (progn (let ((s (open "foo.txt" :direction :output :if-exists :supersede))) (close s)) (signals-error (let ((s (open "foo.txt" :direction :input))) (unwind-protect (read-byte s) (close s))) error)) t) (deftest read-byte.error.4 (signals-error-always (progn (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)))) (close s)) (let ((s (open "foo.txt" :direction :input :element-type '(unsigned-byte 8)))) (unwind-protect (read-byte s t) (close s)))) end-of-file) t t) (deftest read-byte.error.5 (check-type-error #'read-byte #'streamp) nil) (deftest read-byte.error.6 (progn (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)))) (close s)) (signals-error (let ((s (open "foo.txt" :direction :input :element-type '(unsigned-byte 8)))) (unwind-protect (read-byte s t t nil) (close s))) program-error)) t) (deftest write-byte.error.1 (signals-error (write-byte) program-error) t) (deftest write-byte.error.2 (signals-error (write-byte 0) program-error) t) (deftest write-byte.error.3 (signals-error (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)))) (unwind-protect (write 1 s nil) (close s))) program-error) t) (deftest write-byte.error.4 (check-type-error #'(lambda (x) (write-byte 0 x)) #'streamp) nil) (deftest write-byte.error.5 (signals-error (let ((s (open "foo.txt" :direction :output :if-exists :supersede))) (unwind-protect (write 1 s) (close s))) error) t)
null
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/read-byte.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of READ-BYTE, WRITE-BYTE Error tests
Author : Created : Sat Jan 17 17:30:49 2004 (in-package :cl-test) (deftest read-byte.1 (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)))) (values (write-byte 17 s) (close s) (progn (setq s (open "foo.txt" :direction :input :element-type '(unsigned-byte 8))) (read-byte s)) (close s))) 17 t 17 t) (deftest read-byte.2 (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)))) (values (close s) (progn (setq s (open "foo.txt" :direction :input :element-type '(unsigned-byte 8))) (read-byte s nil 'foo)) (read-byte s nil) (close s))) t foo nil t) (deftest read-byte.3 (loop with b1 = 0 and b2 = 0 for i from 1 to 32 do (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type `(unsigned-byte ,i)))) (write-byte (1- (ash 1 i)) s) (write-byte 1 s) (close s)) unless (let ((s (open "foo.txt" :direction :input :element-type `(unsigned-byte ,i)))) (prog1 (and (eql (setq b1 (read-byte s)) (1- (ash 1 i))) (eql (setq b2 (read-byte s)) 1)) (close s))) collect (list i b1 b2)) nil) (deftest read-byte.4 (loop with b1 = 0 and b2 = 0 for i from 33 to 200 by 7 do (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type `(unsigned-byte ,i)))) (write-byte (1- (ash 1 i)) s) (write-byte 1 s) (close s)) unless (let ((s (open "foo.txt" :direction :input :element-type `(unsigned-byte ,i)))) (prog1 (and (eql (setq b1 (read-byte s)) (1- (ash 1 i))) (eql (setq b2 (read-byte s)) 1)) (close s))) collect (list i b1 b2)) nil) (deftest read-byte.error.1 (signals-error (read-byte) program-error) t) (deftest read-byte.error.2 (progn (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type `(unsigned-byte 8)))) (close s)) (signals-error (let ((s (open "foo.txt" :direction :input :element-type '(unsigned-byte 8)))) (read-byte s)) end-of-file)) t) (deftest read-byte.error.3 (progn (let ((s (open "foo.txt" :direction :output :if-exists :supersede))) (close s)) (signals-error (let ((s (open "foo.txt" :direction :input))) (unwind-protect (read-byte s) (close s))) error)) t) (deftest read-byte.error.4 (signals-error-always (progn (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)))) (close s)) (let ((s (open "foo.txt" :direction :input :element-type '(unsigned-byte 8)))) (unwind-protect (read-byte s t) (close s)))) end-of-file) t t) (deftest read-byte.error.5 (check-type-error #'read-byte #'streamp) nil) (deftest read-byte.error.6 (progn (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)))) (close s)) (signals-error (let ((s (open "foo.txt" :direction :input :element-type '(unsigned-byte 8)))) (unwind-protect (read-byte s t t nil) (close s))) program-error)) t) (deftest write-byte.error.1 (signals-error (write-byte) program-error) t) (deftest write-byte.error.2 (signals-error (write-byte 0) program-error) t) (deftest write-byte.error.3 (signals-error (let ((s (open "foo.txt" :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)))) (unwind-protect (write 1 s nil) (close s))) program-error) t) (deftest write-byte.error.4 (check-type-error #'(lambda (x) (write-byte 0 x)) #'streamp) nil) (deftest write-byte.error.5 (signals-error (let ((s (open "foo.txt" :direction :output :if-exists :supersede))) (unwind-protect (write 1 s) (close s))) error) t)
ffae32378a1914cf063f9538d30545f363f089727aab4becdd092ec0bea27dd2
AccelerateHS/accelerate-examples
Tree.hs
-- A Barns - Hut tree -- module Common.Tree where
null
https://raw.githubusercontent.com/AccelerateHS/accelerate-examples/a973ee423b5eadda6ef2e2504d2383f625e49821/examples/n-body/Common/Tree.hs
haskell
A Barns - Hut tree module Common.Tree where
5fec5ad082a3ccc30495644950564517d974e44f04686ae1b25fedfa7053962e
smallmelon/sdzmmo
mysql_recv.erl
%%%------------------------------------------------------------------- %%% File : mysql_recv.erl Author : < > . : Handles data being received on a MySQL socket . %%% per-row framing and sends each row to parent. %%% Created : 4 Aug 2005 by < > %%% Note : All MySQL code was written by , originally %%% in the file mysql.erl - I just moved it here. %%% Copyright ( c ) 2001 - 2004 Kungliga Tekniska Högskolan %%% See the file COPYING %%% %%% Signals this receiver process can send to it's parent ( the parent is a mysql_conn connection handler ) : %%% { mysql_recv , self ( ) , data , Packet , } %%% {mysql_recv, self(), closed, {error, Reason}} %%% {mysql_recv, self(), closed, normal} %%% Internally ( from inside init/4 to start_link/4 ) the %%% following signals may be sent to the parent process : %%% %%% {mysql_recv, self(), init, {ok, Sock}} %%% {mysql_recv, self(), init, {error, E}} %%% %%%------------------------------------------------------------------- -module(mysql_recv). %%-------------------------------------------------------------------- External exports ( should only be used by the ' mysql_conn ' module ) %%-------------------------------------------------------------------- -export([start_link/4 ]). -record(state, { socket, parent, log_fun, data }). -define(SECURE_CONNECTION, 32768). -define(CONNECT_TIMEOUT, 5000). %%==================================================================== %% External functions %%==================================================================== %%-------------------------------------------------------------------- Function : start_link(Host , Port , , Parent ) %% Host = string() %% Port = integer() = undefined | function ( ) of arity 3 %% Parent = pid(), process that should get received frames . : Start a process that connects to Host : Port and waits for %% data. When it has received a MySQL frame, it sends it to %% Parent and waits for the next frame. Returns : { ok , RecvPid , Socket } | %% {error, Reason} %% RecvPid = pid(), receiver process pid %% Socket = term(), gen_tcp socket %% Reason = atom() | string() %%-------------------------------------------------------------------- start_link(Host, Port, LogFun, Parent) when is_list(Host), is_integer(Port) -> RecvPid = spawn_link(fun () -> init(Host, Port, LogFun, Parent) end), %% wait for the socket from the spawned pid receive {mysql_recv, RecvPid, init, {error, E}} -> {error, E}; {mysql_recv, RecvPid, init, {ok, Socket}} -> {ok, RecvPid, Socket} after ?CONNECT_TIMEOUT -> catch exit(RecvPid, kill), {error, "timeout"} end. %%==================================================================== Internal functions %%==================================================================== %%-------------------------------------------------------------------- Function : init((Host , Port , , Parent ) %% Host = string() %% Port = integer() = undefined | function ( ) of arity 3 %% Parent = pid(), process that should get received frames . : Connect to Host : Port and then enter receive - loop . %% Returns : error | never returns %%-------------------------------------------------------------------- init(Host, Port, LogFun, Parent) -> case gen_tcp:connect(Host, Port, [binary, {packet, 0}, {keepalive, true}]) of {ok, Sock} -> Parent ! {mysql_recv, self(), init, {ok, Sock}}, State = #state{socket = Sock, parent = Parent, log_fun = LogFun, data = <<>> }, loop(State); E -> LogFun(?MODULE, ?LINE, error, fun() -> {"mysql_recv: Failed connecting to ~p:~p : ~p", [Host, Port, E]} end), Msg = lists:flatten(io_lib:format("connect failed : ~p", [E])), Parent ! {mysql_recv, self(), init, {error, Msg}} end. %%-------------------------------------------------------------------- %% Function: loop(State) %% State = state record() . : The main loop . Wait for data from our TCP socket and act %% on received data or signals that our socket was closed. %% Returns : error | never returns %%-------------------------------------------------------------------- loop(State) -> Sock = State#state.socket, receive {tcp, Sock, InData} -> NewData = list_to_binary([State#state.data, InData]), %% send data to parent if we have enough data Rest = sendpacket(State#state.parent, NewData), loop(State#state{data = Rest}); {tcp_error, Sock, Reason} -> LogFun = State#state.log_fun, LogFun(?MODULE, ?LINE, error, fun() -> {"mysql_recv: Socket ~p closed : ~p", [Sock, Reason]} end), State#state.parent ! {mysql_recv, self(), closed, {error, Reason}}, error; {tcp_closed, Sock} -> LogFun = State#state.log_fun, LogFun(?MODULE, ?LINE, debug, fun() -> {"mysql_recv: Socket ~p closed", [Sock]} end), State#state.parent ! {mysql_recv, self(), closed, normal}, error end. %%-------------------------------------------------------------------- %% Function: sendpacket(Parent, Data) %% Parent = pid() %% Data = binary() . : Check if we have received one or more complete frames by %% now, and if so - send them to Parent. %% Returns : Rest = binary() %%-------------------------------------------------------------------- %% send data to parent if we have enough data sendpacket(Parent, Data) -> case Data of <<Length:24/little, Num:8, D/binary>> -> if Length =< size(D) -> {Packet, Rest} = split_binary(D, Length), Parent ! {mysql_recv, self(), data, Packet, Num}, sendpacket(Parent, Rest); true -> Data end; _ -> Data end.
null
https://raw.githubusercontent.com/smallmelon/sdzmmo/254ff430481de474527c0e96202c63fb0d2c29d2/src/lib/mysql/mysql_recv.erl
erlang
------------------------------------------------------------------- File : mysql_recv.erl per-row framing and sends each row to parent. in the file mysql.erl - I just moved it here. See the file COPYING Signals this receiver process can send to it's parent {mysql_recv, self(), closed, {error, Reason}} {mysql_recv, self(), closed, normal} following signals may be sent to the parent process : {mysql_recv, self(), init, {ok, Sock}} {mysql_recv, self(), init, {error, E}} ------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- ==================================================================== External functions ==================================================================== -------------------------------------------------------------------- Host = string() Port = integer() Parent = pid(), process that should get received frames data. When it has received a MySQL frame, it sends it to Parent and waits for the next frame. {error, Reason} RecvPid = pid(), receiver process pid Socket = term(), gen_tcp socket Reason = atom() | string() -------------------------------------------------------------------- wait for the socket from the spawned pid ==================================================================== ==================================================================== -------------------------------------------------------------------- Host = string() Port = integer() Parent = pid(), process that should get received frames Returns : error | never returns -------------------------------------------------------------------- -------------------------------------------------------------------- Function: loop(State) State = state record() on received data or signals that our socket was closed. Returns : error | never returns -------------------------------------------------------------------- send data to parent if we have enough data -------------------------------------------------------------------- Function: sendpacket(Parent, Data) Parent = pid() Data = binary() now, and if so - send them to Parent. Returns : Rest = binary() -------------------------------------------------------------------- send data to parent if we have enough data
Author : < > . : Handles data being received on a MySQL socket . Created : 4 Aug 2005 by < > Note : All MySQL code was written by , originally Copyright ( c ) 2001 - 2004 Kungliga Tekniska Högskolan ( the parent is a mysql_conn connection handler ) : { mysql_recv , self ( ) , data , Packet , } Internally ( from inside init/4 to start_link/4 ) the -module(mysql_recv). External exports ( should only be used by the ' mysql_conn ' module ) -export([start_link/4 ]). -record(state, { socket, parent, log_fun, data }). -define(SECURE_CONNECTION, 32768). -define(CONNECT_TIMEOUT, 5000). Function : start_link(Host , Port , , Parent ) = undefined | function ( ) of arity 3 . : Start a process that connects to Host : Port and waits for Returns : { ok , RecvPid , Socket } | start_link(Host, Port, LogFun, Parent) when is_list(Host), is_integer(Port) -> RecvPid = spawn_link(fun () -> init(Host, Port, LogFun, Parent) end), receive {mysql_recv, RecvPid, init, {error, E}} -> {error, E}; {mysql_recv, RecvPid, init, {ok, Socket}} -> {ok, RecvPid, Socket} after ?CONNECT_TIMEOUT -> catch exit(RecvPid, kill), {error, "timeout"} end. Internal functions Function : init((Host , Port , , Parent ) = undefined | function ( ) of arity 3 . : Connect to Host : Port and then enter receive - loop . init(Host, Port, LogFun, Parent) -> case gen_tcp:connect(Host, Port, [binary, {packet, 0}, {keepalive, true}]) of {ok, Sock} -> Parent ! {mysql_recv, self(), init, {ok, Sock}}, State = #state{socket = Sock, parent = Parent, log_fun = LogFun, data = <<>> }, loop(State); E -> LogFun(?MODULE, ?LINE, error, fun() -> {"mysql_recv: Failed connecting to ~p:~p : ~p", [Host, Port, E]} end), Msg = lists:flatten(io_lib:format("connect failed : ~p", [E])), Parent ! {mysql_recv, self(), init, {error, Msg}} end. . : The main loop . Wait for data from our TCP socket and act loop(State) -> Sock = State#state.socket, receive {tcp, Sock, InData} -> NewData = list_to_binary([State#state.data, InData]), Rest = sendpacket(State#state.parent, NewData), loop(State#state{data = Rest}); {tcp_error, Sock, Reason} -> LogFun = State#state.log_fun, LogFun(?MODULE, ?LINE, error, fun() -> {"mysql_recv: Socket ~p closed : ~p", [Sock, Reason]} end), State#state.parent ! {mysql_recv, self(), closed, {error, Reason}}, error; {tcp_closed, Sock} -> LogFun = State#state.log_fun, LogFun(?MODULE, ?LINE, debug, fun() -> {"mysql_recv: Socket ~p closed", [Sock]} end), State#state.parent ! {mysql_recv, self(), closed, normal}, error end. . : Check if we have received one or more complete frames by sendpacket(Parent, Data) -> case Data of <<Length:24/little, Num:8, D/binary>> -> if Length =< size(D) -> {Packet, Rest} = split_binary(D, Length), Parent ! {mysql_recv, self(), data, Packet, Num}, sendpacket(Parent, Rest); true -> Data end; _ -> Data end.
4ce99271e2861acc74303c8ceb8a5c80143955cd7ea107640bce8178c1ad34e7
alanzplus/EOPL
1.34.rkt
#lang eopl (require "bst.rkt") (define path (lambda (int tree) (aux int tree '()))) (define aux (lambda (int tree paths) (if (null? tree) '() (let ((val (val-of-node tree))) (cond ((> int val) (aux int (rtree tree) (append paths (list 'right)))) ((< int val) (aux int (ltree tree) (append paths (list 'left)))) (else paths)))))) (provide path)
null
https://raw.githubusercontent.com/alanzplus/EOPL/d7b06392d26d93df851d0ca66d9edc681a06693c/EOPL/ch1/1.34.rkt
racket
#lang eopl (require "bst.rkt") (define path (lambda (int tree) (aux int tree '()))) (define aux (lambda (int tree paths) (if (null? tree) '() (let ((val (val-of-node tree))) (cond ((> int val) (aux int (rtree tree) (append paths (list 'right)))) ((< int val) (aux int (ltree tree) (append paths (list 'left)))) (else paths)))))) (provide path)
69252f88f6ba7af3e5dd70d70e75765b9981063fe6a08a93cbd1861fa604ec33
esuomi/git-revisions
core_test.clj
(ns git-revisions.core-test (:require [clojure.java.shell :as sh] [clojure.test :refer :all] [git-revisions.core :as core])) (defn ^:private static-sh [commands] (fn [& args] (if-let [res (get commands args)] {:exit 0 :out res} {:exit -1 :err (str "unhandled command '" args "'")}))) (deftest built-in-semver-pattern (let [head-ref "985eb9ee629175cb334472d36aa9536d90789a71" ; clojure.java.shell/sh prepends ' to all rows in multi-row output, this is a bit weird but alas previous-tag "'85827e8fbf41507c23c2b052c604884909995863 (tag: v1.0.0)\n" current-branch "master" commands {core/gitcmd-current-commit head-ref core/gitcmd-tree-metadata "v1.0.0-8-g985eb9ee-dirty" core/gitcmd-current-branch current-branch core/gitcmd-previous-tag previous-tag core/gitcmd-commits "999"}] (testing "happy case" (with-redefs [sh/sh (static-sh commands)] (let [res (core/git-context (get-in core/predefined-formats [:semver :tag-pattern]))] ; current commit (is (= [false head-ref] ((juxt :unversioned? :ref) res))) ; tree metadata (is (= [8 true "985eb9ee" true] ((juxt :ahead :ahead? :ref-short :dirty?) res))) ; current branch (is (= current-branch (:branch res))) ; previous matching tag (is (= [false "85827e8fbf41507c23c2b052c604884909995863" "v1.0.0"] ((juxt :untagged? :tag-ref :tag) res))) ; commit count (is (= 999 (:commits res))) ))) (testing "untagged repository" (with-redefs [sh/sh (static-sh (assoc commands core/gitcmd-previous-tag ""))] (let [res (core/git-context (get-in core/predefined-formats [:semver :tag-pattern]))] (is (= true (:untagged? res))))))))
null
https://raw.githubusercontent.com/esuomi/git-revisions/b529ab43f0b1efee6db719927e1e461627ff6417/test/git_revisions/core_test.clj
clojure
clojure.java.shell/sh prepends ' to all rows in multi-row output, this is a bit weird but alas current commit tree metadata current branch previous matching tag commit count
(ns git-revisions.core-test (:require [clojure.java.shell :as sh] [clojure.test :refer :all] [git-revisions.core :as core])) (defn ^:private static-sh [commands] (fn [& args] (if-let [res (get commands args)] {:exit 0 :out res} {:exit -1 :err (str "unhandled command '" args "'")}))) (deftest built-in-semver-pattern (let [head-ref "985eb9ee629175cb334472d36aa9536d90789a71" previous-tag "'85827e8fbf41507c23c2b052c604884909995863 (tag: v1.0.0)\n" current-branch "master" commands {core/gitcmd-current-commit head-ref core/gitcmd-tree-metadata "v1.0.0-8-g985eb9ee-dirty" core/gitcmd-current-branch current-branch core/gitcmd-previous-tag previous-tag core/gitcmd-commits "999"}] (testing "happy case" (with-redefs [sh/sh (static-sh commands)] (let [res (core/git-context (get-in core/predefined-formats [:semver :tag-pattern]))] (is (= [false head-ref] ((juxt :unversioned? :ref) res))) (is (= [8 true "985eb9ee" true] ((juxt :ahead :ahead? :ref-short :dirty?) res))) (is (= current-branch (:branch res))) (is (= [false "85827e8fbf41507c23c2b052c604884909995863" "v1.0.0"] ((juxt :untagged? :tag-ref :tag) res))) (is (= 999 (:commits res))) ))) (testing "untagged repository" (with-redefs [sh/sh (static-sh (assoc commands core/gitcmd-previous-tag ""))] (let [res (core/git-context (get-in core/predefined-formats [:semver :tag-pattern]))] (is (= true (:untagged? res))))))))
8a90a44153502239061ff03975a600f4f37c1382e78d6db467b86b4541648eaf
maravillas/lein-js
closure_test.clj
(ns closure-test (:use [clojure.test] [clojure.contrib reflect]) (:use [lein-js.closure] :reload-all) (:import [com.google.javascript.jscomp CompilerOptions])) (defn- option-field [instance field] (get-field CompilerOptions field instance)) (deftest test-default-compiler-options (let [o (make-compiler-options default-options "output")] (is (= (option-field o "prettyPrint") (:pretty-print default-options))) (is (= (option-field o "printInputDelimiter") (:print-input-delimiter default-options))) (is (= (option-field o "closurePass") (:process-closure-primitives default-options))) (is (= (option-field o "manageClosureDependencies") (:manage-closure-deps default-options))) (is (= (option-field o "summaryDetailLevel") ((:summary-detail default-options) summary-details))) (is (= (type (option-field o "codingConvention")) ((:coding-convention default-options) coding-conventions)))))
null
https://raw.githubusercontent.com/maravillas/lein-js/3df63d80ebed8813ac67bdf554d560d031611290/test/closure_test.clj
clojure
(ns closure-test (:use [clojure.test] [clojure.contrib reflect]) (:use [lein-js.closure] :reload-all) (:import [com.google.javascript.jscomp CompilerOptions])) (defn- option-field [instance field] (get-field CompilerOptions field instance)) (deftest test-default-compiler-options (let [o (make-compiler-options default-options "output")] (is (= (option-field o "prettyPrint") (:pretty-print default-options))) (is (= (option-field o "printInputDelimiter") (:print-input-delimiter default-options))) (is (= (option-field o "closurePass") (:process-closure-primitives default-options))) (is (= (option-field o "manageClosureDependencies") (:manage-closure-deps default-options))) (is (= (option-field o "summaryDetailLevel") ((:summary-detail default-options) summary-details))) (is (= (type (option-field o "codingConvention")) ((:coding-convention default-options) coding-conventions)))))
013ea3905662554621138e092f668253c95b98c38f2fbd82585291519abe9a0e
rescript-association/genType
predef.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Predefined type constructors (with special typing rules in typecore) *) open Types val type_int: type_expr val type_char: type_expr val type_string: type_expr val type_bytes: type_expr val type_float: type_expr val type_bool: type_expr val type_unit: type_expr val type_exn: type_expr val type_array: type_expr -> type_expr val type_list: type_expr -> type_expr val type_option: type_expr -> type_expr val type_int64: type_expr val type_lazy_t: type_expr -> type_expr val type_extension_constructor:type_expr val type_floatarray:type_expr val path_int: Path.t val path_char: Path.t val path_string: Path.t val path_bytes: Path.t val path_float: Path.t val path_bool: Path.t val path_unit: Path.t val path_exn: Path.t val path_array: Path.t val path_list: Path.t val path_option: Path.t val path_int64: Path.t val path_lazy_t: Path.t val path_extension_constructor: Path.t val path_floatarray: Path.t val path_match_failure: Path.t val path_assert_failure : Path.t val path_undefined_recursive_module : Path.t To build the initial environment . Since there is a nasty mutual recursion between predef and env , we break it by parameterizing over , Env.add_type and Env.add_extension . recursion between predef and env, we break it by parameterizing over Env.t, Env.add_type and Env.add_extension. *) val build_initial_env: (Ident.t -> type_declaration -> 'a -> 'a) -> (Ident.t -> extension_constructor -> 'a -> 'a) -> 'a -> 'a (* To initialize linker tables *) val builtin_values: (string * Ident.t) list val builtin_idents: (string * Ident.t) list * All predefined exceptions , exposed as [ Ident.t ] for flambda ( for building value approximations ) . The [ Ident.t ] for division by zero is also exported explicitly so flambda can generate code to raise it . building value approximations). The [Ident.t] for division by zero is also exported explicitly so flambda can generate code to raise it. *) val ident_division_by_zero: Ident.t val all_predef_exns : Ident.t list type test = | For_sure_yes | For_sure_no | NA val type_is_builtin_path_but_option : Path.t -> test
null
https://raw.githubusercontent.com/rescript-association/genType/c44251e969fb10d27a38d2bdeff6a5f4d778594f/src/compiler-libs-406/predef.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Predefined type constructors (with special typing rules in typecore) To initialize linker tables
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Types val type_int: type_expr val type_char: type_expr val type_string: type_expr val type_bytes: type_expr val type_float: type_expr val type_bool: type_expr val type_unit: type_expr val type_exn: type_expr val type_array: type_expr -> type_expr val type_list: type_expr -> type_expr val type_option: type_expr -> type_expr val type_int64: type_expr val type_lazy_t: type_expr -> type_expr val type_extension_constructor:type_expr val type_floatarray:type_expr val path_int: Path.t val path_char: Path.t val path_string: Path.t val path_bytes: Path.t val path_float: Path.t val path_bool: Path.t val path_unit: Path.t val path_exn: Path.t val path_array: Path.t val path_list: Path.t val path_option: Path.t val path_int64: Path.t val path_lazy_t: Path.t val path_extension_constructor: Path.t val path_floatarray: Path.t val path_match_failure: Path.t val path_assert_failure : Path.t val path_undefined_recursive_module : Path.t To build the initial environment . Since there is a nasty mutual recursion between predef and env , we break it by parameterizing over , Env.add_type and Env.add_extension . recursion between predef and env, we break it by parameterizing over Env.t, Env.add_type and Env.add_extension. *) val build_initial_env: (Ident.t -> type_declaration -> 'a -> 'a) -> (Ident.t -> extension_constructor -> 'a -> 'a) -> 'a -> 'a val builtin_values: (string * Ident.t) list val builtin_idents: (string * Ident.t) list * All predefined exceptions , exposed as [ Ident.t ] for flambda ( for building value approximations ) . The [ Ident.t ] for division by zero is also exported explicitly so flambda can generate code to raise it . building value approximations). The [Ident.t] for division by zero is also exported explicitly so flambda can generate code to raise it. *) val ident_division_by_zero: Ident.t val all_predef_exns : Ident.t list type test = | For_sure_yes | For_sure_no | NA val type_is_builtin_path_but_option : Path.t -> test
1f33a23c976177f83618f4b2233a34719cbf8b85a331eb065467aed93e3f5879
spurious/sagittarius-scheme-mirror
cpstak.scm
CPSTAK -- A continuation - passing version of the TAK benchmark . A good test of first class procedures and tail recursion . (define (cpstak x y z) (define (tak x y z k) (if (not (< y x)) (k z) (tak (- x 1) y z (lambda (v1) (tak (- y 1) z x (lambda (v2) (tak (- z 1) x y (lambda (v3) (tak v1 v2 v3 k))))))))) (tak x y z (lambda (a) a))) (define (main . args) (run-benchmark "cpstak" cpstak-iters (lambda (result) (equal? result 7)) (lambda (x y z) (lambda () (cpstak x y z))) 18 12 6))
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/bench/gambit-benchmarks/cpstak.scm
scheme
CPSTAK -- A continuation - passing version of the TAK benchmark . A good test of first class procedures and tail recursion . (define (cpstak x y z) (define (tak x y z k) (if (not (< y x)) (k z) (tak (- x 1) y z (lambda (v1) (tak (- y 1) z x (lambda (v2) (tak (- z 1) x y (lambda (v3) (tak v1 v2 v3 k))))))))) (tak x y z (lambda (a) a))) (define (main . args) (run-benchmark "cpstak" cpstak-iters (lambda (result) (equal? result 7)) (lambda (x y z) (lambda () (cpstak x y z))) 18 12 6))
0130f669b3f0e44c3b60d7d7e951700e1ec5ccbe9f52ba4d099069590472d6ff
tek/chiasma
Measure.hs
module Chiasma.Ui.Data.Measure where import Control.Lens (makeClassy) import Prettyprinter (Pretty (..), (<+>)) import Chiasma.Data.Axis (Axis) import Chiasma.Data.TmuxId (PaneId (..)) import Chiasma.Ui.Data.Tree (NNode, NTree) data MPane = MPane { _paneId :: PaneId, _mainPosition :: Int, _offPosition :: Int } deriving stock (Eq, Show) makeClassy ''MPane data MLayout = MLayout { _reference :: PaneId, _lMainPosition :: Int, _lOffPosition :: Int, _axis :: Axis } deriving stock (Eq, Show) makeClassy ''MLayout data Measured a = Measured { _size :: Int, _view :: a } deriving stock (Eq, Show) makeClassy ''Measured type MeasureTree = NTree (Measured MLayout) (Measured MPane) type MeasureTreeSub = NNode (Measured MLayout) (Measured MPane) instance Pretty MLayout where pretty (MLayout (PaneId refId) mainPos offPos axis') = "l –" <+> "ref:" <+> pretty refId <+> "pos:" <+> pretty mainPos <+> "(" <> pretty offPos <> ")" <+> pretty axis' instance Pretty MPane where pretty (MPane (PaneId paneId') mainPos offPos) = "p –" <+> pretty paneId' <+> "pos:" <+> pretty mainPos <+> "(" <> pretty offPos <> ")" instance Pretty a => Pretty (Measured a) where pretty (Measured size' a) = pretty a <+> "size:" <+> pretty size'
null
https://raw.githubusercontent.com/tek/chiasma/51751e19a416a9afe12f7797df8a67990b266240/packages/chiasma/lib/Chiasma/Ui/Data/Measure.hs
haskell
module Chiasma.Ui.Data.Measure where import Control.Lens (makeClassy) import Prettyprinter (Pretty (..), (<+>)) import Chiasma.Data.Axis (Axis) import Chiasma.Data.TmuxId (PaneId (..)) import Chiasma.Ui.Data.Tree (NNode, NTree) data MPane = MPane { _paneId :: PaneId, _mainPosition :: Int, _offPosition :: Int } deriving stock (Eq, Show) makeClassy ''MPane data MLayout = MLayout { _reference :: PaneId, _lMainPosition :: Int, _lOffPosition :: Int, _axis :: Axis } deriving stock (Eq, Show) makeClassy ''MLayout data Measured a = Measured { _size :: Int, _view :: a } deriving stock (Eq, Show) makeClassy ''Measured type MeasureTree = NTree (Measured MLayout) (Measured MPane) type MeasureTreeSub = NNode (Measured MLayout) (Measured MPane) instance Pretty MLayout where pretty (MLayout (PaneId refId) mainPos offPos axis') = "l –" <+> "ref:" <+> pretty refId <+> "pos:" <+> pretty mainPos <+> "(" <> pretty offPos <> ")" <+> pretty axis' instance Pretty MPane where pretty (MPane (PaneId paneId') mainPos offPos) = "p –" <+> pretty paneId' <+> "pos:" <+> pretty mainPos <+> "(" <> pretty offPos <> ")" instance Pretty a => Pretty (Measured a) where pretty (Measured size' a) = pretty a <+> "size:" <+> pretty size'
578c47428ba7424ec2a11a8b41c932c373cb7e3c87933fe40784439f169d7b52
simmone/racket-simple-qr
finder-pattern-center-points.rkt
#lang racket (require "../../../../share/func.rkt") (require "../../../../share/draw/draw.rkt") (provide (contract-out [write-report-finder-pattern-center-points (-> natural? list? natural? list? path-string? void?)] )) (define (write-report-finder-pattern-center-points module_width center_points bits_width points_list express_path) (let* ([scrbl_dir (build-path express_path "finder-pattern-center-points")] [scrbl_file (build-path scrbl_dir "finder-pattern-center-points.scrbl")] [img_file (build-path scrbl_dir "finder-pattern-center-points.img")] [points_map (points->points_map points_list)] [base1_center_points (points->base1_points center_points)]) (make-directory* scrbl_dir) (with-output-to-file scrbl_file (lambda () (printf "#lang scribble/base\n\n") (printf "@title{Guess Finder Pattern and Module Width}\n\n") (printf "locate three finder pattern, and probe the module width.\n") (printf "@section{Module Width: ~apx}\n" module_width) (printf "@section{Center Points}\n") (printf "top-left(red): ~a, top-right(yellow): ~a, botterm left(blue): ~a\n" (first center_points) (second center_points) (third center_points)) (printf "@section{Tag Center Points}\n") (let ([color_map (make-hash)]) (hash-set! color_map (first base1_center_points) "red") (hash-set! color_map (second base1_center_points) "yellow") (hash-set! color_map (third base1_center_points) "blue") (draw bits_width 2 points_map color_map img_file)) (printf "@image{finder-pattern-center-points/finder-pattern-center-points.img}") ))))
null
https://raw.githubusercontent.com/simmone/racket-simple-qr/904f1491bc521badeafeabd0d7d7e97e3d0ee958/simple-qr/read/lib/express/finder-pattern-center-points/finder-pattern-center-points.rkt
racket
#lang racket (require "../../../../share/func.rkt") (require "../../../../share/draw/draw.rkt") (provide (contract-out [write-report-finder-pattern-center-points (-> natural? list? natural? list? path-string? void?)] )) (define (write-report-finder-pattern-center-points module_width center_points bits_width points_list express_path) (let* ([scrbl_dir (build-path express_path "finder-pattern-center-points")] [scrbl_file (build-path scrbl_dir "finder-pattern-center-points.scrbl")] [img_file (build-path scrbl_dir "finder-pattern-center-points.img")] [points_map (points->points_map points_list)] [base1_center_points (points->base1_points center_points)]) (make-directory* scrbl_dir) (with-output-to-file scrbl_file (lambda () (printf "#lang scribble/base\n\n") (printf "@title{Guess Finder Pattern and Module Width}\n\n") (printf "locate three finder pattern, and probe the module width.\n") (printf "@section{Module Width: ~apx}\n" module_width) (printf "@section{Center Points}\n") (printf "top-left(red): ~a, top-right(yellow): ~a, botterm left(blue): ~a\n" (first center_points) (second center_points) (third center_points)) (printf "@section{Tag Center Points}\n") (let ([color_map (make-hash)]) (hash-set! color_map (first base1_center_points) "red") (hash-set! color_map (second base1_center_points) "yellow") (hash-set! color_map (third base1_center_points) "blue") (draw bits_width 2 points_map color_map img_file)) (printf "@image{finder-pattern-center-points/finder-pattern-center-points.img}") ))))
45f403b6245e74025f539b3748928bcb0a121c69a92578be277209b9720620ab
fission-codes/fission
Initializer.hs
module Fission.Web.Server.App.Domain.Initializer (module Fission.Web.Server.App.Domain.Initializer.Class) where import Fission.Web.Server.App.Domain.Initializer.Class
null
https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-web-server/library/Fission/Web/Server/App/Domain/Initializer.hs
haskell
module Fission.Web.Server.App.Domain.Initializer (module Fission.Web.Server.App.Domain.Initializer.Class) where import Fission.Web.Server.App.Domain.Initializer.Class
d39f137cdbdb580c12c2a0034875718860bb11a84e140f962538c26f13f89b58
borodust/alien-works
renderable.lisp
(cl:in-package :%alien-works.filament) (defun renderable-manager (engine) (%filament:get-renderable-manager '(claw-utils:claw-pointer %filament::engine) engine)) ;;; ;;; RENDERABLE ;;; (u:define-enumval-extractor renderable-primitive-type-enum %filament:renderable-manager+primitive-type) (warp-intricate-builder-option renderable-builder :index-bound-geometry %filament:geometry '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '%filament:renderable-manager+primitive-type '(claw-utils:claw-pointer %filament:vertex-buffer) '(claw-utils:claw-pointer %filament:index-buffer) '%filament:size-t '%filament:size-t '%filament:size-t '%filament:size-t) (warp-intricate-builder-option renderable-builder :count-bound-geometry %filament:geometry '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '%filament:renderable-manager+primitive-type '(claw-utils:claw-pointer %filament:vertex-buffer) '(claw-utils:claw-pointer %filament:index-buffer) '%filament:size-t '%filament:size-t) (warp-intricate-builder-option renderable-builder :geometry %filament:geometry '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '%filament:renderable-manager+primitive-type '(claw-utils:claw-pointer %filament:vertex-buffer) '(claw-utils:claw-pointer %filament:index-buffer)) (warp-intricate-builder-option renderable-builder :material %filament:material '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '(claw-utils:claw-pointer %filament:material-instance)) (warp-intricate-builder-option renderable-builder :bounding-box %filament:bounding-box '(claw-utils:claw-pointer %filament:renderable-manager+builder) '(claw-utils:claw-pointer %filament:box)) (warp-intricate-builder-option renderable-builder :layer-mask %filament:layer-mask '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:uint8-t '%filament:uint8-t) (warp-intricate-builder-option renderable-builder :priority %filament:priority '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:uint8-t) (warp-intricate-builder-option renderable-builder :culling %filament:culling '(claw-utils:claw-pointer %filament:renderable-manager+builder) ':bool) (warp-intricate-builder-option renderable-builder :cast-shadows %filament:cast-shadows '(claw-utils:claw-pointer %filament:renderable-manager+builder) ':bool) (warp-intricate-builder-option renderable-builder :receive-shadows %filament:receive-shadows '(claw-utils:claw-pointer %filament:renderable-manager+builder) ':bool) (warp-intricate-builder-option renderable-builder :screen-space-contact-shadows %filament:screen-space-contact-shadows '(claw-utils:claw-pointer %filament:renderable-manager+builder) ':bool) (warp-intricate-builder-option renderable-builder :transform-skinning %filament:skinning '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '(claw-utils:claw-pointer %filament:math+mat4f)) (warp-intricate-builder-option renderable-builder :bone-skinning %filament:skinning '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '(claw-utils:claw-pointer %filament:renderable-manager+bone)) (warp-intricate-builder-option renderable-builder :skinning %filament:skinning '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t) (warp-intricate-builder-option renderable-builder :blend-order %filament:blend-order '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '%filament:uint16-t) (defmacro with-renderable-builder ((name (&optional count) &body steps) &body body) (flet ((ctor-expander () `(%filament:renderable-manager+builder '%filament:size-t ,count)) (build-expander (builder) `(%filament:build '(claw-utils:claw-pointer %filament:renderable-manager+builder) ,builder '(claw-utils:claw-pointer %filament:engine) !::engine '(claw-utils:claw-pointer %filament:utils+entity) !::entity))) (explode-builder name 'renderable-builder #'ctor-expander #'build-expander '(!::engine !::entity) steps body))) (defmacro with-renderable-instance ((instance entity) renderable-manager &body body) `(iffi:with-intricate-instance (,instance %filament::renderable-manager+instance) (%filament:get-instance :const '(claw-utils:claw-pointer %filament::renderable-manager+instance) ,instance '(claw-utils:claw-pointer %filament::renderable-manager) ,renderable-manager '(claw-utils:claw-pointer %filament::utils+entity) ,entity) ,@body)) (defun renderable-material-instance (renderable-manager instance layer) (%filament:get-material-instance-at :const '(claw-utils:claw-pointer %filament::renderable-manager) renderable-manager '(claw-utils:claw-pointer %filament::renderable-manager+instance) instance '%filament::size-t layer)) (defun (setf renderable-material-instance) (material-instance renderable-manager instance layer) (%filament:set-material-instance-at '(claw-utils:claw-pointer %filament::renderable-manager) renderable-manager '(claw-utils:claw-pointer %filament::renderable-manager+instance) instance '%filament::size-t layer '(claw-utils:claw-pointer %filament::material-instance) material-instance) material-instance)
null
https://raw.githubusercontent.com/borodust/alien-works/30ece406a7416a7b4690165dde350cd2677335be/src/graphics/filament/renderable.lisp
lisp
RENDERABLE
(cl:in-package :%alien-works.filament) (defun renderable-manager (engine) (%filament:get-renderable-manager '(claw-utils:claw-pointer %filament::engine) engine)) (u:define-enumval-extractor renderable-primitive-type-enum %filament:renderable-manager+primitive-type) (warp-intricate-builder-option renderable-builder :index-bound-geometry %filament:geometry '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '%filament:renderable-manager+primitive-type '(claw-utils:claw-pointer %filament:vertex-buffer) '(claw-utils:claw-pointer %filament:index-buffer) '%filament:size-t '%filament:size-t '%filament:size-t '%filament:size-t) (warp-intricate-builder-option renderable-builder :count-bound-geometry %filament:geometry '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '%filament:renderable-manager+primitive-type '(claw-utils:claw-pointer %filament:vertex-buffer) '(claw-utils:claw-pointer %filament:index-buffer) '%filament:size-t '%filament:size-t) (warp-intricate-builder-option renderable-builder :geometry %filament:geometry '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '%filament:renderable-manager+primitive-type '(claw-utils:claw-pointer %filament:vertex-buffer) '(claw-utils:claw-pointer %filament:index-buffer)) (warp-intricate-builder-option renderable-builder :material %filament:material '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '(claw-utils:claw-pointer %filament:material-instance)) (warp-intricate-builder-option renderable-builder :bounding-box %filament:bounding-box '(claw-utils:claw-pointer %filament:renderable-manager+builder) '(claw-utils:claw-pointer %filament:box)) (warp-intricate-builder-option renderable-builder :layer-mask %filament:layer-mask '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:uint8-t '%filament:uint8-t) (warp-intricate-builder-option renderable-builder :priority %filament:priority '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:uint8-t) (warp-intricate-builder-option renderable-builder :culling %filament:culling '(claw-utils:claw-pointer %filament:renderable-manager+builder) ':bool) (warp-intricate-builder-option renderable-builder :cast-shadows %filament:cast-shadows '(claw-utils:claw-pointer %filament:renderable-manager+builder) ':bool) (warp-intricate-builder-option renderable-builder :receive-shadows %filament:receive-shadows '(claw-utils:claw-pointer %filament:renderable-manager+builder) ':bool) (warp-intricate-builder-option renderable-builder :screen-space-contact-shadows %filament:screen-space-contact-shadows '(claw-utils:claw-pointer %filament:renderable-manager+builder) ':bool) (warp-intricate-builder-option renderable-builder :transform-skinning %filament:skinning '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '(claw-utils:claw-pointer %filament:math+mat4f)) (warp-intricate-builder-option renderable-builder :bone-skinning %filament:skinning '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '(claw-utils:claw-pointer %filament:renderable-manager+bone)) (warp-intricate-builder-option renderable-builder :skinning %filament:skinning '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t) (warp-intricate-builder-option renderable-builder :blend-order %filament:blend-order '(claw-utils:claw-pointer %filament:renderable-manager+builder) '%filament:size-t '%filament:uint16-t) (defmacro with-renderable-builder ((name (&optional count) &body steps) &body body) (flet ((ctor-expander () `(%filament:renderable-manager+builder '%filament:size-t ,count)) (build-expander (builder) `(%filament:build '(claw-utils:claw-pointer %filament:renderable-manager+builder) ,builder '(claw-utils:claw-pointer %filament:engine) !::engine '(claw-utils:claw-pointer %filament:utils+entity) !::entity))) (explode-builder name 'renderable-builder #'ctor-expander #'build-expander '(!::engine !::entity) steps body))) (defmacro with-renderable-instance ((instance entity) renderable-manager &body body) `(iffi:with-intricate-instance (,instance %filament::renderable-manager+instance) (%filament:get-instance :const '(claw-utils:claw-pointer %filament::renderable-manager+instance) ,instance '(claw-utils:claw-pointer %filament::renderable-manager) ,renderable-manager '(claw-utils:claw-pointer %filament::utils+entity) ,entity) ,@body)) (defun renderable-material-instance (renderable-manager instance layer) (%filament:get-material-instance-at :const '(claw-utils:claw-pointer %filament::renderable-manager) renderable-manager '(claw-utils:claw-pointer %filament::renderable-manager+instance) instance '%filament::size-t layer)) (defun (setf renderable-material-instance) (material-instance renderable-manager instance layer) (%filament:set-material-instance-at '(claw-utils:claw-pointer %filament::renderable-manager) renderable-manager '(claw-utils:claw-pointer %filament::renderable-manager+instance) instance '%filament::size-t layer '(claw-utils:claw-pointer %filament::material-instance) material-instance) material-instance)
6c9a93ddaa5c2e338af5dee2a0df3a8d9c624f187665d6cd6c6149df5ee2da9b
avsm/platform
xml_iter.mli
TyXML * * Copyright ( C ) 2004 < > * Copyright ( C ) 2011 , * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 51 Franklin Street , Suite 500 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2004 Thorsten Ohl <> * Copyright (C) 2011 Pierre Chambart, Grégoire Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02111-1307, USA. *) (** Basic iterators over XML tree (functorial interface). *) module Make(Xml : Xml_sigs.Iterable) : sig open Xml val amap : (ename -> attrib list -> attrib list) -> elt -> elt (** Recursively edit attributes for the element and all its children. *) val amap1 : (ename -> attrib list -> attrib list) -> elt -> elt * Edit attributes only for one element . (** The following can safely be exported by higher level libraries, because removing an attribute from a element is always legal. *) val rm_attrib : (aname -> bool) -> attrib list -> attrib list val rm_attrib_from_list : (aname -> bool) -> (string -> bool) -> attrib list -> attrib list val map_int_attrib : (aname -> bool) -> (int -> int) -> attrib list -> attrib list val map_float_attrib : (aname -> bool) -> (float -> float) -> attrib list -> attrib list val map_string_attrib : (aname -> bool) -> (string -> string) -> attrib list -> attrib list val map_string_attrib_in_list : (aname -> bool) -> (string -> string) -> attrib list -> attrib list (** Exporting the following by higher level libraries would drive a hole through a type system, because they allow to add {e any} attribute to {e any} element. *) val add_int_attrib : aname -> int -> attrib list -> attrib list val add_float_attrib : aname -> float -> attrib list -> attrib list val add_string_attrib : aname -> string -> attrib list -> attrib list val add_comma_sep_attrib : aname -> string -> attrib list -> attrib list val add_space_sep_attrib : aname -> string -> attrib list -> attrib list val fold : (unit -> 'a) -> (string -> 'a) -> (string -> 'a) -> (string -> 'a) -> (string -> 'a) -> (ename -> attrib list -> 'a) -> (ename -> attrib list -> 'a list -> 'a) -> elt -> 'a val all_entities : elt -> string list val translate : (ename -> attrib list -> elt) -> (ename -> attrib list -> elt list -> elt) -> ('state -> ename -> attrib list -> elt list) -> ('state -> ename -> attrib list -> elt list -> elt list) -> (ename -> attrib list -> 'state -> 'state) -> 'state -> elt -> elt end
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/tyxml.4.3.0/lib/xml_iter.mli
ocaml
* Basic iterators over XML tree (functorial interface). * Recursively edit attributes for the element and all its children. * The following can safely be exported by higher level libraries, because removing an attribute from a element is always legal. * Exporting the following by higher level libraries would drive a hole through a type system, because they allow to add {e any} attribute to {e any} element.
TyXML * * Copyright ( C ) 2004 < > * Copyright ( C ) 2011 , * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 51 Franklin Street , Suite 500 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2004 Thorsten Ohl <> * Copyright (C) 2011 Pierre Chambart, Grégoire Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02111-1307, USA. *) module Make(Xml : Xml_sigs.Iterable) : sig open Xml val amap : (ename -> attrib list -> attrib list) -> elt -> elt val amap1 : (ename -> attrib list -> attrib list) -> elt -> elt * Edit attributes only for one element . val rm_attrib : (aname -> bool) -> attrib list -> attrib list val rm_attrib_from_list : (aname -> bool) -> (string -> bool) -> attrib list -> attrib list val map_int_attrib : (aname -> bool) -> (int -> int) -> attrib list -> attrib list val map_float_attrib : (aname -> bool) -> (float -> float) -> attrib list -> attrib list val map_string_attrib : (aname -> bool) -> (string -> string) -> attrib list -> attrib list val map_string_attrib_in_list : (aname -> bool) -> (string -> string) -> attrib list -> attrib list val add_int_attrib : aname -> int -> attrib list -> attrib list val add_float_attrib : aname -> float -> attrib list -> attrib list val add_string_attrib : aname -> string -> attrib list -> attrib list val add_comma_sep_attrib : aname -> string -> attrib list -> attrib list val add_space_sep_attrib : aname -> string -> attrib list -> attrib list val fold : (unit -> 'a) -> (string -> 'a) -> (string -> 'a) -> (string -> 'a) -> (string -> 'a) -> (ename -> attrib list -> 'a) -> (ename -> attrib list -> 'a list -> 'a) -> elt -> 'a val all_entities : elt -> string list val translate : (ename -> attrib list -> elt) -> (ename -> attrib list -> elt list -> elt) -> ('state -> ename -> attrib list -> elt list) -> ('state -> ename -> attrib list -> elt list -> elt list) -> (ename -> attrib list -> 'state -> 'state) -> 'state -> elt -> elt end
bc793a5b869be86063a7fb1bf3e31e20fe28edbdce329dc7a5e86a10b291989b
sky-big/RabbitMQ
many_node_ha.erl
The contents of this file are subject to the Mozilla Public License %% Version 1.1 (the "License"); you may not use this file except in %% compliance with the License. You may obtain a copy of the License %% at / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and %% limitations under the License. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . %% -module(many_node_ha). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). -include("amqp_client.hrl"). -import(rabbit_test_util, [a2b/1]). -import(rabbit_misc, [pget/2]). kill_intermediate_with() -> fun (Cfg) -> rabbit_test_configs:ha_policy_all( rabbit_test_configs:cluster(Cfg, [a,b,c,d,e,f])) end. kill_intermediate([CfgA, CfgB, CfgC, CfgD, CfgE, CfgF]) -> Msgs = rabbit_test_configs:cover_work_factor(20000, CfgA), MasterChannel = pget(channel, CfgA), ConsumerChannel = pget(channel, CfgE), ProducerChannel = pget(channel, CfgF), Queue = <<"test">>, amqp_channel:call(MasterChannel, #'queue.declare'{queue = Queue, auto_delete = false}), %% TODO: this seems *highly* timing dependant - the assumption being %% that the kill will work quickly enough that there will still be %% some messages in-flight that we *must* receive despite the intervening %% node deaths. It would be nice if we could find a means to do this %% in a way that is not actually timing dependent. %% Worse still, it assumes that killing the master will cause a %% failover to Slave1, and so on. Nope. ConsumerPid = rabbit_ha_test_consumer:create(ConsumerChannel, Queue, self(), false, Msgs), ProducerPid = rabbit_ha_test_producer:create(ProducerChannel, Queue, self(), false, Msgs), create a killer for the master and the first 3 slaves [rabbit_test_util:kill_after(Time, Cfg, sigkill) || {Cfg, Time} <- [{CfgA, 50}, {CfgB, 50}, {CfgC, 100}, {CfgD, 100}]], verify that the consumer got all msgs , or die , or time out rabbit_ha_test_producer:await_response(ProducerPid), rabbit_ha_test_consumer:await_response(ConsumerPid), ok.
null
https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/plugins-src/rabbitmq-test/test/src/many_node_ha.erl
erlang
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. TODO: this seems *highly* timing dependant - the assumption being that the kill will work quickly enough that there will still be some messages in-flight that we *must* receive despite the intervening node deaths. It would be nice if we could find a means to do this in a way that is not actually timing dependent. Worse still, it assumes that killing the master will cause a failover to Slave1, and so on. Nope.
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . -module(many_node_ha). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). -include("amqp_client.hrl"). -import(rabbit_test_util, [a2b/1]). -import(rabbit_misc, [pget/2]). kill_intermediate_with() -> fun (Cfg) -> rabbit_test_configs:ha_policy_all( rabbit_test_configs:cluster(Cfg, [a,b,c,d,e,f])) end. kill_intermediate([CfgA, CfgB, CfgC, CfgD, CfgE, CfgF]) -> Msgs = rabbit_test_configs:cover_work_factor(20000, CfgA), MasterChannel = pget(channel, CfgA), ConsumerChannel = pget(channel, CfgE), ProducerChannel = pget(channel, CfgF), Queue = <<"test">>, amqp_channel:call(MasterChannel, #'queue.declare'{queue = Queue, auto_delete = false}), ConsumerPid = rabbit_ha_test_consumer:create(ConsumerChannel, Queue, self(), false, Msgs), ProducerPid = rabbit_ha_test_producer:create(ProducerChannel, Queue, self(), false, Msgs), create a killer for the master and the first 3 slaves [rabbit_test_util:kill_after(Time, Cfg, sigkill) || {Cfg, Time} <- [{CfgA, 50}, {CfgB, 50}, {CfgC, 100}, {CfgD, 100}]], verify that the consumer got all msgs , or die , or time out rabbit_ha_test_producer:await_response(ProducerPid), rabbit_ha_test_consumer:await_response(ConsumerPid), ok.
bc887833f3ddaf7af9e119f636d30b4f5c46532ec1f85f3d8d5d66424dfce0a7
scalaris-team/scalaris
cbf.erl
2016 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. @author < > @author < > %% @doc Counting Bloom Filter implementation %% @end , %% <em>Set Reconciliation via Counting Bloom Filters</em> 2013 IEEE Transactions on Knowledge and Data Engineering 25.10 %% @version $Id$ -module(cbf). -author(''). -author(''). -include("record_helpers.hrl"). -include("scalaris.hrl"). -define(REP_HFS, hfs_plain). % hash function set implementation to use -export([new_fpr/2, new_fpr/3, new_bpi/3, new_bin/3, new/2, add/2, add_list/2, remove/2, remove_list/2, is_element/2, item_count/1, to_bloom/1]). -export([equals/2, join/2, minus/2, print/1]). % for tests: -export([get_property/2]). -export([p_add_list/4]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Types %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -record(cbf, { filter = ?required(cbf, filter) :: array:array(integer()), HashFunctionSet items_count = 0 :: non_neg_integer() %number of inserted items }). -opaque cbf() :: #cbf{}. -type key() :: any(). -export_type([cbf/0, key/0]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% API %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% @doc Creates a new counting bloom filter with the default (optimal) hash %% function set based on the given false positive rate. -spec new_fpr(MaxItems::non_neg_integer(), FPR::float()) -> cbf(). new_fpr(MaxItems, FPR) -> {K, Size} = bloom:calc_HF_num_Size_opt(MaxItems, FPR), new(Size, ?REP_HFS:new(K)). %% @doc Creates a new counting bloom filter with the given hash function set %% based on the given false positive rate. -spec new_fpr(MaxItems::non_neg_integer(), FPR::float(), ?REP_HFS:hfs() | non_neg_integer()) -> cbf(). new_fpr(MaxItems, FPR, Hfs) -> Size = bloom:calc_least_size(MaxItems, FPR, ?REP_HFS:size(Hfs)), new(Size, Hfs). %% @doc Creates a new counting bloom filter with the given hash function set and %% a fixed number of positions (bits in standard bloom filters) per item. -spec new_bpi(MaxItems::non_neg_integer(), BitsPerItem::number(), ?REP_HFS:hfs() | non_neg_integer()) -> cbf(). new_bpi(MaxItems, BitPerItem, Hfs) -> new(util:ceil(BitPerItem * MaxItems), Hfs). %% @doc Creates a new counting bloom filter with the given binary, hash %% function set and item count. -spec new_bin(Filter::array:array(integer()), ?REP_HFS:hfs() | non_neg_integer(), ItemsCount::non_neg_integer()) -> cbf(). new_bin(Filter, HfCount, ItemsCount) when is_integer(HfCount) -> new_bin(Filter, ?REP_HFS:new(HfCount), ItemsCount); new_bin(Filter, Hfs, ItemsCount) -> #cbf{filter = Filter, hfs = Hfs, items_count = ItemsCount}. %% @doc Creates a new counting bloom filter. -spec new(BitSize::pos_integer(), ?REP_HFS:hfs() | non_neg_integer()) -> cbf(). new(BitSize, HfCount) when is_integer(HfCount) -> new(BitSize, ?REP_HFS:new(HfCount)); new(BitSize, Hfs) -> #cbf{filter = array:new(BitSize, {default,0}), hfs = Hfs, items_count = 0}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @doc Adds one item to the counting bloom filter . -spec add(cbf(), key()) -> cbf(). add(#cbf{hfs = Hfs, items_count = FilledCount, filter = Filter} = Bloom, Item) -> BFSize = array:size(Filter), Bloom#cbf{filter = p_add_list(Hfs, BFSize, Filter, [Item]), items_count = FilledCount + 1}. %% @doc Adds multiple items to the counting bloom filter. -spec add_list(cbf(), [key()]) -> cbf(). add_list(#cbf{hfs = Hfs, items_count = FilledCount, filter = Filter } = Bloom, Items) -> BFSize = array:size(Filter), ItemsL = length(Items), F = p_add_list(Hfs, BFSize, Filter, Items), Bloom#cbf{filter = F, items_count = FilledCount + ItemsL}. -compile({inline, [p_add_list/4, p_change_list_/6]}). %% @doc Helper to add items to the counting bloom filter. -spec p_add_list(Hfs::?REP_HFS:hfs(), BFSize::pos_integer(), BF1::array:array(integer()), Items::[key()]) -> BF2::array:array(integer()). p_add_list(_Hfs, _BFSize, BF, []) -> BF; p_add_list(Hfs, 1, BF, _Items = [_|_]) -> array:set(0, ?REP_HFS:size(Hfs), BF); p_add_list(Hfs, BFSize, BF, Items = [_|_]) -> Positions = lists:flatmap(fun(Item) -> ?REP_HFS:apply_val_rem(Hfs, Item, BFSize) end, Items), [Pos | Rest] = lists:sort(Positions), p_change_list_(Rest, Pos, [1 | lists:duplicate(Pos, 0)], BFSize, BF, fun erlang:'+'/2). @doc Helper increasing or decreasing counters by first accumulating all %% counters in a list and merging it with the old list. -spec p_change_list_(Positions::[non_neg_integer()], CurPos::non_neg_integer(), Counters::[non_neg_integer(),...], BFSize::non_neg_integer(), BF::array:array(integer()), ChangeFun::fun((non_neg_integer(), non_neg_integer()) -> integer())) -> BF2::array:array(integer()). p_change_list_([], CurPos, Counters, BFSize, BF, ChangeFun) -> Counters1 = lists:reverse(Counters, lists:duplicate(erlang:max(0, BFSize - CurPos - 1), 0)), Counters2 = lists:zipwith(ChangeFun, array:to_list(BF), Counters1), array:from_list(Counters2); p_change_list_([CurPos | Positions], CurPos, [CurCount | Counters], BFSize, BF, ChangeFun) -> p_change_list_(Positions, CurPos, [CurCount + 1 | Counters], BFSize, BF, ChangeFun); p_change_list_([NewPos | Positions], CurPos, Counters, BFSize, BF, ChangeFun) -> Counters1 = lists:duplicate(NewPos - CurPos - 1, 0) ++ Counters, p_change_list_(Positions, NewPos, [1 | Counters1], BFSize, BF, ChangeFun). @doc Removes one item from the counting bloom filter . %% (may introduce false negatives if removing an item not added previously) -spec remove(cbf(), key()) -> cbf(). remove(#cbf{hfs = Hfs, items_count = FilledCount, filter = Filter} = Bloom, Item) -> BFSize = array:size(Filter), Bloom#cbf{filter = p_remove_list(Hfs, BFSize, Filter, [Item]), items_count = FilledCount + 1}. %% @doc Removes multiple items from the counting bloom filter. %% (may introduce false negatives if removing an item not added previously) -spec remove_list(cbf(), [key()]) -> cbf(). remove_list(#cbf{hfs = Hfs, items_count = FilledCount, filter = Filter } = Bloom, Items) -> BFSize = array:size(Filter), ItemsL = length(Items), F = p_remove_list(Hfs, BFSize, Filter, Items), Bloom#cbf{filter = F, items_count = FilledCount + ItemsL}. -compile({inline, [p_remove_list/4]}). %% @doc Helper to remove items from the counting bloom filter. -spec p_remove_list(Hfs::?REP_HFS:hfs(), BFSize::pos_integer(), BF1::array:array(integer()), Items::[key()]) -> BF2::array:array(integer()). p_remove_list(_Hfs, _BFSize, BF, []) -> BF; p_remove_list(_Hfs, 1, BF, _Items = [_|_]) -> array:set(0, 0, BF); p_remove_list(Hfs, BFSize, BF, Items = [_|_]) -> Positions = lists:flatmap(fun(Item) -> ?REP_HFS:apply_val_rem(Hfs, Item, BFSize) end, Items), [Pos | Rest] = lists:sort(Positions), p_change_list_(Rest, Pos, [1 | lists:duplicate(Pos, 0)], BFSize, BF, fun erlang:'-'/2). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% @doc Returns true if the counting bloom filter contains this item. -spec is_element(cbf(), key()) -> boolean(). is_element(#cbf{items_count = 0}, _Item) -> false; is_element(#cbf{hfs = Hfs, filter = Filter}, Item) -> BFSize = array:size(Filter), Positions = ?REP_HFS:apply_val_rem(Hfs, Item, BFSize), check_counters(Filter, Positions). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% @doc Gets the number of items inserted into this counting bloom filter. -spec item_count(cbf()) -> non_neg_integer(). item_count(#cbf{items_count = ItemsCount}) -> ItemsCount. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @doc Joins two counting bloom filters so that the returned counting bloom %% filter represents their union. -spec join(cbf(), cbf()) -> cbf(). join(#cbf{items_count = 0, hfs = Hfs1} = _BF1, #cbf{hfs = Hfs2} = BF2) -> ?ASSERT(?REP_HFS:size(Hfs1) =:= ?REP_HFS:size(Hfs2)), ?ASSERT(get_property(BF2, size) =:= get_property(_BF1, size)), BF2; join(#cbf{hfs = Hfs1} = BF1, #cbf{items_count = 0, hfs = Hfs2} = _BF2) -> ?ASSERT(?REP_HFS:size(Hfs1) =:= ?REP_HFS:size(Hfs2)), ?ASSERT(get_property(BF1, size) =:= get_property(_BF2, size)), BF1; join(#cbf{items_count = Items1, filter = F1, hfs = Hfs}, #cbf{items_count = Items2, filter = F2}) -> Size = array:size(F1), ?ASSERT(Size =:= array:size(F2)), if Items1 > Items2 -> FSmall = F2, FBig = F1, ok; true -> FSmall = F1, FBig = F2, ok end, NewF = array:sparse_foldl(fun(I, X, Acc) -> array:set(I, array:get(I, Acc) + X, Acc) end, FBig, FSmall), #cbf{filter = NewF, hfs = Hfs, items_count = Items1 + Items2 %approximation }. %% @doc Subtracts counting bloom filter A from B so that the returned %% counting bloom filter that approximates the set difference (with false %% positives and false negatives!). -spec minus(A::cbf(), B::cbf()) -> cbf(). minus(#cbf{items_count = 0, hfs = Hfs1} = BF1, #cbf{hfs = Hfs2} = _BF2) -> ?ASSERT(?REP_HFS:size(Hfs1) =:= ?REP_HFS:size(Hfs2)), ?ASSERT(get_property(_BF2, size) =:= get_property(BF1, size)), BF1; minus(#cbf{hfs = Hfs1} = BF1, #cbf{items_count = 0, hfs = Hfs2} = _BF2) -> ?ASSERT(?REP_HFS:size(Hfs1) =:= ?REP_HFS:size(Hfs2)), ?ASSERT(get_property(BF1, size) =:= get_property(_BF2, size)), BF1; minus(#cbf{items_count = Items1, filter = F1, hfs = Hfs}, #cbf{items_count = Items2, filter = F2}) -> Size = array:size(F1), ?ASSERT(Size =:= array:size(F2)), NewF = array:sparse_foldl(fun(I, X, Acc) -> array:set(I, array:get(I, Acc) - X, Acc) end, F1, F2), #cbf{filter = NewF, hfs = Hfs, items_count = Items1 - Items2 %approximation }. -spec to_bloom(cbf()) -> bloom:bloom_filter(). to_bloom(#cbf{items_count = 0, filter = F, hfs = Hfs}) -> bloom:new(array:size(F), Hfs); to_bloom(#cbf{items_count = ItemsCount, filter = F, hfs = Hfs}) -> % note : this is faster than using array : sparse_fold[r , l]/3 to get the positions %% Positions0 = array:sparse_to_list(array:sparse_map(fun(I, _) -> I end, F)), %% % position 0 may be missing since 0 is the default value, too Positions = case array : , F ) of %% 0 -> Positions0; %% _ -> [0 | Positions0] %% end, % this seems even faster: Positions = lists:reverse( element(2, lists:foldl( fun(0, {N, L}) -> {N+1, L}; (_, {N, L}) -> {N+1, [N | L]} end, {0, []}, array:to_list(F)))), BFSize = array:size(F), BFBits = bloom:p_add_positions(Positions, <<0:BFSize>>, BFSize), bloom:new_bin(BFBits, Hfs, ItemsCount). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @doc Checks whether two counting bloom filters are equal . -spec equals(cbf(), cbf()) -> boolean(). equals(#cbf{ items_count = Items1, filter = Filter1 }, #cbf{ items_count = Items2, filter = Filter2 }) -> Items1 =:= Items2 andalso Filter1 =:= Filter2. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% @doc Returns counting bloom filter debug information. -spec print(cbf()) -> [{atom(), any()}]. print(#cbf{filter = Filter, hfs = Hfs, items_count = NumItems} = Bloom) -> Size = array:size(Filter), HCount = ?REP_HFS:size(Hfs), [{filter_size, Size}, {filter_byte_size, byte_size(term_to_binary(Filter, [compressed]))}, {filter_as_list_byte_size, byte_size(term_to_binary(array:to_list(Filter), [compressed]))}, {hash_fun_num, HCount}, {items_inserted, NumItems}, {act_fpr, get_property(Bloom, fpr)}, {compression_rate, ?IIF(NumItems =:= 0, 0.0, Size / NumItems)}]. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec get_property(cbf(), fpr) -> float(); (cbf(), size) -> non_neg_integer(); (cbf(), filter) -> array:array(integer()); (cbf(), hfs_size) -> non_neg_integer(); (cbf(), hfs) -> ?REP_HFS:hfs(); (cbf(), items_count) -> non_neg_integer(). get_property(#cbf{filter = Filter, hfs = Hfs, items_count = NumItems}, fpr) -> Size = array:size(Filter), bloom:calc_FPR(Size, NumItems, ?REP_HFS:size(Hfs)); get_property(#cbf{filter = Filter}, size) -> array:size(Filter); get_property(#cbf{filter = X} , filter) -> X; get_property(#cbf{hfs = X} , hfs_size) -> ?REP_HFS:size(X); get_property(#cbf{hfs = X} , hfs) -> X; get_property(#cbf{items_count = X}, items_count) -> X. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% bit/counter position operations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % @doc Checks whether all counters are non-zero at the given positions. -spec check_counters(array:array(integer()), Positions::[non_neg_integer()]) -> boolean(). check_counters(Filter, [Pos | Positions]) -> array:get(Pos, Filter) =/= 0 andalso check_counters(Filter, Positions); check_counters(_, []) -> true.
null
https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/src/rrepair/cbf.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @doc Counting Bloom Filter implementation @end <em>Set Reconciliation via Counting Bloom Filters</em> @version $Id$ hash function set implementation to use for tests: Types number of inserted items API @doc Creates a new counting bloom filter with the default (optimal) hash function set based on the given false positive rate. @doc Creates a new counting bloom filter with the given hash function set based on the given false positive rate. @doc Creates a new counting bloom filter with the given hash function set and a fixed number of positions (bits in standard bloom filters) per item. @doc Creates a new counting bloom filter with the given binary, hash function set and item count. @doc Creates a new counting bloom filter. @doc Adds multiple items to the counting bloom filter. @doc Helper to add items to the counting bloom filter. counters in a list and merging it with the old list. (may introduce false negatives if removing an item not added previously) @doc Removes multiple items from the counting bloom filter. (may introduce false negatives if removing an item not added previously) @doc Helper to remove items from the counting bloom filter. @doc Returns true if the counting bloom filter contains this item. @doc Gets the number of items inserted into this counting bloom filter. filter represents their union. approximation @doc Subtracts counting bloom filter A from B so that the returned counting bloom filter that approximates the set difference (with false positives and false negatives!). approximation note : this is faster than using array : sparse_fold[r , l]/3 to get the positions Positions0 = array:sparse_to_list(array:sparse_map(fun(I, _) -> I end, F)), % position 0 may be missing since 0 is the default value, too 0 -> Positions0; _ -> [0 | Positions0] end, this seems even faster: @doc Returns counting bloom filter debug information. bit/counter position operations @doc Checks whether all counters are non-zero at the given positions.
2016 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > @author < > , 2013 IEEE Transactions on Knowledge and Data Engineering 25.10 -module(cbf). -author(''). -author(''). -include("record_helpers.hrl"). -include("scalaris.hrl"). -export([new_fpr/2, new_fpr/3, new_bpi/3, new_bin/3, new/2, add/2, add_list/2, remove/2, remove_list/2, is_element/2, item_count/1, to_bloom/1]). -export([equals/2, join/2, minus/2, print/1]). -export([get_property/2]). -export([p_add_list/4]). -record(cbf, { filter = ?required(cbf, filter) :: array:array(integer()), HashFunctionSet }). -opaque cbf() :: #cbf{}. -type key() :: any(). -export_type([cbf/0, key/0]). -spec new_fpr(MaxItems::non_neg_integer(), FPR::float()) -> cbf(). new_fpr(MaxItems, FPR) -> {K, Size} = bloom:calc_HF_num_Size_opt(MaxItems, FPR), new(Size, ?REP_HFS:new(K)). -spec new_fpr(MaxItems::non_neg_integer(), FPR::float(), ?REP_HFS:hfs() | non_neg_integer()) -> cbf(). new_fpr(MaxItems, FPR, Hfs) -> Size = bloom:calc_least_size(MaxItems, FPR, ?REP_HFS:size(Hfs)), new(Size, Hfs). -spec new_bpi(MaxItems::non_neg_integer(), BitsPerItem::number(), ?REP_HFS:hfs() | non_neg_integer()) -> cbf(). new_bpi(MaxItems, BitPerItem, Hfs) -> new(util:ceil(BitPerItem * MaxItems), Hfs). -spec new_bin(Filter::array:array(integer()), ?REP_HFS:hfs() | non_neg_integer(), ItemsCount::non_neg_integer()) -> cbf(). new_bin(Filter, HfCount, ItemsCount) when is_integer(HfCount) -> new_bin(Filter, ?REP_HFS:new(HfCount), ItemsCount); new_bin(Filter, Hfs, ItemsCount) -> #cbf{filter = Filter, hfs = Hfs, items_count = ItemsCount}. -spec new(BitSize::pos_integer(), ?REP_HFS:hfs() | non_neg_integer()) -> cbf(). new(BitSize, HfCount) when is_integer(HfCount) -> new(BitSize, ?REP_HFS:new(HfCount)); new(BitSize, Hfs) -> #cbf{filter = array:new(BitSize, {default,0}), hfs = Hfs, items_count = 0}. @doc Adds one item to the counting bloom filter . -spec add(cbf(), key()) -> cbf(). add(#cbf{hfs = Hfs, items_count = FilledCount, filter = Filter} = Bloom, Item) -> BFSize = array:size(Filter), Bloom#cbf{filter = p_add_list(Hfs, BFSize, Filter, [Item]), items_count = FilledCount + 1}. -spec add_list(cbf(), [key()]) -> cbf(). add_list(#cbf{hfs = Hfs, items_count = FilledCount, filter = Filter } = Bloom, Items) -> BFSize = array:size(Filter), ItemsL = length(Items), F = p_add_list(Hfs, BFSize, Filter, Items), Bloom#cbf{filter = F, items_count = FilledCount + ItemsL}. -compile({inline, [p_add_list/4, p_change_list_/6]}). -spec p_add_list(Hfs::?REP_HFS:hfs(), BFSize::pos_integer(), BF1::array:array(integer()), Items::[key()]) -> BF2::array:array(integer()). p_add_list(_Hfs, _BFSize, BF, []) -> BF; p_add_list(Hfs, 1, BF, _Items = [_|_]) -> array:set(0, ?REP_HFS:size(Hfs), BF); p_add_list(Hfs, BFSize, BF, Items = [_|_]) -> Positions = lists:flatmap(fun(Item) -> ?REP_HFS:apply_val_rem(Hfs, Item, BFSize) end, Items), [Pos | Rest] = lists:sort(Positions), p_change_list_(Rest, Pos, [1 | lists:duplicate(Pos, 0)], BFSize, BF, fun erlang:'+'/2). @doc Helper increasing or decreasing counters by first accumulating all -spec p_change_list_(Positions::[non_neg_integer()], CurPos::non_neg_integer(), Counters::[non_neg_integer(),...], BFSize::non_neg_integer(), BF::array:array(integer()), ChangeFun::fun((non_neg_integer(), non_neg_integer()) -> integer())) -> BF2::array:array(integer()). p_change_list_([], CurPos, Counters, BFSize, BF, ChangeFun) -> Counters1 = lists:reverse(Counters, lists:duplicate(erlang:max(0, BFSize - CurPos - 1), 0)), Counters2 = lists:zipwith(ChangeFun, array:to_list(BF), Counters1), array:from_list(Counters2); p_change_list_([CurPos | Positions], CurPos, [CurCount | Counters], BFSize, BF, ChangeFun) -> p_change_list_(Positions, CurPos, [CurCount + 1 | Counters], BFSize, BF, ChangeFun); p_change_list_([NewPos | Positions], CurPos, Counters, BFSize, BF, ChangeFun) -> Counters1 = lists:duplicate(NewPos - CurPos - 1, 0) ++ Counters, p_change_list_(Positions, NewPos, [1 | Counters1], BFSize, BF, ChangeFun). @doc Removes one item from the counting bloom filter . -spec remove(cbf(), key()) -> cbf(). remove(#cbf{hfs = Hfs, items_count = FilledCount, filter = Filter} = Bloom, Item) -> BFSize = array:size(Filter), Bloom#cbf{filter = p_remove_list(Hfs, BFSize, Filter, [Item]), items_count = FilledCount + 1}. -spec remove_list(cbf(), [key()]) -> cbf(). remove_list(#cbf{hfs = Hfs, items_count = FilledCount, filter = Filter } = Bloom, Items) -> BFSize = array:size(Filter), ItemsL = length(Items), F = p_remove_list(Hfs, BFSize, Filter, Items), Bloom#cbf{filter = F, items_count = FilledCount + ItemsL}. -compile({inline, [p_remove_list/4]}). -spec p_remove_list(Hfs::?REP_HFS:hfs(), BFSize::pos_integer(), BF1::array:array(integer()), Items::[key()]) -> BF2::array:array(integer()). p_remove_list(_Hfs, _BFSize, BF, []) -> BF; p_remove_list(_Hfs, 1, BF, _Items = [_|_]) -> array:set(0, 0, BF); p_remove_list(Hfs, BFSize, BF, Items = [_|_]) -> Positions = lists:flatmap(fun(Item) -> ?REP_HFS:apply_val_rem(Hfs, Item, BFSize) end, Items), [Pos | Rest] = lists:sort(Positions), p_change_list_(Rest, Pos, [1 | lists:duplicate(Pos, 0)], BFSize, BF, fun erlang:'-'/2). -spec is_element(cbf(), key()) -> boolean(). is_element(#cbf{items_count = 0}, _Item) -> false; is_element(#cbf{hfs = Hfs, filter = Filter}, Item) -> BFSize = array:size(Filter), Positions = ?REP_HFS:apply_val_rem(Hfs, Item, BFSize), check_counters(Filter, Positions). -spec item_count(cbf()) -> non_neg_integer(). item_count(#cbf{items_count = ItemsCount}) -> ItemsCount. @doc Joins two counting bloom filters so that the returned counting bloom -spec join(cbf(), cbf()) -> cbf(). join(#cbf{items_count = 0, hfs = Hfs1} = _BF1, #cbf{hfs = Hfs2} = BF2) -> ?ASSERT(?REP_HFS:size(Hfs1) =:= ?REP_HFS:size(Hfs2)), ?ASSERT(get_property(BF2, size) =:= get_property(_BF1, size)), BF2; join(#cbf{hfs = Hfs1} = BF1, #cbf{items_count = 0, hfs = Hfs2} = _BF2) -> ?ASSERT(?REP_HFS:size(Hfs1) =:= ?REP_HFS:size(Hfs2)), ?ASSERT(get_property(BF1, size) =:= get_property(_BF2, size)), BF1; join(#cbf{items_count = Items1, filter = F1, hfs = Hfs}, #cbf{items_count = Items2, filter = F2}) -> Size = array:size(F1), ?ASSERT(Size =:= array:size(F2)), if Items1 > Items2 -> FSmall = F2, FBig = F1, ok; true -> FSmall = F1, FBig = F2, ok end, NewF = array:sparse_foldl(fun(I, X, Acc) -> array:set(I, array:get(I, Acc) + X, Acc) end, FBig, FSmall), #cbf{filter = NewF, hfs = Hfs, }. -spec minus(A::cbf(), B::cbf()) -> cbf(). minus(#cbf{items_count = 0, hfs = Hfs1} = BF1, #cbf{hfs = Hfs2} = _BF2) -> ?ASSERT(?REP_HFS:size(Hfs1) =:= ?REP_HFS:size(Hfs2)), ?ASSERT(get_property(_BF2, size) =:= get_property(BF1, size)), BF1; minus(#cbf{hfs = Hfs1} = BF1, #cbf{items_count = 0, hfs = Hfs2} = _BF2) -> ?ASSERT(?REP_HFS:size(Hfs1) =:= ?REP_HFS:size(Hfs2)), ?ASSERT(get_property(BF1, size) =:= get_property(_BF2, size)), BF1; minus(#cbf{items_count = Items1, filter = F1, hfs = Hfs}, #cbf{items_count = Items2, filter = F2}) -> Size = array:size(F1), ?ASSERT(Size =:= array:size(F2)), NewF = array:sparse_foldl(fun(I, X, Acc) -> array:set(I, array:get(I, Acc) - X, Acc) end, F1, F2), #cbf{filter = NewF, hfs = Hfs, }. -spec to_bloom(cbf()) -> bloom:bloom_filter(). to_bloom(#cbf{items_count = 0, filter = F, hfs = Hfs}) -> bloom:new(array:size(F), Hfs); to_bloom(#cbf{items_count = ItemsCount, filter = F, hfs = Hfs}) -> Positions = case array : , F ) of Positions = lists:reverse( element(2, lists:foldl( fun(0, {N, L}) -> {N+1, L}; (_, {N, L}) -> {N+1, [N | L]} end, {0, []}, array:to_list(F)))), BFSize = array:size(F), BFBits = bloom:p_add_positions(Positions, <<0:BFSize>>, BFSize), bloom:new_bin(BFBits, Hfs, ItemsCount). @doc Checks whether two counting bloom filters are equal . -spec equals(cbf(), cbf()) -> boolean(). equals(#cbf{ items_count = Items1, filter = Filter1 }, #cbf{ items_count = Items2, filter = Filter2 }) -> Items1 =:= Items2 andalso Filter1 =:= Filter2. -spec print(cbf()) -> [{atom(), any()}]. print(#cbf{filter = Filter, hfs = Hfs, items_count = NumItems} = Bloom) -> Size = array:size(Filter), HCount = ?REP_HFS:size(Hfs), [{filter_size, Size}, {filter_byte_size, byte_size(term_to_binary(Filter, [compressed]))}, {filter_as_list_byte_size, byte_size(term_to_binary(array:to_list(Filter), [compressed]))}, {hash_fun_num, HCount}, {items_inserted, NumItems}, {act_fpr, get_property(Bloom, fpr)}, {compression_rate, ?IIF(NumItems =:= 0, 0.0, Size / NumItems)}]. -spec get_property(cbf(), fpr) -> float(); (cbf(), size) -> non_neg_integer(); (cbf(), filter) -> array:array(integer()); (cbf(), hfs_size) -> non_neg_integer(); (cbf(), hfs) -> ?REP_HFS:hfs(); (cbf(), items_count) -> non_neg_integer(). get_property(#cbf{filter = Filter, hfs = Hfs, items_count = NumItems}, fpr) -> Size = array:size(Filter), bloom:calc_FPR(Size, NumItems, ?REP_HFS:size(Hfs)); get_property(#cbf{filter = Filter}, size) -> array:size(Filter); get_property(#cbf{filter = X} , filter) -> X; get_property(#cbf{hfs = X} , hfs_size) -> ?REP_HFS:size(X); get_property(#cbf{hfs = X} , hfs) -> X; get_property(#cbf{items_count = X}, items_count) -> X. -spec check_counters(array:array(integer()), Positions::[non_neg_integer()]) -> boolean(). check_counters(Filter, [Pos | Positions]) -> array:get(Pos, Filter) =/= 0 andalso check_counters(Filter, Positions); check_counters(_, []) -> true.
072beb4b933d07c955885959dcfd0d3985088aa2bb6757e891c0ab56dbb84d83
dpiponi/Moodler
string_warp.hs
do (x0, y0) <- mouse let (x, y) = quantise2 quantum (x0, y0) root <- currentPlane string_id10 <- new' "string_id" in11 <- plugin' (string_id10 ! "input") (x+(-27.0), y+(1.0)) (Inside root) setColour in11 "(0, 0, 1)" out12 <- plugout' (string_id10 ! "result") (x+(14.0), y+(1.0)) (Inside root) setColour out12 "(0, 0, 1)" recompile return ()
null
https://raw.githubusercontent.com/dpiponi/Moodler/a0c984c36abae52668d00f25eb3749e97e8936d3/Moodler/scripts/string_warp.hs
haskell
do (x0, y0) <- mouse let (x, y) = quantise2 quantum (x0, y0) root <- currentPlane string_id10 <- new' "string_id" in11 <- plugin' (string_id10 ! "input") (x+(-27.0), y+(1.0)) (Inside root) setColour in11 "(0, 0, 1)" out12 <- plugout' (string_id10 ! "result") (x+(14.0), y+(1.0)) (Inside root) setColour out12 "(0, 0, 1)" recompile return ()
ac43b175f78ef2bebbc93ad8bc95378000d9a9db87421a737334f70c6ff6dee2
afiskon/erlang-task-queue
task_queue_workers_sup.erl
-module(task_queue_workers_sup). -behaviour(supervisor). %% API -export([start_link/1]). %% Supervisor callbacks -export([init/1]). -define(CHILD(Id, Mod, Type, Args), {Id, {Mod, start_link, Args}, transient, 5000, Type, [Mod]}). %%%=================================================================== %%% API functions %%%=================================================================== start_link(Options) -> supervisor:start_link(?MODULE, Options). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== init(Options) -> MaxR = proplists:get_value(workers_max_r, Options, 0), MaxT = proplists:get_value(workers_max_t, Options, 1), WorkersNum = proplists:get_value(workers_num, Options, 10), WorkersSpec = [ ?CHILD(worker_id(N), task_queue_worker, worker, [Options]) || N <- lists:seq(1, WorkersNum) ], {ok, {{one_for_one, MaxR, MaxT}, WorkersSpec}}. %%%=================================================================== Internal functions %%%=================================================================== worker_id(N) -> list_to_binary(["worker_" | integer_to_list(N)]).
null
https://raw.githubusercontent.com/afiskon/erlang-task-queue/1d3a48d0620ed2108b0cf2fdbd2531778597970f/src/task_queue_workers_sup.erl
erlang
API Supervisor callbacks =================================================================== API functions =================================================================== =================================================================== Supervisor callbacks =================================================================== =================================================================== ===================================================================
-module(task_queue_workers_sup). -behaviour(supervisor). -export([start_link/1]). -export([init/1]). -define(CHILD(Id, Mod, Type, Args), {Id, {Mod, start_link, Args}, transient, 5000, Type, [Mod]}). start_link(Options) -> supervisor:start_link(?MODULE, Options). init(Options) -> MaxR = proplists:get_value(workers_max_r, Options, 0), MaxT = proplists:get_value(workers_max_t, Options, 1), WorkersNum = proplists:get_value(workers_num, Options, 10), WorkersSpec = [ ?CHILD(worker_id(N), task_queue_worker, worker, [Options]) || N <- lists:seq(1, WorkersNum) ], {ok, {{one_for_one, MaxR, MaxT}, WorkersSpec}}. Internal functions worker_id(N) -> list_to_binary(["worker_" | integer_to_list(N)]).
552ad610481178f6dbd0bcc67d66425710997d823aa2c9a757812e5ad46595ca
manu291/dypgen
parse_tree.ml
type tree = Int of int | Node of (tree * tree * tree) let rec print_tree t = match t with | Int x -> print_int x | Node (t1,t2,t3) -> ( print_string "("; print_tree t1; print_string "+"; print_tree t2; print_string "*"; print_tree t3; print_string ")") let print_forest forest = let aux t = print_tree t; print_newline () in List.iter aux forest; print_newline ()
null
https://raw.githubusercontent.com/manu291/dypgen/59d11b4c70b8d0971348ca6913839ff1fb4f9b5f/demos/position/parse_tree.ml
ocaml
type tree = Int of int | Node of (tree * tree * tree) let rec print_tree t = match t with | Int x -> print_int x | Node (t1,t2,t3) -> ( print_string "("; print_tree t1; print_string "+"; print_tree t2; print_string "*"; print_tree t3; print_string ")") let print_forest forest = let aux t = print_tree t; print_newline () in List.iter aux forest; print_newline ()
66efdbb7cbcd5b7073e64f4a2bc3f371a388cceb36c9a637ecb51da5c19cdcc0
gleam-lang/rebar_gleam
rebar_gleam_prv_compile.erl
-module(rebar_gleam_prv_compile). -behaviour(provider). -export([init/1, do/1, format_error/1]). -define(PROVIDER, compile). -define(DEPS, [lock]). %% =================================================================== %% Public API %% =================================================================== -spec init(rebar_state:t()) -> {ok, rebar_state:t()}. init(State) -> Provider = providers:create([ {name, ?PROVIDER}, {module, ?MODULE}, {bare, true}, {deps, ?DEPS}, {example, "rebar3 compile"}, {short_desc, "Build Gleam projects with rebar3"}, {desc, "Build Gleam projects with rebar3"}, {opts, [{deps_only, $d, "deps_only", undefined, "Only compile dependencies, no project apps will be built."}]} ]), {ok, rebar_state:add_provider(State, Provider)}. -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. do(State) -> rebar_gleam:provider_do(State, fun rebar_prv_compile:do/1). -spec format_error(any()) -> iolist(). format_error(Reason) -> rebar_prv_compile:format_error(Reason).
null
https://raw.githubusercontent.com/gleam-lang/rebar_gleam/2e9f8d4726f4c38db08e5dbc894c67da6159489f/src/rebar_gleam_prv_compile.erl
erlang
=================================================================== Public API ===================================================================
-module(rebar_gleam_prv_compile). -behaviour(provider). -export([init/1, do/1, format_error/1]). -define(PROVIDER, compile). -define(DEPS, [lock]). -spec init(rebar_state:t()) -> {ok, rebar_state:t()}. init(State) -> Provider = providers:create([ {name, ?PROVIDER}, {module, ?MODULE}, {bare, true}, {deps, ?DEPS}, {example, "rebar3 compile"}, {short_desc, "Build Gleam projects with rebar3"}, {desc, "Build Gleam projects with rebar3"}, {opts, [{deps_only, $d, "deps_only", undefined, "Only compile dependencies, no project apps will be built."}]} ]), {ok, rebar_state:add_provider(State, Provider)}. -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. do(State) -> rebar_gleam:provider_do(State, fun rebar_prv_compile:do/1). -spec format_error(any()) -> iolist(). format_error(Reason) -> rebar_prv_compile:format_error(Reason).
4541da07fa6a6e2e0620544c7ca81376772b8c090bbdefe03bbbd242dfee1057
onyx-platform/onyx
tail_params_test.clj
(ns onyx.peer.tail-params-test (:require [clojure.core.async :refer [chan >!! <!! close! sliding-buffer]] [clojure.test :refer [deftest is testing]] [onyx.plugin.core-async :refer [take-segments!]] [onyx.test-helper :refer [load-config with-test-env add-test-env-peers!]] [onyx.static.uuid :refer [random-uuid]] [onyx.api])) (defn handle-exception [event lifecycle lf-kw exception] :kill) (def exception-calls {:lifecycle/handle-exception handle-exception}) (def n-messages 1) (def in-chan (atom nil)) (def in-buffer (atom nil)) (def out-chan (atom nil)) (defn inject-in-ch [event lifecycle] {:core.async/buffer in-buffer :core.async/chan @in-chan}) (defn inject-out-ch [event lifecycle] {:core.async/chan @out-chan}) (def in-calls {:lifecycle/before-task-start inject-in-ch}) (def out-calls {:lifecycle/before-task-start inject-out-ch}) (defn my-adder [factor {:keys [n] :as segment}] (throw (ex-info "fail" {:x 50}))) (deftest tail-params (let [id (random-uuid) config (load-config) env-config (assoc (:env-config config) :onyx/tenancy-id id) peer-config (assoc (:peer-config config) :onyx/tenancy-id id) batch-size 20 workflow [[:in :out]] catalog [{:onyx/name :in :onyx/plugin :onyx.plugin.core-async/input :onyx/type :input :onyx/medium :core.async :onyx/batch-size batch-size :onyx/max-peers 1 :onyx/doc "Reads segments from a core.async channel"} {:onyx/name :out :onyx/plugin :onyx.plugin.core-async/output :onyx/type :output :onyx/medium :core.async :onyx/fn :onyx.peer.tail-params-test/my-adder :some/factor 42 :onyx/params [:some/factor] :onyx/batch-size batch-size :onyx/max-peers 1 :onyx/doc "Writes segments to a core.async channel"}] lifecycles [{:lifecycle/task :in :lifecycle/calls :onyx.peer.tail-params-test/in-calls} {:lifecycle/task :out :lifecycle/calls :onyx.peer.tail-params-test/out-calls} {:lifecycle/task :all :lifecycle/calls ::exception-calls}]] (reset! in-chan (chan (inc n-messages))) (reset! in-buffer {}) (reset! out-chan (chan (sliding-buffer (inc n-messages)))) (with-test-env [test-env [3 env-config peer-config]] (doseq [n (range n-messages)] (>!! @in-chan {:n n})) (close! @in-chan) (let [{:keys [job-id]} (onyx.api/submit-job peer-config {:catalog catalog :workflow workflow :lifecycles lifecycles :task-scheduler :onyx.task-scheduler/balanced})] (try (onyx.test-helper/feedback-exception! peer-config job-id) (is false) (catch Exception e (is (= "fail" (.getMessage e))) (is (= {:x 50 :original-exception :clojure.lang.ExceptionInfo :offending-task :out :offending-segment {:n 0}} (ex-data e)))))))))
null
https://raw.githubusercontent.com/onyx-platform/onyx/74f9ae58cdbcfcb1163464595f1e6ae6444c9782/test/onyx/peer/tail_params_test.clj
clojure
(ns onyx.peer.tail-params-test (:require [clojure.core.async :refer [chan >!! <!! close! sliding-buffer]] [clojure.test :refer [deftest is testing]] [onyx.plugin.core-async :refer [take-segments!]] [onyx.test-helper :refer [load-config with-test-env add-test-env-peers!]] [onyx.static.uuid :refer [random-uuid]] [onyx.api])) (defn handle-exception [event lifecycle lf-kw exception] :kill) (def exception-calls {:lifecycle/handle-exception handle-exception}) (def n-messages 1) (def in-chan (atom nil)) (def in-buffer (atom nil)) (def out-chan (atom nil)) (defn inject-in-ch [event lifecycle] {:core.async/buffer in-buffer :core.async/chan @in-chan}) (defn inject-out-ch [event lifecycle] {:core.async/chan @out-chan}) (def in-calls {:lifecycle/before-task-start inject-in-ch}) (def out-calls {:lifecycle/before-task-start inject-out-ch}) (defn my-adder [factor {:keys [n] :as segment}] (throw (ex-info "fail" {:x 50}))) (deftest tail-params (let [id (random-uuid) config (load-config) env-config (assoc (:env-config config) :onyx/tenancy-id id) peer-config (assoc (:peer-config config) :onyx/tenancy-id id) batch-size 20 workflow [[:in :out]] catalog [{:onyx/name :in :onyx/plugin :onyx.plugin.core-async/input :onyx/type :input :onyx/medium :core.async :onyx/batch-size batch-size :onyx/max-peers 1 :onyx/doc "Reads segments from a core.async channel"} {:onyx/name :out :onyx/plugin :onyx.plugin.core-async/output :onyx/type :output :onyx/medium :core.async :onyx/fn :onyx.peer.tail-params-test/my-adder :some/factor 42 :onyx/params [:some/factor] :onyx/batch-size batch-size :onyx/max-peers 1 :onyx/doc "Writes segments to a core.async channel"}] lifecycles [{:lifecycle/task :in :lifecycle/calls :onyx.peer.tail-params-test/in-calls} {:lifecycle/task :out :lifecycle/calls :onyx.peer.tail-params-test/out-calls} {:lifecycle/task :all :lifecycle/calls ::exception-calls}]] (reset! in-chan (chan (inc n-messages))) (reset! in-buffer {}) (reset! out-chan (chan (sliding-buffer (inc n-messages)))) (with-test-env [test-env [3 env-config peer-config]] (doseq [n (range n-messages)] (>!! @in-chan {:n n})) (close! @in-chan) (let [{:keys [job-id]} (onyx.api/submit-job peer-config {:catalog catalog :workflow workflow :lifecycles lifecycles :task-scheduler :onyx.task-scheduler/balanced})] (try (onyx.test-helper/feedback-exception! peer-config job-id) (is false) (catch Exception e (is (= "fail" (.getMessage e))) (is (= {:x 50 :original-exception :clojure.lang.ExceptionInfo :offending-task :out :offending-segment {:n 0}} (ex-data e)))))))))
26923f0f5c41b48b98285e2a1b9279b2248c4542e99dd8ab49403e8cfbecdd79
huangz1990/SICP-answers
23-another-for-each.scm
23-another-for-each.scm (define (for-each p lst) (cond ((not (null? lst)) (p (car lst)) (for-each p (cdr lst)))))
null
https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp2/code/23-another-for-each.scm
scheme
23-another-for-each.scm (define (for-each p lst) (cond ((not (null? lst)) (p (car lst)) (for-each p (cdr lst)))))
c41e11139ee8ef46eb7a41eb9bd45041a37a7edbad19f1e66c01cb5a37b8ec39
xh4/web-toolkit
style.lisp
(in-package :component) (defgeneric component-class-style (component-name)) (defun css-properties () (loop for class in (class-direct-subclasses (find-class 'css:property)) for name = (class-name class) when (fboundp name) collect name)) (define-condition on-css-property () ((property :initarg :property :initform nil))) (define-condition on-css-rule () ((rule :initarg :rule :initform nil))) (defmacro with-css-as-signal (&body body) (let ((properties (css-properties))) `(flet ,(loop for property in properties collect `(,property (value) (let ((property (funcall (symbol-function ',property) value))) (restart-case (signal 'on-css-property :property property) (continue ()))))) (macrolet ((css:rule (selector &body body) `(let ((properties '())) (handler-bind ((on-css-property (lambda (c) (push (slot-value c 'property) properties) (continue)))) ,@body (let ((rule (apply (symbol-function 'css:rule) ,selector (reverse properties)))) (restart-case (signal 'on-css-rule :rule rule) (continue ())))))) (css:property (name value) `(let ((property (funcall (symbol-function 'css:property) ,name ,value))) (restart-case (signal 'on-css-property :property property) (continue ()))))) ,@body)))) (defmacro define-component-class-style-method (component-name &body body) `(defmethod component-class-style ((class (eql ',component-name))) (with-css-as-signal ,@body))) (defmethod component-class-style (component)) (defmethod component-class-style :around (component) (let* ((component-name (typecase component (symbol component) (component (class-name (class-of component))))) (package (symbol-package component-name)) (rules '())) (handler-bind ((on-css-rule (lambda (c) (push (slot-value c 'rule) rules) (continue)))) (call-next-method)) (reverse rules)))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/component/style.lisp
lisp
(in-package :component) (defgeneric component-class-style (component-name)) (defun css-properties () (loop for class in (class-direct-subclasses (find-class 'css:property)) for name = (class-name class) when (fboundp name) collect name)) (define-condition on-css-property () ((property :initarg :property :initform nil))) (define-condition on-css-rule () ((rule :initarg :rule :initform nil))) (defmacro with-css-as-signal (&body body) (let ((properties (css-properties))) `(flet ,(loop for property in properties collect `(,property (value) (let ((property (funcall (symbol-function ',property) value))) (restart-case (signal 'on-css-property :property property) (continue ()))))) (macrolet ((css:rule (selector &body body) `(let ((properties '())) (handler-bind ((on-css-property (lambda (c) (push (slot-value c 'property) properties) (continue)))) ,@body (let ((rule (apply (symbol-function 'css:rule) ,selector (reverse properties)))) (restart-case (signal 'on-css-rule :rule rule) (continue ())))))) (css:property (name value) `(let ((property (funcall (symbol-function 'css:property) ,name ,value))) (restart-case (signal 'on-css-property :property property) (continue ()))))) ,@body)))) (defmacro define-component-class-style-method (component-name &body body) `(defmethod component-class-style ((class (eql ',component-name))) (with-css-as-signal ,@body))) (defmethod component-class-style (component)) (defmethod component-class-style :around (component) (let* ((component-name (typecase component (symbol component) (component (class-name (class-of component))))) (package (symbol-package component-name)) (rules '())) (handler-bind ((on-css-rule (lambda (c) (push (slot-value c 'rule) rules) (continue)))) (call-next-method)) (reverse rules)))
c4ce8f4965e24a5d5086c3dc02adb7b164643220486d947a59cd58da7a5e2a26
thheller/shadow-cljsjs
storage.cljs
(ns firebase.storage {:skip-goog-provide true} (:require ["@firebase/storage"]))
null
https://raw.githubusercontent.com/thheller/shadow-cljsjs/eaf350d29d45adb85c0753dff77e276e7925a744/src/main/firebase/storage.cljs
clojure
(ns firebase.storage {:skip-goog-provide true} (:require ["@firebase/storage"]))
999b09054ff2fe6788f051f873aef1e55dc05e923b049f25d78fd0b3d5927062
shayan-najd/NativeMetaprogramming
T7220.hs
# OPTIONS_GHC -fno - warn - redundant - constraints # # LANGUAGE FlexibleContexts # # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeFamilies # # LANGUAGE ScopedTypeVariables # module Test2 where class C a b | b -> a data A = A data X a = X data Y = Y type family TF b f :: (forall b. (C a b, TF b ~ Y) => b) -> X a f _ = undefined u :: (C A b, TF b ~ Y) => b u = undefined v :: X A v = (f :: (forall b. (C A b, TF b ~ Y) => b) -> X A) u -- This line causes an error (see below) GHC 7.6.1 - rc1 ( 7.6.0.20120810 ) rejects this code with the following error message . Test2.hs:24:52 : Could n't match expected type ` Y ' with actual type ` TF ( forall b. ( C A b , TF b ~ Y ) = > b ) ' In the first argument of ` f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X ' , namely ` u ' In the expression : ( f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X ) u In an equation for ` v ' : v = ( f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X ) u GHC 7.4.1 rejected this code with a different error message : Test2.hs:24:6 : Can not deal with a type function under a forall type : forall b. ( C A b , TF b ~ Y ) = > b In the expression : f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X In the expression : ( f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X ) u In an equation for ` v ' : v = ( f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X ) u GHC 7.6.1-rc1 (7.6.0.20120810) rejects this code with the following error message. Test2.hs:24:52: Couldn't match expected type `Y' with actual type `TF (forall b. (C A b, TF b ~ Y) => b)' In the first argument of `f :: (forall b. (C A b, TF b ~ Y) => b) -> X', namely `u' In the expression: (f :: (forall b. (C A b, TF b ~ Y) => b) -> X) u In an equation for `v': v = (f :: (forall b. (C A b, TF b ~ Y) => b) -> X) u GHC 7.4.1 rejected this code with a different error message: Test2.hs:24:6: Cannot deal with a type function under a forall type: forall b. (C A b, TF b ~ Y) => b In the expression: f :: (forall b. (C A b, TF b ~ Y) => b) -> X In the expression: (f :: (forall b. (C A b, TF b ~ Y) => b) -> X) u In an equation for `v': v = (f :: (forall b. (C A b, TF b ~ Y) => b) -> X) u -}
null
https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/typecheck/should_compile/T7220.hs
haskell
# LANGUAGE RankNTypes # This line causes an error (see below)
# OPTIONS_GHC -fno - warn - redundant - constraints # # LANGUAGE FlexibleContexts # # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # # LANGUAGE ScopedTypeVariables # module Test2 where class C a b | b -> a data A = A data X a = X data Y = Y type family TF b f :: (forall b. (C a b, TF b ~ Y) => b) -> X a f _ = undefined u :: (C A b, TF b ~ Y) => b u = undefined v :: X A GHC 7.6.1 - rc1 ( 7.6.0.20120810 ) rejects this code with the following error message . Test2.hs:24:52 : Could n't match expected type ` Y ' with actual type ` TF ( forall b. ( C A b , TF b ~ Y ) = > b ) ' In the first argument of ` f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X ' , namely ` u ' In the expression : ( f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X ) u In an equation for ` v ' : v = ( f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X ) u GHC 7.4.1 rejected this code with a different error message : Test2.hs:24:6 : Can not deal with a type function under a forall type : forall b. ( C A b , TF b ~ Y ) = > b In the expression : f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X In the expression : ( f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X ) u In an equation for ` v ' : v = ( f : : ( forall b. ( C A b , TF b ~ Y ) = > b ) - > X ) u GHC 7.6.1-rc1 (7.6.0.20120810) rejects this code with the following error message. Test2.hs:24:52: Couldn't match expected type `Y' with actual type `TF (forall b. (C A b, TF b ~ Y) => b)' In the first argument of `f :: (forall b. (C A b, TF b ~ Y) => b) -> X', namely `u' In the expression: (f :: (forall b. (C A b, TF b ~ Y) => b) -> X) u In an equation for `v': v = (f :: (forall b. (C A b, TF b ~ Y) => b) -> X) u GHC 7.4.1 rejected this code with a different error message: Test2.hs:24:6: Cannot deal with a type function under a forall type: forall b. (C A b, TF b ~ Y) => b In the expression: f :: (forall b. (C A b, TF b ~ Y) => b) -> X In the expression: (f :: (forall b. (C A b, TF b ~ Y) => b) -> X) u In an equation for `v': v = (f :: (forall b. (C A b, TF b ~ Y) => b) -> X) u -}
6c4f943b8986173a2ca8e1d17eaa33376090238044dcc03f49ef67e3dc2572ea
finnishtransportagency/harja
sampo_api.clj
(ns harja.palvelin.integraatiot.vayla-rest.sampo-api (:require [com.stuartsierra.component :as component] [compojure.core :refer [POST]] [taoensso.timbre :as log] [harja.palvelin.asetukset :refer [ominaisuus-kaytossa?]] [harja.palvelin.komponentit.http-palvelin :refer [julkaise-reitti poista-palvelut julkaise-palvelu]] [harja.palvelin.integraatiot.sampo.tuonti :as tuonti] [harja.palvelin.integraatiot.sampo.vienti :as vienti] [harja.palvelin.integraatiot.api.tyokalut.xml-skeemat :as xml-skeemat] [harja.palvelin.integraatiot.api.tyokalut.kutsukasittely :as kutsukasittely] [harja.palvelin.tyokalut.ajastettu-tehtava :as ajastettu-tehtava] [harja.kyselyt.maksuerat :as q-maksuerat] [harja.palvelin.integraatiot.sampo.kasittely.maksuerat :as maksuerat] [harja.palvelin.integraatiot.sampo.kasittely.kustannussuunnitelmat :as kustannussuunnitelmat] [harja.pvm :as pvm])) (defprotocol Maksueralahetys (laheta-maksuera-sampoon [this numero])) (defn tee-paivittainen-lahetys-tehtava [{:keys [db integraatioloki]} {:keys [paivittainen-lahetysaika] :as api-sampo-asetukset}] (if paivittainen-lahetysaika (do (log/debug "Ajastetaan maksuerien ja kustannussuunnitelmien lähetys ajettavaksi joka päivä kello: " paivittainen-lahetysaika) (ajastettu-tehtava/ajasta-paivittain paivittainen-lahetysaika (fn [_] (vienti/aja-paivittainen-api-lahetys db integraatioloki api-sampo-asetukset)))) (constantly nil))) (defrecord ApiSampo [api-sampo-asetukset] component/Lifecycle (start [{http :http-palvelin db :db integraatioloki :integraatioloki :as this}] (log/debug "Käynnistetään SampoAPI-komponentti") (when (ominaisuus-kaytossa? :api-sampo) (julkaise-reitti http :sampo-vastaanotto (POST "/api/sampo" request (kutsukasittely/kasittele-sampo-kutsu db integraatioloki :sisaanluku request xml-skeemat/+sampo-kutsu+ (fn [db kutsun-data tapahtuma-id] (tuonti/kasittele-api-viesti db integraatioloki kutsun-data tapahtuma-id)) "sampo-api")))) (if (ominaisuus-kaytossa? :api-sampo) (assoc this :paivittainen-lahetys-tehtava (tee-paivittainen-lahetys-tehtava this api-sampo-asetukset)) this)) (stop [{http :http-palvelin :as this}] (when (ominaisuus-kaytossa? :api-sampo) (poista-palvelut http :sampo-vastaanotto)) (if (ominaisuus-kaytossa? :api-sampo) (dissoc this :paivittainen-lahetys-tehtava) this)) Maksueralahetys (laheta-maksuera-sampoon [{:keys [db integraatioloki]} numero] (let [urakkaid (q-maksuerat/hae-maksueran-urakka db numero) summat (q-maksuerat/hae-urakan-maksueran-summat db urakkaid) Sampo joutuu prosessoimaan maksuerän lähetystä , jonka tuloksena kustannussuunnitelmaan tehdään jotain . on , koska Sampo on voinut itse valita , minkä viestin se . - järjestelmälle annetaan aikaa asioiden pureskeluun , niin lähetetään , jonka jälkeen kustanussuunnitelma voidaan lähettää maksueran-lahetys (maksuerat/laheta-api-maksuera db api-sampo-asetukset integraatioloki numero summat) kustannussuunnitelman-lahetys (when maksueran-lahetys (kustannussuunnitelmat/laheta-api-kustannusuunnitelma db api-sampo-asetukset integraatioloki numero))] {:maksuera maksueran-lahetys :kustannussuunnitelma kustannussuunnitelman-lahetys})))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/af09d60911ed31ea98634a9d5c7f4b062e63504f/src/clj/harja/palvelin/integraatiot/vayla_rest/sampo_api.clj
clojure
(ns harja.palvelin.integraatiot.vayla-rest.sampo-api (:require [com.stuartsierra.component :as component] [compojure.core :refer [POST]] [taoensso.timbre :as log] [harja.palvelin.asetukset :refer [ominaisuus-kaytossa?]] [harja.palvelin.komponentit.http-palvelin :refer [julkaise-reitti poista-palvelut julkaise-palvelu]] [harja.palvelin.integraatiot.sampo.tuonti :as tuonti] [harja.palvelin.integraatiot.sampo.vienti :as vienti] [harja.palvelin.integraatiot.api.tyokalut.xml-skeemat :as xml-skeemat] [harja.palvelin.integraatiot.api.tyokalut.kutsukasittely :as kutsukasittely] [harja.palvelin.tyokalut.ajastettu-tehtava :as ajastettu-tehtava] [harja.kyselyt.maksuerat :as q-maksuerat] [harja.palvelin.integraatiot.sampo.kasittely.maksuerat :as maksuerat] [harja.palvelin.integraatiot.sampo.kasittely.kustannussuunnitelmat :as kustannussuunnitelmat] [harja.pvm :as pvm])) (defprotocol Maksueralahetys (laheta-maksuera-sampoon [this numero])) (defn tee-paivittainen-lahetys-tehtava [{:keys [db integraatioloki]} {:keys [paivittainen-lahetysaika] :as api-sampo-asetukset}] (if paivittainen-lahetysaika (do (log/debug "Ajastetaan maksuerien ja kustannussuunnitelmien lähetys ajettavaksi joka päivä kello: " paivittainen-lahetysaika) (ajastettu-tehtava/ajasta-paivittain paivittainen-lahetysaika (fn [_] (vienti/aja-paivittainen-api-lahetys db integraatioloki api-sampo-asetukset)))) (constantly nil))) (defrecord ApiSampo [api-sampo-asetukset] component/Lifecycle (start [{http :http-palvelin db :db integraatioloki :integraatioloki :as this}] (log/debug "Käynnistetään SampoAPI-komponentti") (when (ominaisuus-kaytossa? :api-sampo) (julkaise-reitti http :sampo-vastaanotto (POST "/api/sampo" request (kutsukasittely/kasittele-sampo-kutsu db integraatioloki :sisaanluku request xml-skeemat/+sampo-kutsu+ (fn [db kutsun-data tapahtuma-id] (tuonti/kasittele-api-viesti db integraatioloki kutsun-data tapahtuma-id)) "sampo-api")))) (if (ominaisuus-kaytossa? :api-sampo) (assoc this :paivittainen-lahetys-tehtava (tee-paivittainen-lahetys-tehtava this api-sampo-asetukset)) this)) (stop [{http :http-palvelin :as this}] (when (ominaisuus-kaytossa? :api-sampo) (poista-palvelut http :sampo-vastaanotto)) (if (ominaisuus-kaytossa? :api-sampo) (dissoc this :paivittainen-lahetys-tehtava) this)) Maksueralahetys (laheta-maksuera-sampoon [{:keys [db integraatioloki]} numero] (let [urakkaid (q-maksuerat/hae-maksueran-urakka db numero) summat (q-maksuerat/hae-urakan-maksueran-summat db urakkaid) Sampo joutuu prosessoimaan maksuerän lähetystä , jonka tuloksena kustannussuunnitelmaan tehdään jotain . on , koska Sampo on voinut itse valita , minkä viestin se . - järjestelmälle annetaan aikaa asioiden pureskeluun , niin lähetetään , jonka jälkeen kustanussuunnitelma voidaan lähettää maksueran-lahetys (maksuerat/laheta-api-maksuera db api-sampo-asetukset integraatioloki numero summat) kustannussuunnitelman-lahetys (when maksueran-lahetys (kustannussuunnitelmat/laheta-api-kustannusuunnitelma db api-sampo-asetukset integraatioloki numero))] {:maksuera maksueran-lahetys :kustannussuunnitelma kustannussuunnitelman-lahetys})))
884acd89292b5ab982052770e33c387ac383aae2c9bfc18edbfad2609d7c77e4
imrehg/ypsilon
range.scm
#!nobacktrace Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (library (ypsilon gtk range) (export gtk_range_get_adjustment gtk_range_get_fill_level gtk_range_get_inverted gtk_range_get_lower_stepper_sensitivity gtk_range_get_restrict_to_fill_level gtk_range_get_show_fill_level gtk_range_get_type gtk_range_get_update_policy gtk_range_get_upper_stepper_sensitivity gtk_range_get_value gtk_range_set_adjustment gtk_range_set_fill_level gtk_range_set_increments gtk_range_set_inverted gtk_range_set_lower_stepper_sensitivity gtk_range_set_range gtk_range_set_restrict_to_fill_level gtk_range_set_show_fill_level gtk_range_set_update_policy gtk_range_set_upper_stepper_sensitivity gtk_range_set_value) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libgtk-x11-2.0.so.0") (on-sunos "libgtk-x11-2.0.so.0") (on-freebsd "libgtk-x11-2.0.so.0") (on-openbsd "libgtk-x11-2.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libgtk-win32-2.0-0.dll") (else (assertion-violation #f "can not locate GTK library, unknown operating system")))) (define lib (load-shared-object lib-name)) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (c-function lib lib-name ret name args))))) (define-syntax define-function/va_list (syntax-rules () ((_ ret name args) (define name (lambda x (assertion-violation 'name "va_list argument not supported")))))) ;; GtkAdjustment* gtk_range_get_adjustment (GtkRange* range) (define-function void* gtk_range_get_adjustment (void*)) ;; gdouble gtk_range_get_fill_level (GtkRange* range) (define-function double gtk_range_get_fill_level (void*)) ;; gboolean gtk_range_get_inverted (GtkRange* range) (define-function int gtk_range_get_inverted (void*)) ;; GtkSensitivityType gtk_range_get_lower_stepper_sensitivity (GtkRange* range) (define-function int gtk_range_get_lower_stepper_sensitivity (void*)) ;; gboolean gtk_range_get_restrict_to_fill_level (GtkRange* range) (define-function int gtk_range_get_restrict_to_fill_level (void*)) ;; gboolean gtk_range_get_show_fill_level (GtkRange* range) (define-function int gtk_range_get_show_fill_level (void*)) GType gtk_range_get_type ( void ) (define-function unsigned-long gtk_range_get_type ()) ;; GtkUpdateType gtk_range_get_update_policy (GtkRange* range) (define-function int gtk_range_get_update_policy (void*)) ;; GtkSensitivityType gtk_range_get_upper_stepper_sensitivity (GtkRange* range) (define-function int gtk_range_get_upper_stepper_sensitivity (void*)) ;; gdouble gtk_range_get_value (GtkRange* range) (define-function double gtk_range_get_value (void*)) void gtk_range_set_adjustment ( GtkRange * range , GtkAdjustment * adjustment ) (define-function void gtk_range_set_adjustment (void* void*)) ;; void gtk_range_set_fill_level (GtkRange* range, gdouble fill_level) (define-function void gtk_range_set_fill_level (void* double)) ;; void gtk_range_set_increments (GtkRange* range, gdouble step, gdouble page) (define-function void gtk_range_set_increments (void* double double)) void gtk_range_set_inverted ( GtkRange * range , ) (define-function void gtk_range_set_inverted (void* int)) void gtk_range_set_lower_stepper_sensitivity ( GtkRange * range , GtkSensitivityType sensitivity ) (define-function void gtk_range_set_lower_stepper_sensitivity (void* int)) void gtk_range_set_range ( GtkRange * range , , ) (define-function void gtk_range_set_range (void* double double)) void gtk_range_set_restrict_to_fill_level ( GtkRange * range , gboolean restrict_to_fill_level ) (define-function void gtk_range_set_restrict_to_fill_level (void* int)) void gtk_range_set_show_fill_level ( GtkRange * range , ) (define-function void gtk_range_set_show_fill_level (void* int)) ;; void gtk_range_set_update_policy (GtkRange* range, GtkUpdateType policy) (define-function void gtk_range_set_update_policy (void* int)) void gtk_range_set_upper_stepper_sensitivity ( GtkRange * range , GtkSensitivityType sensitivity ) (define-function void gtk_range_set_upper_stepper_sensitivity (void* int)) ;; void gtk_range_set_value (GtkRange* range, gdouble value) (define-function void gtk_range_set_value (void* double)) ) ;[end]
null
https://raw.githubusercontent.com/imrehg/ypsilon/e57a06ef5c66c1a88905b2be2fa791fa29848514/sitelib/ypsilon/gtk/range.scm
scheme
GtkAdjustment* gtk_range_get_adjustment (GtkRange* range) gdouble gtk_range_get_fill_level (GtkRange* range) gboolean gtk_range_get_inverted (GtkRange* range) GtkSensitivityType gtk_range_get_lower_stepper_sensitivity (GtkRange* range) gboolean gtk_range_get_restrict_to_fill_level (GtkRange* range) gboolean gtk_range_get_show_fill_level (GtkRange* range) GtkUpdateType gtk_range_get_update_policy (GtkRange* range) GtkSensitivityType gtk_range_get_upper_stepper_sensitivity (GtkRange* range) gdouble gtk_range_get_value (GtkRange* range) void gtk_range_set_fill_level (GtkRange* range, gdouble fill_level) void gtk_range_set_increments (GtkRange* range, gdouble step, gdouble page) void gtk_range_set_update_policy (GtkRange* range, GtkUpdateType policy) void gtk_range_set_value (GtkRange* range, gdouble value) [end]
#!nobacktrace Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (library (ypsilon gtk range) (export gtk_range_get_adjustment gtk_range_get_fill_level gtk_range_get_inverted gtk_range_get_lower_stepper_sensitivity gtk_range_get_restrict_to_fill_level gtk_range_get_show_fill_level gtk_range_get_type gtk_range_get_update_policy gtk_range_get_upper_stepper_sensitivity gtk_range_get_value gtk_range_set_adjustment gtk_range_set_fill_level gtk_range_set_increments gtk_range_set_inverted gtk_range_set_lower_stepper_sensitivity gtk_range_set_range gtk_range_set_restrict_to_fill_level gtk_range_set_show_fill_level gtk_range_set_update_policy gtk_range_set_upper_stepper_sensitivity gtk_range_set_value) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libgtk-x11-2.0.so.0") (on-sunos "libgtk-x11-2.0.so.0") (on-freebsd "libgtk-x11-2.0.so.0") (on-openbsd "libgtk-x11-2.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libgtk-win32-2.0-0.dll") (else (assertion-violation #f "can not locate GTK library, unknown operating system")))) (define lib (load-shared-object lib-name)) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (c-function lib lib-name ret name args))))) (define-syntax define-function/va_list (syntax-rules () ((_ ret name args) (define name (lambda x (assertion-violation 'name "va_list argument not supported")))))) (define-function void* gtk_range_get_adjustment (void*)) (define-function double gtk_range_get_fill_level (void*)) (define-function int gtk_range_get_inverted (void*)) (define-function int gtk_range_get_lower_stepper_sensitivity (void*)) (define-function int gtk_range_get_restrict_to_fill_level (void*)) (define-function int gtk_range_get_show_fill_level (void*)) GType gtk_range_get_type ( void ) (define-function unsigned-long gtk_range_get_type ()) (define-function int gtk_range_get_update_policy (void*)) (define-function int gtk_range_get_upper_stepper_sensitivity (void*)) (define-function double gtk_range_get_value (void*)) void gtk_range_set_adjustment ( GtkRange * range , GtkAdjustment * adjustment ) (define-function void gtk_range_set_adjustment (void* void*)) (define-function void gtk_range_set_fill_level (void* double)) (define-function void gtk_range_set_increments (void* double double)) void gtk_range_set_inverted ( GtkRange * range , ) (define-function void gtk_range_set_inverted (void* int)) void gtk_range_set_lower_stepper_sensitivity ( GtkRange * range , GtkSensitivityType sensitivity ) (define-function void gtk_range_set_lower_stepper_sensitivity (void* int)) void gtk_range_set_range ( GtkRange * range , , ) (define-function void gtk_range_set_range (void* double double)) void gtk_range_set_restrict_to_fill_level ( GtkRange * range , gboolean restrict_to_fill_level ) (define-function void gtk_range_set_restrict_to_fill_level (void* int)) void gtk_range_set_show_fill_level ( GtkRange * range , ) (define-function void gtk_range_set_show_fill_level (void* int)) (define-function void gtk_range_set_update_policy (void* int)) void gtk_range_set_upper_stepper_sensitivity ( GtkRange * range , GtkSensitivityType sensitivity ) (define-function void gtk_range_set_upper_stepper_sensitivity (void* int)) (define-function void gtk_range_set_value (void* double))
b0c032e05c6095ed4e192920ea26469d218ed9c5d213bb2d90dd6a3f71186a11
keigoi/ocaml-mpst-light
example.ml
open Mpst_light module OAuthExample = struct let c = {role_label= {make_obj=(fun v->object method role_C=v end); call_obj=(fun obj->obj#role_C)}; role_index=idx0} let s = {role_label= {make_obj=(fun v->object method role_S=v end); call_obj=(fun obj->obj#role_S)}; role_index=idx1} let a = {role_label= {make_obj=(fun v->object method role_A=v end); call_obj=(fun obj->obj#role_A)}; role_index=idx2} let login = {obj={make_obj=(fun v->object method login=v end);call_obj=(fun obj->obj#login)}; var=(fun v->`login v)} let pwd = {obj={make_obj=(fun v->object method pwd=v end);call_obj=(fun obj->obj#pwd)}; var=(fun v->`pwd v)} let auth = {obj={make_obj=(fun v->object method auth=v end);call_obj=(fun obj->obj#auth)}; var=(fun v->`auth v)} let oAuth () = (s --> c) login @@ (c --> a) pwd @@ (a --> s) auth @@ finish end module Example = struct let sample_prot () = (a --> c) msg @@ fix (fun t -> (c --> b) msg @@ choice_at a (to_b left_or_right) (a, (a --> b) left @@ (c --> b) msg @@ (b --> c) left @@ t) (a, (a --> b) right @@ (c --> b) msg @@ (b --> c) right @@ finish)) end module UnfairExample = struct let unfair () = let g = fix (fun t -> choice_at a (to_b right_or_left) (a, (a --> b) right @@ t) (a, (a --> b) left @@ (a --> c) left @@ finish)) in g let run () = let g = unfair () in let ea = get_ch a g in print_endline"projected on a"; let eb = get_ch b g in print_endline"projected on b"; let ec = get_ch c g in print_endline"projected on c"; print_endline"projected on d"; let ta = Thread.create (fun () -> let* ea = send ea#role_B#right () in let* ea = send ea#role_B#right () in let* ea = send ea#role_B#right () in let* ea = send ea#role_B#right () in let* ea = send ea#role_B#left () in let* ea = send ea#role_C#left () in close ea )() and tb = Thread.create (fun () -> let rec loop eb = let* var = receive eb#role_A in match var with | `right(_,eb) -> print_endline "B: right"; loop eb | `left(_,eb) -> print_endline "B: left"; close eb in loop eb) () and tc = Thread.create (fun () -> let* `left(_,ec) = receive ec#role_A in print_endline "C: closing"; close ec) () in List.iter Thread.join [ta; tb; tc] end
null
https://raw.githubusercontent.com/keigoi/ocaml-mpst-light/099658369798b9588cb744ee0b95d09ff6e50d9f/examples/example.ml
ocaml
open Mpst_light module OAuthExample = struct let c = {role_label= {make_obj=(fun v->object method role_C=v end); call_obj=(fun obj->obj#role_C)}; role_index=idx0} let s = {role_label= {make_obj=(fun v->object method role_S=v end); call_obj=(fun obj->obj#role_S)}; role_index=idx1} let a = {role_label= {make_obj=(fun v->object method role_A=v end); call_obj=(fun obj->obj#role_A)}; role_index=idx2} let login = {obj={make_obj=(fun v->object method login=v end);call_obj=(fun obj->obj#login)}; var=(fun v->`login v)} let pwd = {obj={make_obj=(fun v->object method pwd=v end);call_obj=(fun obj->obj#pwd)}; var=(fun v->`pwd v)} let auth = {obj={make_obj=(fun v->object method auth=v end);call_obj=(fun obj->obj#auth)}; var=(fun v->`auth v)} let oAuth () = (s --> c) login @@ (c --> a) pwd @@ (a --> s) auth @@ finish end module Example = struct let sample_prot () = (a --> c) msg @@ fix (fun t -> (c --> b) msg @@ choice_at a (to_b left_or_right) (a, (a --> b) left @@ (c --> b) msg @@ (b --> c) left @@ t) (a, (a --> b) right @@ (c --> b) msg @@ (b --> c) right @@ finish)) end module UnfairExample = struct let unfair () = let g = fix (fun t -> choice_at a (to_b right_or_left) (a, (a --> b) right @@ t) (a, (a --> b) left @@ (a --> c) left @@ finish)) in g let run () = let g = unfair () in let ea = get_ch a g in print_endline"projected on a"; let eb = get_ch b g in print_endline"projected on b"; let ec = get_ch c g in print_endline"projected on c"; print_endline"projected on d"; let ta = Thread.create (fun () -> let* ea = send ea#role_B#right () in let* ea = send ea#role_B#right () in let* ea = send ea#role_B#right () in let* ea = send ea#role_B#right () in let* ea = send ea#role_B#left () in let* ea = send ea#role_C#left () in close ea )() and tb = Thread.create (fun () -> let rec loop eb = let* var = receive eb#role_A in match var with | `right(_,eb) -> print_endline "B: right"; loop eb | `left(_,eb) -> print_endline "B: left"; close eb in loop eb) () and tc = Thread.create (fun () -> let* `left(_,ec) = receive ec#role_A in print_endline "C: closing"; close ec) () in List.iter Thread.join [ta; tb; tc] end
a173582c76674b675daa2a130de7518ae27ebf841d89ec1623216537c24e25d5
mbutterick/typesetting
hacs.rkt
#lang debug racket (require racket/generator graph racket/set) (provide (except-out (all-defined-out) define/contract)) (define-syntax-rule (define/contract EXPR CONTRACT . BODY) (define EXPR . BODY)) (define-syntax when-debug (let () (define debug #t) (if debug (make-rename-transformer #'begin) (λ (stx) (syntax-case stx () [(_ . rest) #'(void)]))))) (define (print-debug-info) (when-debug (displayln (format "assignments: ~a forward checks: ~a checks: ~a " nassns nchecks nfchecks)))) (define-syntax-rule (in-cartesian x) (in-generator (let ([argss x]) (let loop ([argss argss][acc empty]) (if (null? argss) (yield (reverse acc)) (for ([arg (in-stream (car argss))]) (loop (cdr argss) (cons arg acc)))))))) (struct csp (vars constraints) #:mutable #:transparent) (define constraints csp-constraints) (define vars csp-vars) (define-syntax-rule (in-constraints csp) (in-list (csp-constraints csp))) (define-syntax-rule (in-vars csp) (in-list (vars csp))) (define-syntax-rule (in-var-names csp) (in-list (map var-name (vars csp)))) (struct constraint (names proc) #:transparent #:property prop:procedure (λ (const prob) (unless (csp? prob) (raise-argument-error 'constraint "csp" prob)) ;; apply proc in many-to-many style (for/and ([args (in-cartesian (map (λ (name) (find-domain prob name)) (constraint-names const)))]) (apply (constraint-proc const) args)))) (define/contract (make-constraint [names null] [proc values]) (() ((listof name?) procedure?) . ->* . constraint?) (constraint names proc)) (define/contract (csp->graphviz prob) (csp? . -> . string?) (define g (csp->graph prob)) (graphviz g #:colors (coloring/brelaz g))) (define/contract (csp->graph prob) (csp? . -> . graph?) (for*/fold ([gr (unweighted-graph/undirected (map var-name (vars prob)))]) ([constraint (in-constraints prob)] [edge (in-combinations (constraint-names constraint) 2)]) (apply add-edge! gr edge) gr)) (struct var (name domain) #:transparent) (define (var-name? x) #true) ; anything is ok for now (define domain var-domain) (struct checked-variable var (history) #:transparent) (define history checked-variable-history) (define cvar checked-variable) (define cvar? checked-variable?) (struct assigned-var var () #:transparent) (define avar assigned-var) (define avar? assigned-var?) (define/contract (make-csp [vars null] [consts null]) (() ((listof var?) (listof constraint?)) . ->* . csp?) (csp vars consts)) (define (varvals->set vals) (match vals [(list (or (? fixnum?) (? symbol?)) ...) (list->seteq vals)] [_ (list->set vals)])) (define/contract (make-var name [vals null]) ((name?) ((listof any/c)) . ->* . var?) (var name (varvals->set vals))) (define (make-checked-var name vals history) (checked-variable name (varvals->set vals) history)) (define/contract (make-var-names prefix vals [suffix ""]) ((string? (listof any/c)) ((string?)) . ->* . (listof name?)) (for/list ([val (in-list vals)]) (string->symbol (format "~a~a~a" prefix val suffix)))) (define/contract (add-vars! prob names [vals-or-procedure empty]) ((csp? (listof name?)) ((or/c (listof any/c) procedure?)) . ->* . void?) (for/fold ([vrs (vars prob)] #:result (set-csp-vars! prob vrs)) ([name (in-list names)]) (when (memq name (map var-name vrs)) (raise-argument-error 'add-vars! "var that doesn't already exist" name)) (append vrs (list (make-var name (match vals-or-procedure [(? procedure? proc) (proc)] [vals vals])))))) (define/contract (add-var! prob name [vals-or-procedure empty]) ((csp? name?) ((or/c (listof any/c) procedure?)) . ->* . void?) (add-vars! prob (list name) vals-or-procedure)) (define/contract (add-constraints! prob proc namess [proc-name #false] #:caller [caller-id 'add-constraints!]) ((csp? procedure? (listof (listof name?))) ((or/c #false name?)) . ->* . void?) (unless (procedure? proc) (raise-argument-error caller-id "procedure" proc)) (unless (and (list? namess) (andmap list? namess)) (raise-argument-error caller-id "list of lists of names" namess)) (set-csp-constraints! prob (append (constraints prob) (for/list ([names (in-list namess)]) (for ([name (in-list names)]) (check-name-in-csp! 'add-constraints! prob name)) (make-constraint names (if proc-name (procedure-rename proc proc-name) proc)))))) (define/contract (add-pairwise-constraint! prob proc names [proc-name #false]) ((csp? procedure? (listof name?)) (name?) . ->* . void?) (unless (list? names) (raise-argument-error 'add-pairwise-constraint! "list of names" names)) (add-constraints! prob proc (combinations names 2) proc-name #:caller 'add-pairwise-constraint!)) (define/contract (add-transitive-constraint! prob proc names [proc-name #false]) ((csp? procedure? (listof name?)) (name?) . ->* . void?) (unless (and (list? names) (>= (length names) 2)) (raise-argument-error 'add-transitive-constraint! "list of two or more names" names)) (add-constraints! prob proc (for/list ([name (in-list names)] [next (in-list (cdr names))]) (list name next)) proc-name #:caller 'add-transitive-constraint!)) (define/contract (add-constraint! prob proc names [proc-name #false]) ((csp? procedure? (listof name?)) (name?) . ->* . void?) (unless (list? names) (raise-argument-error 'add-constraint! "list of names" names)) (add-constraints! prob proc (list names) proc-name #:caller 'add-constraint!)) (define/contract (alldiff x y) (any/c any/c . -> . boolean?) (not (= x y))) (define alldiff= alldiff) (define (add-all-diff-constraint! prob [names (map var-name (csp-vars prob))] #:same [equal-proc equal?]) (add-pairwise-constraint! prob (λ (x y) (not (equal-proc x y))) names (string->symbol (format "all-diff-~a" (object-name equal-proc))))) (struct backtrack (histories) #:transparent) (define (backtrack! [names null]) (raise (backtrack names))) (define/contract (check-name-in-csp! caller prob name) (symbol? csp? name? . -> . void?) (define names (map var-name (vars prob))) (unless (memq name names) (raise-argument-error caller (format "one of these existing csp var names: ~v" names) name))) (define/contract (find-var prob name) (csp? name? . -> . var?) (check-name-in-csp! 'find-var prob name) (for/first ([vr (in-vars prob)] #:when (eq? name (var-name vr))) vr)) (define/contract (find-domain prob name) (csp? name? . -> . (listof any/c)) (check-name-in-csp! 'find-domain prob name) (domain (find-var prob name))) (define order-domain-values values) (define/contract (assigned-name? prob name) (csp? name? . -> . any/c) (assigned-var? (find-var prob name))) (define/contract (reduce-function-arity proc pattern) (procedure? (listof any/c) . -> . procedure?) (unless (match (procedure-arity proc) [(arity-at-least val) (<= val (length pattern))] [(? number? val) (= val (length pattern))]) (raise-argument-error 'reduce-function-arity (format "list of length ~a, same as procedure arity" (procedure-arity proc)) pattern)) (define reduced-arity-name (string->symbol (format "reduced-arity-~a" (object-name proc)))) (define-values (boxed-id-names vals) (partition box? pattern)) (define new-arity (length boxed-id-names)) (procedure-rename (λ xs (unless (= (length xs) new-arity) (apply raise-arity-error reduced-arity-name new-arity xs)) (apply proc (for/fold ([acc empty] [xs xs] [vals vals] #:result (reverse acc)) ([pat-item (in-list pattern)]) (if (box? pat-item) (values (cons (car xs) acc) (cdr xs) vals) (values (cons (car vals) acc) xs (cdr vals)))))) reduced-arity-name)) (define/contract (reduce-constraint-arity prob [minimum-arity 3]) ((csp?) ((or/c #false natural?)) . ->* . csp?) (define assigned? (curry assigned-name? prob)) (define (partially-assigned? constraint) (ormap assigned? (constraint-names constraint))) (make-csp (vars prob) (for/list ([const (in-constraints prob)]) (cond no point reducing 2 - arity functions because they will be consumed by forward checking [(and (or (not minimum-arity) (<= minimum-arity (constraint-arity const))) (partially-assigned? const)) (match-define (constraint cnames proc) const) ;; pattern is mix of values and boxed symbols (indicating variables to persist) ;; use boxes here as cheap way to distinguish id symbols from value symbols (define arity-reduction-pattern (for/list ([cname (in-list cnames)]) (if (assigned? cname) (first (find-domain prob cname)) (box cname)))) (constraint (filter-not assigned? cnames) (reduce-function-arity proc arity-reduction-pattern))] [else const])))) (define nassns 0) (define nfchecks 0) (define nchecks 0) (define (reset-nassns!) (set! nassns 0)) (define (reset-nfchecks!) (set! nfchecks 0)) (define (reset-nchecks!) (set! nchecks 0)) (define/contract (assign-val prob name val) (csp? name? any/c . -> . csp?) (begin0 (make-csp (for/list ([vr (in-vars prob)]) (if (eq? name (var-name vr)) (assigned-var name (list val)) vr)) (constraints prob)) (when-debug (set! nassns (add1 nassns))))) (define/contract (assigned-vars prob [invert? #f]) ((csp?) (any/c) . ->* . (listof var?)) ((if invert? filter-not filter) assigned-var? (vars prob))) (define/contract (unassigned-vars prob) (csp? . -> . (listof var?)) (assigned-vars prob 'invert)) (define/contract (first-unassigned-variable csp) (csp? . -> . (or/c #false (and/c var? (not/c assigned-var?)))) (match (unassigned-vars csp) [(== empty) #false] [uvars (first uvars)])) (define/contract (argmin* proc xs [max-style? #f]) ((procedure? (listof any/c)) (any/c) . ->* . (listof any/c)) ;; return all elements that have min value. (match xs [(== empty) xs] [(list x) xs] [xs (define vals (map proc xs)) (define target-val (apply (if max-style? max min) vals)) (for/list ([x (in-list xs)] [val (in-list vals)] #:when (= val target-val)) x)])) (define/contract (argmax* proc xs) (procedure? (listof any/c) . -> . (listof any/c)) ;; return all elements that have max value. (argmin* proc xs 'max-mode!)) (define/contract (minimum-remaining-values prob) (csp? . -> . (or/c #false (and/c var? (not/c assigned-var?)))) (match (unassigned-vars prob) [(== empty) #false] [uvars (random-pick (argmin* domain-length uvars))])) (define/contract (max-degree prob) (csp? . -> . (or/c #false (and/c var? (not/c assigned-var?)))) (match (unassigned-vars prob) [(== empty) #false] [uvars (random-pick (argmax* (λ (var) (var-degree prob var)) uvars))])) (define mrv minimum-remaining-values) (define/contract (var-degree prob var) (csp? var? . -> . natural?) (for/sum ([const (in-constraints prob)] #:when (memq (var-name var) (constraint-names const))) 1)) (define/contract (domain-length var) (var? . -> . natural?) (set-count (domain var))) (define/contract (state-count csp) (csp? . -> . natural?) (for/product ([vr (in-vars csp)]) (domain-length vr))) (define/contract (mrv-degree-hybrid prob) (csp? . -> . (or/c #f var?)) (match (unassigned-vars prob) [(== empty) #false] [uvars (max-degree (make-csp (argmin* domain-length uvars) (constraints prob)))])) (define first-domain-value values) (define (no-inference prob name) prob) (define/contract (relating-only constraints names) ((listof constraint?) (listof name?) . -> . (listof constraint?)) (for*/list ([const (in-list constraints)] [cnames (in-value (constraint-names const))] #:when (and (= (length names) (length cnames)) (for/and ([name (in-list names)]) (memq name cnames)))) const)) (define (one-arity? const) (= 1 (constraint-arity const))) (define (two-arity? const) (= 2 (constraint-arity const))) (define (constraint-relates? const name) (memq name (constraint-names const))) (struct arc (name const) #:transparent) (define/contract (two-arity-constraints->arcs constraints) ((listof (and/c constraint? two-arity?)) . -> . (listof arc?)) (for*/list ([const (in-list constraints)] [name (in-list (constraint-names const))]) (arc name const))) (require sugar/debug) (define/contract (reduce-domain prob ark) (csp? arc? . -> . csp?) (match-define (arc name (constraint names constraint-proc)) ark) (match-define (list other-name) (remove name names)) (define proc (if (eq? name (first names)) ; name is on left so stays on left (λ (val other-val) (constraint-proc other-val val)))) ; otherwise reverse arg order (define (satisfies-arc? val) (for/or ([other-val (in-set (find-domain prob other-name))]) (proc val other-val))) (make-csp (for/list ([vr (in-vars prob)]) (cond [(assigned-var? vr) vr] [(eq? name (var-name vr)) (make-var name (match (filter satisfies-arc? (set->list (domain vr))) [(? empty?) (backtrack!)] [vals vals]))] [else vr])) (constraints prob))) (define/contract (terminating-at? arcs name) ((listof arc?) name? . -> . (listof arc?)) (for/list ([arc (in-list arcs)] #:when (and (memq name (constraint-names (arc-const arc))) (not (eq? name (arc-name arc))))) arc)) (define/contract (ac-3 prob ref-name) (csp? name? . -> . csp?) ;; csp is arc-consistent if every pair of variables (x y) ;; has values in their domain that satisfy every binary constraint (define checkable-names (cons ref-name (filter-not (λ (vn) (assigned-name? prob vn)) (map var-name (vars prob))))) (define starting-arcs (two-arity-constraints->arcs (for/list ([const (in-constraints prob)] #:when (and (two-arity? const) (for/and ([cname (in-list (constraint-names const))]) (memq cname checkable-names)))) const))) (for/fold ([prob prob] [arcs (sort starting-arcs < #:key (λ (a) (domain-length (find-var prob (arc-name a)))) #:cache-keys? #true)] #:result (prune-singleton-constraints prob)) ([i (in-naturals)] #:break (empty? arcs)) (match-define (cons (and first-arc (arc name _)) other-arcs) arcs) (define reduced-csp (reduce-domain prob first-arc)) (define domain-reduced? (< (domain-length (find-var reduced-csp name)) (domain-length (find-var prob name)))) (values reduced-csp (if domain-reduced? ;; revision reduced the domain, so supplement the list of arcs (remove-duplicates (append (starting-arcs . terminating-at? . name) other-arcs)) ;; revision did not reduce the domain, so keep going other-arcs)))) (define/contract (forward-check-var prob ref-name vr) (csp? name? var? . -> . var?) (match vr ;; don't check against assigned vars, or the reference var ;; (which is probably assigned but maybe not) [(? assigned-var? vr) vr] [(var (== ref-name eq?) _) vr] [(var name vals) (match ((constraints prob) . relating-only . (list ref-name name)) [(? empty?) vr] [constraints (define ref-val (first (find-domain prob ref-name))) (define new-vals (for/list ([val (in-set vals)] #:when (for/and ([const (in-list constraints)]) (match const [(constraint (list (== name eq?) _) proc) (proc val ref-val)] [(constraint _ proc) (proc ref-val val)]))) val)) (make-checked-var name new-vals (cons (cons ref-name ref-val) (match vr [(checked-variable _ _ history) history] [_ null])))])])) (define/contract (prune-singleton-constraints prob [ref-name #false]) ((csp?) ((or/c #false name?)) . ->* . csp?) (define singleton-var-names (for/list ([vr (in-vars prob)] #:when (singleton-var? vr)) (var-name vr))) (make-csp (vars prob) (for/list ([const (in-constraints prob)] #:unless (and (two-arity? const) (or (not ref-name) (constraint-relates? const ref-name)) (for/and ([cname (in-list (constraint-names const))]) (memq cname singleton-var-names)))) const))) (define/contract (forward-check prob ref-name) (csp? name? . -> . csp?) (define checked-vars (map (λ (vr) (forward-check-var prob ref-name vr)) (vars prob))) (when-debug (set! nfchecks (+ (length checked-vars) nchecks))) ;; conflict-set will be empty if there are no empty domains (as we would hope) (define conflict-set (for/list ([cvr (in-list checked-vars)] #:when (set-empty? (domain cvr))) (history cvr))) ;; for conflict-directed backjumping it's essential to forward-check ALL vars ;; (even after an empty domain is generated) and combine their conflicts ;; so we can discover the *most recent past var* that could be the culprit. If we just bail out at the first conflict , we may backjump too far based on its history ;; (and thereby miss parts of the search tree) (unless (empty? conflict-set) (backtrack! conflict-set)) ;; Discard constraints that have produced singleton domains ;; (they have no further use) (prune-singleton-constraints (make-csp checked-vars (constraints prob)) ref-name)) (define/contract (constraint-checkable? const names) (constraint? (listof name?) . -> . any/c) ;; constraint is checkable if all constraint names ;; are in target list of names. (for/and ([cname (in-list (constraint-names const))]) (memq cname names))) (define/contract (constraint-arity const) (constraint? . -> . natural?) (length (constraint-names const))) (define/contract (singleton-var? var) (var? . -> . boolean?) (= 1 (domain-length var))) (define/contract (check-constraints prob [mandatory-names #f] #:conflicts [conflict-count? #f]) ((csp?) ((listof name?) #:conflicts boolean?) . ->* . (or/c csp? natural?)) (define assigned-varnames (map var-name (assigned-vars prob))) (define-values (checkable-consts other-consts) (partition (λ (const) (and (constraint-checkable? const assigned-varnames) (or (not mandatory-names) (for/and ([name (in-list mandatory-names)]) (constraint-relates? const name))))) (constraints prob))) (cond [conflict-count? (define conflict-count (for/sum ([constraint (in-list checkable-consts)] #:unless (constraint prob)) 1)) (when-debug (set! nchecks (+ conflict-count nchecks))) conflict-count] [else (for ([(constraint idx) (in-indexed checkable-consts)] #:unless (constraint prob)) (when-debug (set! nchecks (+ (add1 idx) nchecks))) (backtrack!)) ;; discard checked constraints, since they have no further reason to live (make-csp (vars prob) other-consts)])) (define/contract (make-nodes-consistent prob) (csp? . -> . csp?) (define-values (unary-constraints other-constraints) (partition one-arity? (constraints prob))) (if (empty? unary-constraints) prob (make-csp (for/list ([vr (in-vars prob)]) (match-define (var name vals) vr) (define name-constraints (filter (λ (const) (constraint-relates? const name)) unary-constraints)) (make-var name (for/list ([val (in-set vals)] #:when (for/and ([const (in-list name-constraints)]) ((constraint-proc const) val))) val))) other-constraints))) (define ((make-hist-proc assocs) . xs) (not (for/and ([x (in-list xs)] [val (in-list (map cdr assocs))]) (equal? x val)))) (struct solver (generator kill) #:transparent #:property prop:procedure 0) (define/contract (backtracking-solver prob #:select-variable [select-unassigned-variable (or (current-select-variable) first-unassigned-variable)] #:order-values [order-domain-values (or (current-order-values) first-domain-value)] #:inference [inference (or (current-inference) no-inference)]) ((csp?) (#:select-variable procedure? #:order-values procedure? #:inference procedure?) . ->* . solver?) (solver (generator () (define starting-state-count (state-count prob)) (define states-examined 0) (define reduce-arity-proc (if (current-arity-reduction) reduce-constraint-arity values)) (let loop ([prob ((if (current-node-consistency) make-nodes-consistent values) prob)]) (match (select-unassigned-variable prob) [#false (yield prob)] [(var name domain) (define (wants-backtrack? exn) (and (backtrack? exn) (or (let ([bths (backtrack-histories exn)]) (or (empty? bths) (for*/or ([bth (in-list bths)] [rec (in-list bth)]) (eq? name (car rec)))))))) (for/fold ([conflicts null] #:result (void)) ([val (in-list (order-domain-values (set->list domain)))]) (with-handlers ([wants-backtrack? (λ (bt) (define bths (backtrack-histories bt)) (append conflicts (remq name (remove-duplicates (for*/list ([bth (in-list bths)] [rec (in-list bth)]) (car rec)) eq?))))]) (let* ([prob (assign-val prob name val)] ;; reduce constraints before inference, ;; to create more forward-checkable (binary) constraints [prob (reduce-arity-proc prob)] [prob (inference prob name)] [prob (check-constraints prob)]) (loop prob)) ;; conflicts goes inside the handler expression ;; so raises can supersede it conflicts))]))) void)) (define/contract (random-pick xs) ((non-empty-listof any/c) . -> . any/c) (match xs [(list x) x] [(app set->list xs) (list-ref xs (random (length xs)))])) (define (assign-random-vals prob) (for/fold ([new-csp prob]) ([name (in-var-names prob)]) (assign-val new-csp name (random-pick (find-domain prob name))))) (define (make-min-conflcts-thread prob-start thread-count max-steps [main-thread (current-thread)]) (thread (λ () (let loop () ;; Generate a complete assignment for all variables (probably with conflicts) (for/fold ([prob (assign-random-vals prob-start)]) ([nth-step (in-range max-steps)]) ;; Now repeatedly choose a random conflicted variable and change it (match (conflicted-variable-names prob) [(? empty?) (thread-send main-thread prob) (loop)] [names (define name (random-pick names)) (define val (min-conflicts-value prob name (find-domain prob-start name))) (assign-val prob name val)])))))) (define/contract (min-conflicts-solver prob [max-steps 100]) ((csp?) (exact-positive-integer?) . ->* . solver?) ; todo: what is ideal thread count? (define threads (for/list ([thread-count (or (current-thread-count) 1)]) (make-min-conflcts-thread prob thread-count max-steps))) (solver (generator () (let loop () (yield (thread-receive)) (loop))) (λ () (for-each kill-thread threads) ))) (define/contract (optimal-stop-min proc xs) (procedure? (listof any/c) . -> . any/c) ;; coefficient from ;; /~tom/Stopping/sr2.pdf (define optimal-stopping-coefficient .458) (define-values (sample candidates) (split-at xs (inexact->exact (floor (* optimal-stopping-coefficient (length xs)))))) (define threshold (argmin proc sample)) (or (for/first ([candidate (in-list candidates)] #:when (<= (proc candidate) threshold)) candidate) (last candidates))) (define/contract (conflicted-variable-names prob) (csp? . -> . (listof name?)) ;; Return a list of variables in current assignment that are conflicted (for/list ([name (in-var-names prob)] #:when (positive? (nconflicts prob name))) name)) (define/contract (min-conflicts-value prob name vals) (csp? name? (listof any/c) . -> . any/c) ;; Return the value that will give var the least number of conflicts (define vals-by-conflict (sort (set->list vals) < #:key (λ (val) (nconflicts prob name val)) #:cache-keys? #true)) (for/first ([val (in-list vals-by-conflict)] #:unless (equal? val (first (find-domain prob name)))) ;; but change the value val)) (define no-value-sig (gensym)) (define/contract (nconflicts prob name [val no-value-sig]) ((csp? name?) (any/c) . ->* . natural?) How many conflicts var : assignment has with other variables . (check-constraints (if (eq? val no-value-sig) prob (assign-val prob name val)) (list name) #:conflicts #true)) (define/contract (csp->assocs prob [keys #f]) ((csp?) ((listof name?)) . ->* . (listof (cons/c name? any/c))) (define assocs (for/list ([vr (in-vars prob)]) (match vr [(var name (list val)) (cons name val)]))) (if keys (for/list ([key (in-list keys)]) (assq key assocs)) assocs)) (define/contract (combine-csps probs) ((listof csp?) . -> . csp?) (make-csp (apply append (map vars probs)) (apply append (map csp-constraints probs)))) (define/contract (extract-subcsp prob names) (csp? (listof name?) . -> . csp?) (make-csp (for/list ([vr (in-vars prob)] #:when (memq (var-name vr) names)) vr) (for/list ([const (in-constraints prob)] #:when (constraint-checkable? const names)) const))) (define (decompose-prob prob) decompose into independent csps . ` cc ` determines " connected components " (if (current-decompose) (for/list ([nodeset (in-list (cc (csp->graph prob)))]) (extract-subcsp prob nodeset)) (list prob))) (define (make-solution-generator prob [max-solutions #false]) (generator () (define subprobs (decompose-prob prob)) (define solgens (map (current-solver) subprobs)) (define solstreams (for/list ([solgen (in-list solgens)]) (for/stream ([sol (in-producer solgen (void))]) sol))) (for ([solution-pieces (in-cartesian solstreams)] [count (in-range (or max-solutions +inf.0))]) (yield (combine-csps solution-pieces))) (for-each solver-kill solgens))) (define-syntax (in-solutions stx) (syntax-case stx () [(_ PROB) #'(in-solutions PROB #false)] [(_ PROB MAX-SOLUTIONS) #'(in-producer (make-solution-generator PROB MAX-SOLUTIONS) (void))])) (define/contract (solve* prob [max-solutions #false] #:finish-proc [finish-proc (λ (p) (csp->assocs p (map var-name (vars prob))))] #:solver [solver #f]) ((csp?) (natural? #:finish-proc procedure? #:solver procedure?) . ->* . (listof any/c)) (when-debug (reset-nassns!) (reset-nfchecks!) (reset-nchecks!)) (parameterize ([current-solver (or solver (current-solver))]) (for/list ([sol (in-solutions prob max-solutions)]) (finish-proc sol)))) (define/contract (solve prob #:finish-proc [finish-proc (λ (p) (csp->assocs p (map var-name (vars prob))))] #:solver [solver #f]) ((csp?) (#:finish-proc procedure? #:solver procedure?) . ->* . (or/c #false any/c)) (match (solve* prob 1 #:finish-proc finish-proc #:solver solver) [(list solution) solution] [_ #false])) (define (<> a b) (not (= a b))) (define (neq? a b) (not (eq? a b))) (define current-select-variable (make-parameter #f)) (define current-order-values (make-parameter #f)) (define current-inference (make-parameter forward-check)) (define current-solver (make-parameter backtracking-solver)) (define current-decompose (make-parameter #t)) (define current-thread-count (make-parameter 4)) (define current-node-consistency (make-parameter #f)) (define current-arity-reduction (make-parameter #t)) (define current-learning (make-parameter #f))
null
https://raw.githubusercontent.com/mbutterick/typesetting/93a682a1581f3c1564b6f39fc05a5fe1a09a5ccb/csp/csp/hacs.rkt
racket
apply proc in many-to-many style anything is ok for now pattern is mix of values and boxed symbols (indicating variables to persist) use boxes here as cheap way to distinguish id symbols from value symbols return all elements that have min value. return all elements that have max value. name is on left otherwise reverse arg order csp is arc-consistent if every pair of variables (x y) has values in their domain that satisfy every binary constraint revision reduced the domain, so supplement the list of arcs revision did not reduce the domain, so keep going don't check against assigned vars, or the reference var (which is probably assigned but maybe not) conflict-set will be empty if there are no empty domains (as we would hope) for conflict-directed backjumping it's essential to forward-check ALL vars (even after an empty domain is generated) and combine their conflicts so we can discover the *most recent past var* that could be the culprit. (and thereby miss parts of the search tree) Discard constraints that have produced singleton domains (they have no further use) constraint is checkable if all constraint names are in target list of names. discard checked constraints, since they have no further reason to live reduce constraints before inference, to create more forward-checkable (binary) constraints conflicts goes inside the handler expression so raises can supersede it Generate a complete assignment for all variables (probably with conflicts) Now repeatedly choose a random conflicted variable and change it todo: what is ideal thread count? coefficient from /~tom/Stopping/sr2.pdf Return a list of variables in current assignment that are conflicted Return the value that will give var the least number of conflicts but change the value
#lang debug racket (require racket/generator graph racket/set) (provide (except-out (all-defined-out) define/contract)) (define-syntax-rule (define/contract EXPR CONTRACT . BODY) (define EXPR . BODY)) (define-syntax when-debug (let () (define debug #t) (if debug (make-rename-transformer #'begin) (λ (stx) (syntax-case stx () [(_ . rest) #'(void)]))))) (define (print-debug-info) (when-debug (displayln (format "assignments: ~a forward checks: ~a checks: ~a " nassns nchecks nfchecks)))) (define-syntax-rule (in-cartesian x) (in-generator (let ([argss x]) (let loop ([argss argss][acc empty]) (if (null? argss) (yield (reverse acc)) (for ([arg (in-stream (car argss))]) (loop (cdr argss) (cons arg acc)))))))) (struct csp (vars constraints) #:mutable #:transparent) (define constraints csp-constraints) (define vars csp-vars) (define-syntax-rule (in-constraints csp) (in-list (csp-constraints csp))) (define-syntax-rule (in-vars csp) (in-list (vars csp))) (define-syntax-rule (in-var-names csp) (in-list (map var-name (vars csp)))) (struct constraint (names proc) #:transparent #:property prop:procedure (λ (const prob) (unless (csp? prob) (raise-argument-error 'constraint "csp" prob)) (for/and ([args (in-cartesian (map (λ (name) (find-domain prob name)) (constraint-names const)))]) (apply (constraint-proc const) args)))) (define/contract (make-constraint [names null] [proc values]) (() ((listof name?) procedure?) . ->* . constraint?) (constraint names proc)) (define/contract (csp->graphviz prob) (csp? . -> . string?) (define g (csp->graph prob)) (graphviz g #:colors (coloring/brelaz g))) (define/contract (csp->graph prob) (csp? . -> . graph?) (for*/fold ([gr (unweighted-graph/undirected (map var-name (vars prob)))]) ([constraint (in-constraints prob)] [edge (in-combinations (constraint-names constraint) 2)]) (apply add-edge! gr edge) gr)) (struct var (name domain) #:transparent) (define domain var-domain) (struct checked-variable var (history) #:transparent) (define history checked-variable-history) (define cvar checked-variable) (define cvar? checked-variable?) (struct assigned-var var () #:transparent) (define avar assigned-var) (define avar? assigned-var?) (define/contract (make-csp [vars null] [consts null]) (() ((listof var?) (listof constraint?)) . ->* . csp?) (csp vars consts)) (define (varvals->set vals) (match vals [(list (or (? fixnum?) (? symbol?)) ...) (list->seteq vals)] [_ (list->set vals)])) (define/contract (make-var name [vals null]) ((name?) ((listof any/c)) . ->* . var?) (var name (varvals->set vals))) (define (make-checked-var name vals history) (checked-variable name (varvals->set vals) history)) (define/contract (make-var-names prefix vals [suffix ""]) ((string? (listof any/c)) ((string?)) . ->* . (listof name?)) (for/list ([val (in-list vals)]) (string->symbol (format "~a~a~a" prefix val suffix)))) (define/contract (add-vars! prob names [vals-or-procedure empty]) ((csp? (listof name?)) ((or/c (listof any/c) procedure?)) . ->* . void?) (for/fold ([vrs (vars prob)] #:result (set-csp-vars! prob vrs)) ([name (in-list names)]) (when (memq name (map var-name vrs)) (raise-argument-error 'add-vars! "var that doesn't already exist" name)) (append vrs (list (make-var name (match vals-or-procedure [(? procedure? proc) (proc)] [vals vals])))))) (define/contract (add-var! prob name [vals-or-procedure empty]) ((csp? name?) ((or/c (listof any/c) procedure?)) . ->* . void?) (add-vars! prob (list name) vals-or-procedure)) (define/contract (add-constraints! prob proc namess [proc-name #false] #:caller [caller-id 'add-constraints!]) ((csp? procedure? (listof (listof name?))) ((or/c #false name?)) . ->* . void?) (unless (procedure? proc) (raise-argument-error caller-id "procedure" proc)) (unless (and (list? namess) (andmap list? namess)) (raise-argument-error caller-id "list of lists of names" namess)) (set-csp-constraints! prob (append (constraints prob) (for/list ([names (in-list namess)]) (for ([name (in-list names)]) (check-name-in-csp! 'add-constraints! prob name)) (make-constraint names (if proc-name (procedure-rename proc proc-name) proc)))))) (define/contract (add-pairwise-constraint! prob proc names [proc-name #false]) ((csp? procedure? (listof name?)) (name?) . ->* . void?) (unless (list? names) (raise-argument-error 'add-pairwise-constraint! "list of names" names)) (add-constraints! prob proc (combinations names 2) proc-name #:caller 'add-pairwise-constraint!)) (define/contract (add-transitive-constraint! prob proc names [proc-name #false]) ((csp? procedure? (listof name?)) (name?) . ->* . void?) (unless (and (list? names) (>= (length names) 2)) (raise-argument-error 'add-transitive-constraint! "list of two or more names" names)) (add-constraints! prob proc (for/list ([name (in-list names)] [next (in-list (cdr names))]) (list name next)) proc-name #:caller 'add-transitive-constraint!)) (define/contract (add-constraint! prob proc names [proc-name #false]) ((csp? procedure? (listof name?)) (name?) . ->* . void?) (unless (list? names) (raise-argument-error 'add-constraint! "list of names" names)) (add-constraints! prob proc (list names) proc-name #:caller 'add-constraint!)) (define/contract (alldiff x y) (any/c any/c . -> . boolean?) (not (= x y))) (define alldiff= alldiff) (define (add-all-diff-constraint! prob [names (map var-name (csp-vars prob))] #:same [equal-proc equal?]) (add-pairwise-constraint! prob (λ (x y) (not (equal-proc x y))) names (string->symbol (format "all-diff-~a" (object-name equal-proc))))) (struct backtrack (histories) #:transparent) (define (backtrack! [names null]) (raise (backtrack names))) (define/contract (check-name-in-csp! caller prob name) (symbol? csp? name? . -> . void?) (define names (map var-name (vars prob))) (unless (memq name names) (raise-argument-error caller (format "one of these existing csp var names: ~v" names) name))) (define/contract (find-var prob name) (csp? name? . -> . var?) (check-name-in-csp! 'find-var prob name) (for/first ([vr (in-vars prob)] #:when (eq? name (var-name vr))) vr)) (define/contract (find-domain prob name) (csp? name? . -> . (listof any/c)) (check-name-in-csp! 'find-domain prob name) (domain (find-var prob name))) (define order-domain-values values) (define/contract (assigned-name? prob name) (csp? name? . -> . any/c) (assigned-var? (find-var prob name))) (define/contract (reduce-function-arity proc pattern) (procedure? (listof any/c) . -> . procedure?) (unless (match (procedure-arity proc) [(arity-at-least val) (<= val (length pattern))] [(? number? val) (= val (length pattern))]) (raise-argument-error 'reduce-function-arity (format "list of length ~a, same as procedure arity" (procedure-arity proc)) pattern)) (define reduced-arity-name (string->symbol (format "reduced-arity-~a" (object-name proc)))) (define-values (boxed-id-names vals) (partition box? pattern)) (define new-arity (length boxed-id-names)) (procedure-rename (λ xs (unless (= (length xs) new-arity) (apply raise-arity-error reduced-arity-name new-arity xs)) (apply proc (for/fold ([acc empty] [xs xs] [vals vals] #:result (reverse acc)) ([pat-item (in-list pattern)]) (if (box? pat-item) (values (cons (car xs) acc) (cdr xs) vals) (values (cons (car vals) acc) xs (cdr vals)))))) reduced-arity-name)) (define/contract (reduce-constraint-arity prob [minimum-arity 3]) ((csp?) ((or/c #false natural?)) . ->* . csp?) (define assigned? (curry assigned-name? prob)) (define (partially-assigned? constraint) (ormap assigned? (constraint-names constraint))) (make-csp (vars prob) (for/list ([const (in-constraints prob)]) (cond no point reducing 2 - arity functions because they will be consumed by forward checking [(and (or (not minimum-arity) (<= minimum-arity (constraint-arity const))) (partially-assigned? const)) (match-define (constraint cnames proc) const) (define arity-reduction-pattern (for/list ([cname (in-list cnames)]) (if (assigned? cname) (first (find-domain prob cname)) (box cname)))) (constraint (filter-not assigned? cnames) (reduce-function-arity proc arity-reduction-pattern))] [else const])))) (define nassns 0) (define nfchecks 0) (define nchecks 0) (define (reset-nassns!) (set! nassns 0)) (define (reset-nfchecks!) (set! nfchecks 0)) (define (reset-nchecks!) (set! nchecks 0)) (define/contract (assign-val prob name val) (csp? name? any/c . -> . csp?) (begin0 (make-csp (for/list ([vr (in-vars prob)]) (if (eq? name (var-name vr)) (assigned-var name (list val)) vr)) (constraints prob)) (when-debug (set! nassns (add1 nassns))))) (define/contract (assigned-vars prob [invert? #f]) ((csp?) (any/c) . ->* . (listof var?)) ((if invert? filter-not filter) assigned-var? (vars prob))) (define/contract (unassigned-vars prob) (csp? . -> . (listof var?)) (assigned-vars prob 'invert)) (define/contract (first-unassigned-variable csp) (csp? . -> . (or/c #false (and/c var? (not/c assigned-var?)))) (match (unassigned-vars csp) [(== empty) #false] [uvars (first uvars)])) (define/contract (argmin* proc xs [max-style? #f]) ((procedure? (listof any/c)) (any/c) . ->* . (listof any/c)) (match xs [(== empty) xs] [(list x) xs] [xs (define vals (map proc xs)) (define target-val (apply (if max-style? max min) vals)) (for/list ([x (in-list xs)] [val (in-list vals)] #:when (= val target-val)) x)])) (define/contract (argmax* proc xs) (procedure? (listof any/c) . -> . (listof any/c)) (argmin* proc xs 'max-mode!)) (define/contract (minimum-remaining-values prob) (csp? . -> . (or/c #false (and/c var? (not/c assigned-var?)))) (match (unassigned-vars prob) [(== empty) #false] [uvars (random-pick (argmin* domain-length uvars))])) (define/contract (max-degree prob) (csp? . -> . (or/c #false (and/c var? (not/c assigned-var?)))) (match (unassigned-vars prob) [(== empty) #false] [uvars (random-pick (argmax* (λ (var) (var-degree prob var)) uvars))])) (define mrv minimum-remaining-values) (define/contract (var-degree prob var) (csp? var? . -> . natural?) (for/sum ([const (in-constraints prob)] #:when (memq (var-name var) (constraint-names const))) 1)) (define/contract (domain-length var) (var? . -> . natural?) (set-count (domain var))) (define/contract (state-count csp) (csp? . -> . natural?) (for/product ([vr (in-vars csp)]) (domain-length vr))) (define/contract (mrv-degree-hybrid prob) (csp? . -> . (or/c #f var?)) (match (unassigned-vars prob) [(== empty) #false] [uvars (max-degree (make-csp (argmin* domain-length uvars) (constraints prob)))])) (define first-domain-value values) (define (no-inference prob name) prob) (define/contract (relating-only constraints names) ((listof constraint?) (listof name?) . -> . (listof constraint?)) (for*/list ([const (in-list constraints)] [cnames (in-value (constraint-names const))] #:when (and (= (length names) (length cnames)) (for/and ([name (in-list names)]) (memq name cnames)))) const)) (define (one-arity? const) (= 1 (constraint-arity const))) (define (two-arity? const) (= 2 (constraint-arity const))) (define (constraint-relates? const name) (memq name (constraint-names const))) (struct arc (name const) #:transparent) (define/contract (two-arity-constraints->arcs constraints) ((listof (and/c constraint? two-arity?)) . -> . (listof arc?)) (for*/list ([const (in-list constraints)] [name (in-list (constraint-names const))]) (arc name const))) (require sugar/debug) (define/contract (reduce-domain prob ark) (csp? arc? . -> . csp?) (match-define (arc name (constraint names constraint-proc)) ark) (match-define (list other-name) (remove name names)) so stays on left (define (satisfies-arc? val) (for/or ([other-val (in-set (find-domain prob other-name))]) (proc val other-val))) (make-csp (for/list ([vr (in-vars prob)]) (cond [(assigned-var? vr) vr] [(eq? name (var-name vr)) (make-var name (match (filter satisfies-arc? (set->list (domain vr))) [(? empty?) (backtrack!)] [vals vals]))] [else vr])) (constraints prob))) (define/contract (terminating-at? arcs name) ((listof arc?) name? . -> . (listof arc?)) (for/list ([arc (in-list arcs)] #:when (and (memq name (constraint-names (arc-const arc))) (not (eq? name (arc-name arc))))) arc)) (define/contract (ac-3 prob ref-name) (csp? name? . -> . csp?) (define checkable-names (cons ref-name (filter-not (λ (vn) (assigned-name? prob vn)) (map var-name (vars prob))))) (define starting-arcs (two-arity-constraints->arcs (for/list ([const (in-constraints prob)] #:when (and (two-arity? const) (for/and ([cname (in-list (constraint-names const))]) (memq cname checkable-names)))) const))) (for/fold ([prob prob] [arcs (sort starting-arcs < #:key (λ (a) (domain-length (find-var prob (arc-name a)))) #:cache-keys? #true)] #:result (prune-singleton-constraints prob)) ([i (in-naturals)] #:break (empty? arcs)) (match-define (cons (and first-arc (arc name _)) other-arcs) arcs) (define reduced-csp (reduce-domain prob first-arc)) (define domain-reduced? (< (domain-length (find-var reduced-csp name)) (domain-length (find-var prob name)))) (values reduced-csp (if domain-reduced? (remove-duplicates (append (starting-arcs . terminating-at? . name) other-arcs)) other-arcs)))) (define/contract (forward-check-var prob ref-name vr) (csp? name? var? . -> . var?) (match vr [(? assigned-var? vr) vr] [(var (== ref-name eq?) _) vr] [(var name vals) (match ((constraints prob) . relating-only . (list ref-name name)) [(? empty?) vr] [constraints (define ref-val (first (find-domain prob ref-name))) (define new-vals (for/list ([val (in-set vals)] #:when (for/and ([const (in-list constraints)]) (match const [(constraint (list (== name eq?) _) proc) (proc val ref-val)] [(constraint _ proc) (proc ref-val val)]))) val)) (make-checked-var name new-vals (cons (cons ref-name ref-val) (match vr [(checked-variable _ _ history) history] [_ null])))])])) (define/contract (prune-singleton-constraints prob [ref-name #false]) ((csp?) ((or/c #false name?)) . ->* . csp?) (define singleton-var-names (for/list ([vr (in-vars prob)] #:when (singleton-var? vr)) (var-name vr))) (make-csp (vars prob) (for/list ([const (in-constraints prob)] #:unless (and (two-arity? const) (or (not ref-name) (constraint-relates? const ref-name)) (for/and ([cname (in-list (constraint-names const))]) (memq cname singleton-var-names)))) const))) (define/contract (forward-check prob ref-name) (csp? name? . -> . csp?) (define checked-vars (map (λ (vr) (forward-check-var prob ref-name vr)) (vars prob))) (when-debug (set! nfchecks (+ (length checked-vars) nchecks))) (define conflict-set (for/list ([cvr (in-list checked-vars)] #:when (set-empty? (domain cvr))) (history cvr))) If we just bail out at the first conflict , we may backjump too far based on its history (unless (empty? conflict-set) (backtrack! conflict-set)) (prune-singleton-constraints (make-csp checked-vars (constraints prob)) ref-name)) (define/contract (constraint-checkable? const names) (constraint? (listof name?) . -> . any/c) (for/and ([cname (in-list (constraint-names const))]) (memq cname names))) (define/contract (constraint-arity const) (constraint? . -> . natural?) (length (constraint-names const))) (define/contract (singleton-var? var) (var? . -> . boolean?) (= 1 (domain-length var))) (define/contract (check-constraints prob [mandatory-names #f] #:conflicts [conflict-count? #f]) ((csp?) ((listof name?) #:conflicts boolean?) . ->* . (or/c csp? natural?)) (define assigned-varnames (map var-name (assigned-vars prob))) (define-values (checkable-consts other-consts) (partition (λ (const) (and (constraint-checkable? const assigned-varnames) (or (not mandatory-names) (for/and ([name (in-list mandatory-names)]) (constraint-relates? const name))))) (constraints prob))) (cond [conflict-count? (define conflict-count (for/sum ([constraint (in-list checkable-consts)] #:unless (constraint prob)) 1)) (when-debug (set! nchecks (+ conflict-count nchecks))) conflict-count] [else (for ([(constraint idx) (in-indexed checkable-consts)] #:unless (constraint prob)) (when-debug (set! nchecks (+ (add1 idx) nchecks))) (backtrack!)) (make-csp (vars prob) other-consts)])) (define/contract (make-nodes-consistent prob) (csp? . -> . csp?) (define-values (unary-constraints other-constraints) (partition one-arity? (constraints prob))) (if (empty? unary-constraints) prob (make-csp (for/list ([vr (in-vars prob)]) (match-define (var name vals) vr) (define name-constraints (filter (λ (const) (constraint-relates? const name)) unary-constraints)) (make-var name (for/list ([val (in-set vals)] #:when (for/and ([const (in-list name-constraints)]) ((constraint-proc const) val))) val))) other-constraints))) (define ((make-hist-proc assocs) . xs) (not (for/and ([x (in-list xs)] [val (in-list (map cdr assocs))]) (equal? x val)))) (struct solver (generator kill) #:transparent #:property prop:procedure 0) (define/contract (backtracking-solver prob #:select-variable [select-unassigned-variable (or (current-select-variable) first-unassigned-variable)] #:order-values [order-domain-values (or (current-order-values) first-domain-value)] #:inference [inference (or (current-inference) no-inference)]) ((csp?) (#:select-variable procedure? #:order-values procedure? #:inference procedure?) . ->* . solver?) (solver (generator () (define starting-state-count (state-count prob)) (define states-examined 0) (define reduce-arity-proc (if (current-arity-reduction) reduce-constraint-arity values)) (let loop ([prob ((if (current-node-consistency) make-nodes-consistent values) prob)]) (match (select-unassigned-variable prob) [#false (yield prob)] [(var name domain) (define (wants-backtrack? exn) (and (backtrack? exn) (or (let ([bths (backtrack-histories exn)]) (or (empty? bths) (for*/or ([bth (in-list bths)] [rec (in-list bth)]) (eq? name (car rec)))))))) (for/fold ([conflicts null] #:result (void)) ([val (in-list (order-domain-values (set->list domain)))]) (with-handlers ([wants-backtrack? (λ (bt) (define bths (backtrack-histories bt)) (append conflicts (remq name (remove-duplicates (for*/list ([bth (in-list bths)] [rec (in-list bth)]) (car rec)) eq?))))]) (let* ([prob (assign-val prob name val)] [prob (reduce-arity-proc prob)] [prob (inference prob name)] [prob (check-constraints prob)]) (loop prob)) conflicts))]))) void)) (define/contract (random-pick xs) ((non-empty-listof any/c) . -> . any/c) (match xs [(list x) x] [(app set->list xs) (list-ref xs (random (length xs)))])) (define (assign-random-vals prob) (for/fold ([new-csp prob]) ([name (in-var-names prob)]) (assign-val new-csp name (random-pick (find-domain prob name))))) (define (make-min-conflcts-thread prob-start thread-count max-steps [main-thread (current-thread)]) (thread (λ () (let loop () (for/fold ([prob (assign-random-vals prob-start)]) ([nth-step (in-range max-steps)]) (match (conflicted-variable-names prob) [(? empty?) (thread-send main-thread prob) (loop)] [names (define name (random-pick names)) (define val (min-conflicts-value prob name (find-domain prob-start name))) (assign-val prob name val)])))))) (define/contract (min-conflicts-solver prob [max-steps 100]) ((csp?) (exact-positive-integer?) . ->* . solver?) (define threads (for/list ([thread-count (or (current-thread-count) 1)]) (make-min-conflcts-thread prob thread-count max-steps))) (solver (generator () (let loop () (yield (thread-receive)) (loop))) (λ () (for-each kill-thread threads) ))) (define/contract (optimal-stop-min proc xs) (procedure? (listof any/c) . -> . any/c) (define optimal-stopping-coefficient .458) (define-values (sample candidates) (split-at xs (inexact->exact (floor (* optimal-stopping-coefficient (length xs)))))) (define threshold (argmin proc sample)) (or (for/first ([candidate (in-list candidates)] #:when (<= (proc candidate) threshold)) candidate) (last candidates))) (define/contract (conflicted-variable-names prob) (csp? . -> . (listof name?)) (for/list ([name (in-var-names prob)] #:when (positive? (nconflicts prob name))) name)) (define/contract (min-conflicts-value prob name vals) (csp? name? (listof any/c) . -> . any/c) (define vals-by-conflict (sort (set->list vals) < #:key (λ (val) (nconflicts prob name val)) #:cache-keys? #true)) (for/first ([val (in-list vals-by-conflict)] val)) (define no-value-sig (gensym)) (define/contract (nconflicts prob name [val no-value-sig]) ((csp? name?) (any/c) . ->* . natural?) How many conflicts var : assignment has with other variables . (check-constraints (if (eq? val no-value-sig) prob (assign-val prob name val)) (list name) #:conflicts #true)) (define/contract (csp->assocs prob [keys #f]) ((csp?) ((listof name?)) . ->* . (listof (cons/c name? any/c))) (define assocs (for/list ([vr (in-vars prob)]) (match vr [(var name (list val)) (cons name val)]))) (if keys (for/list ([key (in-list keys)]) (assq key assocs)) assocs)) (define/contract (combine-csps probs) ((listof csp?) . -> . csp?) (make-csp (apply append (map vars probs)) (apply append (map csp-constraints probs)))) (define/contract (extract-subcsp prob names) (csp? (listof name?) . -> . csp?) (make-csp (for/list ([vr (in-vars prob)] #:when (memq (var-name vr) names)) vr) (for/list ([const (in-constraints prob)] #:when (constraint-checkable? const names)) const))) (define (decompose-prob prob) decompose into independent csps . ` cc ` determines " connected components " (if (current-decompose) (for/list ([nodeset (in-list (cc (csp->graph prob)))]) (extract-subcsp prob nodeset)) (list prob))) (define (make-solution-generator prob [max-solutions #false]) (generator () (define subprobs (decompose-prob prob)) (define solgens (map (current-solver) subprobs)) (define solstreams (for/list ([solgen (in-list solgens)]) (for/stream ([sol (in-producer solgen (void))]) sol))) (for ([solution-pieces (in-cartesian solstreams)] [count (in-range (or max-solutions +inf.0))]) (yield (combine-csps solution-pieces))) (for-each solver-kill solgens))) (define-syntax (in-solutions stx) (syntax-case stx () [(_ PROB) #'(in-solutions PROB #false)] [(_ PROB MAX-SOLUTIONS) #'(in-producer (make-solution-generator PROB MAX-SOLUTIONS) (void))])) (define/contract (solve* prob [max-solutions #false] #:finish-proc [finish-proc (λ (p) (csp->assocs p (map var-name (vars prob))))] #:solver [solver #f]) ((csp?) (natural? #:finish-proc procedure? #:solver procedure?) . ->* . (listof any/c)) (when-debug (reset-nassns!) (reset-nfchecks!) (reset-nchecks!)) (parameterize ([current-solver (or solver (current-solver))]) (for/list ([sol (in-solutions prob max-solutions)]) (finish-proc sol)))) (define/contract (solve prob #:finish-proc [finish-proc (λ (p) (csp->assocs p (map var-name (vars prob))))] #:solver [solver #f]) ((csp?) (#:finish-proc procedure? #:solver procedure?) . ->* . (or/c #false any/c)) (match (solve* prob 1 #:finish-proc finish-proc #:solver solver) [(list solution) solution] [_ #false])) (define (<> a b) (not (= a b))) (define (neq? a b) (not (eq? a b))) (define current-select-variable (make-parameter #f)) (define current-order-values (make-parameter #f)) (define current-inference (make-parameter forward-check)) (define current-solver (make-parameter backtracking-solver)) (define current-decompose (make-parameter #t)) (define current-thread-count (make-parameter 4)) (define current-node-consistency (make-parameter #f)) (define current-arity-reduction (make-parameter #t)) (define current-learning (make-parameter #f))
2379317e07a433ec8200968a8fc2caad5157eef0a70fcff6a8e8663a53357e58
imrehg/ypsilon
build-boot-fasl.scm
Ypsilon Scheme System Copyright ( c ) 2004 - 2008 Y.FUJITA , LittleWing Company Limited . See license.txt for terms and conditions of use . #!core (begin (import (core primitives) (core destructuring) (core optimize) (core parameters) (core io) (core files)) (define put-fasl (parameterize ((current-environment (system-environment))) (top-level-value 'put-fasl))) (define target-file-name "bootimage.vmi") (define prefix-file '("./boot/first-load.scm")) (define files '("./boot/r6rs-aux.scm" "./boot/common.scm" "./boot/parameter.scm" "./boot/macro/initial.scm" "./boot/macro/expand.scm" "./boot/macro/base.scm" "./boot/macro/derived.scm" "./boot/macro/quasi.scm" "./boot/macro/synpat.scm" "./boot/macro/syntmp.scm" "./boot/macro/synrule.scm" "./boot/macro/syncase.scm" "./boot/macro/library.scm" "./boot/macro/synenv.scm" "./boot/compile.scm" "./boot/dynamic-wind.scm" "./boot/exception.scm" "./boot/record.scm" "./boot/condition.scm" "./boot/pp.scm" "./boot/eval.scm" "./boot/interaction.scm" "./boot/libraries.scm")) (define compile-to (lambda (in out) (let ((obj (read in))) (or (eof-object? obj) (begin (set! obj (compile obj)) (put-fasl out obj) (compile-to in out)))))) (define concat-file (lambda (in out) (let ((obj (read in))) (or (eof-object? obj) (begin (put-datum out obj) (concat-file in out)))))) (define temp-port (transcoded-port (open-temporary-file-port) (native-transcoder))) (format #t ";; build ~a/~a~!" (current-directory) target-file-name) (parameterize ((backtrace #f) (pretty-print-unwrap-syntax #f) (coreform-optimize #t)) (call-with-port (open-file-output-port target-file-name (file-options no-fail) (buffer-mode block) (native-transcoder)) (lambda (output) (for-each (lambda (file) (let ((path file)) (format #t "~%;; compiling ~a~!" path) (compile-to (open-input-file path) output))) prefix-file) (format temp-port "(begin~%") (for-each (lambda (file) (let ((path file)) (format #t "~%;; concat ~a~!" path) (concat-file (open-input-file path) temp-port))) files) (format temp-port ")~%") (set-port-position! temp-port 0) (format #t "~%;; compiling ... ~%~!") (compile-to temp-port output)))) ) ;[end]
null
https://raw.githubusercontent.com/imrehg/ypsilon/e57a06ef5c66c1a88905b2be2fa791fa29848514/heap/build-boot-fasl.scm
scheme
[end]
Ypsilon Scheme System Copyright ( c ) 2004 - 2008 Y.FUJITA , LittleWing Company Limited . See license.txt for terms and conditions of use . #!core (begin (import (core primitives) (core destructuring) (core optimize) (core parameters) (core io) (core files)) (define put-fasl (parameterize ((current-environment (system-environment))) (top-level-value 'put-fasl))) (define target-file-name "bootimage.vmi") (define prefix-file '("./boot/first-load.scm")) (define files '("./boot/r6rs-aux.scm" "./boot/common.scm" "./boot/parameter.scm" "./boot/macro/initial.scm" "./boot/macro/expand.scm" "./boot/macro/base.scm" "./boot/macro/derived.scm" "./boot/macro/quasi.scm" "./boot/macro/synpat.scm" "./boot/macro/syntmp.scm" "./boot/macro/synrule.scm" "./boot/macro/syncase.scm" "./boot/macro/library.scm" "./boot/macro/synenv.scm" "./boot/compile.scm" "./boot/dynamic-wind.scm" "./boot/exception.scm" "./boot/record.scm" "./boot/condition.scm" "./boot/pp.scm" "./boot/eval.scm" "./boot/interaction.scm" "./boot/libraries.scm")) (define compile-to (lambda (in out) (let ((obj (read in))) (or (eof-object? obj) (begin (set! obj (compile obj)) (put-fasl out obj) (compile-to in out)))))) (define concat-file (lambda (in out) (let ((obj (read in))) (or (eof-object? obj) (begin (put-datum out obj) (concat-file in out)))))) (define temp-port (transcoded-port (open-temporary-file-port) (native-transcoder))) (format #t ";; build ~a/~a~!" (current-directory) target-file-name) (parameterize ((backtrace #f) (pretty-print-unwrap-syntax #f) (coreform-optimize #t)) (call-with-port (open-file-output-port target-file-name (file-options no-fail) (buffer-mode block) (native-transcoder)) (lambda (output) (for-each (lambda (file) (let ((path file)) (format #t "~%;; compiling ~a~!" path) (compile-to (open-input-file path) output))) prefix-file) (format temp-port "(begin~%") (for-each (lambda (file) (let ((path file)) (format #t "~%;; concat ~a~!" path) (concat-file (open-input-file path) temp-port))) files) (format temp-port ")~%") (set-port-position! temp-port 0) (format #t "~%;; compiling ... ~%~!") (compile-to temp-port output))))
8136f514f89564e7a1c9f486948840016f35c7d15dbf172b96fa3bb96212a08e
seckcoder/iu_c311
interp.rkt
; interpreter of let-lang #lang eopl (require "../base/utils.rkt") (require "store.rkt") (require "grammar.rkt") (require "ds.rkt") (require "scheduler.rkt") (require racket/file) (provide (all-defined-out)) (define apply-proc (lambda (proc1 arg cont) (cases proc proc1 (closure (var body env) (let* ((ref (newref arg)) (new-env (extend-env var ref env))) (interp-exp/k body new-env cont))) (else (eopl:error 'apply-proc "invalid procedure value:~s" proc1))))) (define-datatype continuation continuation? (zero1-cont (cont continuation?)) (let-exp-cont (var symbol?) (env environment?) (body expression?) (cont continuation?)) (diff1-cont (subtractor-exp expression?) (env environment?) (cont continuation?)) (diff2-cont ; todo (expval support) (minuend-val expval?) (env environment?) (cont continuation?)) (if-test-cont (sbj-exp expression?) (else-exp expression?) (env environment?) (cont continuation?)) (rator-cont (arg-exp expression?) (env environment?) (cont continuation?)) (rand-cont (proc proc?) (env environment?) (cont continuation?)) (cons1-cont (cdrv-exp expression?) (env environment?) (cont continuation?)) (cons2-cont (carv expval?) (env environment?) (cont continuation?)) (car-exp-cont (cont continuation?)) (cdr-exp-cont (cont continuation?)) (is-empty-exp-cont (cont continuation?)) (multi-exp-cont (exps (list-of expression?)) (accum-op procedure?) (accum expval?) (env environment?) (cont continuation?)) (set-rhs-cont (ref reference?) (env environment?) (cont continuation?)) (mult-cont1 (exp2 expression?) (env environment?) (cont continuation?)) (mult-cont2 (val expval?) (cont continuation?)) (print-cont (cont continuation?)) (spawn-cont (cont continuation?)) (end-subthread-cont) (end-mainthread-cont) (wait-cont (cont continuation?)) (signal-cont (cont continuation?)) ) (define apply-cont (lambda (cont exp-val) (if (time-expired?) (begin (place-on-ready-queue! (lambda () (apply-cont cont exp-val))) (run-next-thread)) (begin (decrement-timer!) (cases continuation cont (zero1-cont (next-cont) (apply-cont next-cont (boolval (zero? (expval->numval exp-val))))) (let-exp-cont (var env body next-cont) (let* ((ref (newref exp-val)) (new-env (extend-env var ref env))) (interp-exp/k body new-env next-cont))) (diff1-cont (subtractor-exp env next-cont) (interp-exp/k subtractor-exp env (diff2-cont exp-val env next-cont))) (diff2-cont (minuend-val env next-cont) (apply-cont next-cont (numval (- (expval->numval minuend-val) (expval->numval exp-val))))) (if-test-cont (sbj-exp else-exp env next-cont) (if (expval->boolval exp-val) (interp-exp/k sbj-exp env next-cont) (interp-exp/k else-exp env next-cont))) (rator-cont (arg-exp env next-cont) (interp-exp/k arg-exp env (rand-cont (expval->procval exp-val) env next-cont))) (rand-cont (proc env next-cont) (apply-proc proc exp-val next-cont)) (cons1-cont (cdrv-exp env next-cont) (interp-exp/k cdrv-exp env (cons2-cont exp-val env next-cont))) (cons2-cont (carv env next-cont) (apply-cont next-cont (listval (cons carv (expval->listval exp-val))))) (car-exp-cont (next-cont) (apply-cont next-cont (car (expval->listval exp-val)))) (cdr-exp-cont (next-cont) (apply-cont next-cont (listval (cdr (expval->listval exp-val))))) (is-empty-exp-cont (next-cont) (apply-cont next-cont (boolval (null? (expval->listval exp-val))))) (multi-exp-cont (exps accum-op accum env next-cont) (interp-exps/k exps accum-op (accum-op exp-val accum) env next-cont)) (set-rhs-cont (var-ref env next-cont) (apply-cont next-cont (setref! var-ref exp-val))) (mult-cont1 (exp2 env next-cont) (interp-exp/k exp2 env (mult-cont2 exp-val next-cont))) (mult-cont2 (val1 next-cont) (apply-cont next-cont (numval (* (expval->numval val1) (expval->numval exp-val))))) (print-cont (next-cont) (display (expval->normalval exp-val))(newline) (apply-cont next-cont exp-val) ) (spawn-cont (next-cont) (let* ((proc1 (expval->procval exp-val)) (thd (lambda () (apply-proc proc1 (numval 28) (end-subthread-cont))))) (place-on-ready-queue! thd) (apply-cont next-cont (threadval thd)))) (end-subthread-cont () (run-next-thread)) (end-mainthread-cont () (set-final-answer! exp-val) (run-next-thread)) (wait-cont (saved-cont) (wait-for-mutex (expval->mutexval exp-val) (lambda () (apply-cont saved-cont (numval 0))))) (signal-cont (saved-cont) (signal-for-mutex (expval->mutexval exp-val) (lambda () (apply-cont saved-cont (numval 0))))) ))))) (define interp-exps/k (lambda (exps accum-op accum env cont) (if (null? exps) (apply-cont cont accum) (interp-exp/k (car exps) env (multi-exp-cont (cdr exps) accum-op accum env cont))))) (define interp-exp/k (lambda (exp env cont) ; (display cont)(newline)(newline) (cases expression exp (const-exp (num) (apply-cont cont (numval num))) (diff-exp (minuend subtractor) (interp-exp/k minuend env (diff1-cont subtractor env cont))) (zero?-exp (exp) (interp-exp/k exp env (zero1-cont cont))) (if-exp (predicate sbj-exp else-exp) (interp-exp/k predicate env (if-test-cont sbj-exp else-exp env cont))) (var-exp (var) (apply-cont cont (deref (apply-env env var)))) (let-exp (var exp1 body) (interp-exp/k exp1 env (let-exp-cont var env body cont))) (proc-exp (var body) (apply-cont cont (procval (closure var body env)))) (call-exp (exp1 exp2) (interp-exp/k exp1 env (rator-cont exp2 env cont))) (letrec-exp (p-name b-var b-body letrec-body) (let ((new-env (extend-env-recursively p-name b-var b-body env))) (interp-exp/k letrec-body new-env cont))) (cons-exp (carv-exp cdrv-exp) (interp-exp/k carv-exp env (cons1-cont cdrv-exp env cont))) (car-exp (lst-exp) (interp-exp/k lst-exp env (car-exp-cont cont))) (cdr-exp (lst-exp) (interp-exp/k lst-exp env (cdr-exp-cont cont))) (empty-lst-exp () (apply-cont cont (listval '()))) (is-empty-exp (lst-exp) (interp-exp/k lst-exp env (is-empty-exp-cont cont))) (list-exp (exps) (interp-exps/k exps (lambda (val accum) (listval (append (expval->listval accum) (list val)))) (listval '()) env cont)) (compound-exp (exps) (interp-exps/k exps (lambda (val accum) val) (listval '()) env cont)) (set-exp (var exp) (interp-exp/k exp env (set-rhs-cont (apply-env env var) env cont))) (mult-exp (exp1 exp2) (interp-exp/k exp1 env (mult-cont1 exp2 env cont))) (print-exp (exp) (interp-exp/k exp env (print-cont cont))) (spawn-exp (exp) (interp-exp/k exp env (spawn-cont cont))) (mutex-exp () (apply-cont cont (mutexval (make-new-mutex)))) (wait-exp (exp) (interp-exp/k exp env (wait-cont cont))) (signal-exp (exp) (interp-exp/k exp env (signal-cont cont))) ))) (define interp (lambda (datum) (cases program datum (a-program (exp) (initialize-store!) (initialize-scheduler! 5) (interp-exp/k exp (empty-env) (end-mainthread-cont)) (expval->normalval (final-answer))))))
null
https://raw.githubusercontent.com/seckcoder/iu_c311/a1215983b6ab08df32058ef1e089cb294419e567/racket/thread1/interp.rkt
racket
interpreter of let-lang todo (expval support) (display cont)(newline)(newline)
#lang eopl (require "../base/utils.rkt") (require "store.rkt") (require "grammar.rkt") (require "ds.rkt") (require "scheduler.rkt") (require racket/file) (provide (all-defined-out)) (define apply-proc (lambda (proc1 arg cont) (cases proc proc1 (closure (var body env) (let* ((ref (newref arg)) (new-env (extend-env var ref env))) (interp-exp/k body new-env cont))) (else (eopl:error 'apply-proc "invalid procedure value:~s" proc1))))) (define-datatype continuation continuation? (zero1-cont (cont continuation?)) (let-exp-cont (var symbol?) (env environment?) (body expression?) (cont continuation?)) (diff1-cont (subtractor-exp expression?) (env environment?) (cont continuation?)) (diff2-cont (minuend-val expval?) (env environment?) (cont continuation?)) (if-test-cont (sbj-exp expression?) (else-exp expression?) (env environment?) (cont continuation?)) (rator-cont (arg-exp expression?) (env environment?) (cont continuation?)) (rand-cont (proc proc?) (env environment?) (cont continuation?)) (cons1-cont (cdrv-exp expression?) (env environment?) (cont continuation?)) (cons2-cont (carv expval?) (env environment?) (cont continuation?)) (car-exp-cont (cont continuation?)) (cdr-exp-cont (cont continuation?)) (is-empty-exp-cont (cont continuation?)) (multi-exp-cont (exps (list-of expression?)) (accum-op procedure?) (accum expval?) (env environment?) (cont continuation?)) (set-rhs-cont (ref reference?) (env environment?) (cont continuation?)) (mult-cont1 (exp2 expression?) (env environment?) (cont continuation?)) (mult-cont2 (val expval?) (cont continuation?)) (print-cont (cont continuation?)) (spawn-cont (cont continuation?)) (end-subthread-cont) (end-mainthread-cont) (wait-cont (cont continuation?)) (signal-cont (cont continuation?)) ) (define apply-cont (lambda (cont exp-val) (if (time-expired?) (begin (place-on-ready-queue! (lambda () (apply-cont cont exp-val))) (run-next-thread)) (begin (decrement-timer!) (cases continuation cont (zero1-cont (next-cont) (apply-cont next-cont (boolval (zero? (expval->numval exp-val))))) (let-exp-cont (var env body next-cont) (let* ((ref (newref exp-val)) (new-env (extend-env var ref env))) (interp-exp/k body new-env next-cont))) (diff1-cont (subtractor-exp env next-cont) (interp-exp/k subtractor-exp env (diff2-cont exp-val env next-cont))) (diff2-cont (minuend-val env next-cont) (apply-cont next-cont (numval (- (expval->numval minuend-val) (expval->numval exp-val))))) (if-test-cont (sbj-exp else-exp env next-cont) (if (expval->boolval exp-val) (interp-exp/k sbj-exp env next-cont) (interp-exp/k else-exp env next-cont))) (rator-cont (arg-exp env next-cont) (interp-exp/k arg-exp env (rand-cont (expval->procval exp-val) env next-cont))) (rand-cont (proc env next-cont) (apply-proc proc exp-val next-cont)) (cons1-cont (cdrv-exp env next-cont) (interp-exp/k cdrv-exp env (cons2-cont exp-val env next-cont))) (cons2-cont (carv env next-cont) (apply-cont next-cont (listval (cons carv (expval->listval exp-val))))) (car-exp-cont (next-cont) (apply-cont next-cont (car (expval->listval exp-val)))) (cdr-exp-cont (next-cont) (apply-cont next-cont (listval (cdr (expval->listval exp-val))))) (is-empty-exp-cont (next-cont) (apply-cont next-cont (boolval (null? (expval->listval exp-val))))) (multi-exp-cont (exps accum-op accum env next-cont) (interp-exps/k exps accum-op (accum-op exp-val accum) env next-cont)) (set-rhs-cont (var-ref env next-cont) (apply-cont next-cont (setref! var-ref exp-val))) (mult-cont1 (exp2 env next-cont) (interp-exp/k exp2 env (mult-cont2 exp-val next-cont))) (mult-cont2 (val1 next-cont) (apply-cont next-cont (numval (* (expval->numval val1) (expval->numval exp-val))))) (print-cont (next-cont) (display (expval->normalval exp-val))(newline) (apply-cont next-cont exp-val) ) (spawn-cont (next-cont) (let* ((proc1 (expval->procval exp-val)) (thd (lambda () (apply-proc proc1 (numval 28) (end-subthread-cont))))) (place-on-ready-queue! thd) (apply-cont next-cont (threadval thd)))) (end-subthread-cont () (run-next-thread)) (end-mainthread-cont () (set-final-answer! exp-val) (run-next-thread)) (wait-cont (saved-cont) (wait-for-mutex (expval->mutexval exp-val) (lambda () (apply-cont saved-cont (numval 0))))) (signal-cont (saved-cont) (signal-for-mutex (expval->mutexval exp-val) (lambda () (apply-cont saved-cont (numval 0))))) ))))) (define interp-exps/k (lambda (exps accum-op accum env cont) (if (null? exps) (apply-cont cont accum) (interp-exp/k (car exps) env (multi-exp-cont (cdr exps) accum-op accum env cont))))) (define interp-exp/k (lambda (exp env cont) (cases expression exp (const-exp (num) (apply-cont cont (numval num))) (diff-exp (minuend subtractor) (interp-exp/k minuend env (diff1-cont subtractor env cont))) (zero?-exp (exp) (interp-exp/k exp env (zero1-cont cont))) (if-exp (predicate sbj-exp else-exp) (interp-exp/k predicate env (if-test-cont sbj-exp else-exp env cont))) (var-exp (var) (apply-cont cont (deref (apply-env env var)))) (let-exp (var exp1 body) (interp-exp/k exp1 env (let-exp-cont var env body cont))) (proc-exp (var body) (apply-cont cont (procval (closure var body env)))) (call-exp (exp1 exp2) (interp-exp/k exp1 env (rator-cont exp2 env cont))) (letrec-exp (p-name b-var b-body letrec-body) (let ((new-env (extend-env-recursively p-name b-var b-body env))) (interp-exp/k letrec-body new-env cont))) (cons-exp (carv-exp cdrv-exp) (interp-exp/k carv-exp env (cons1-cont cdrv-exp env cont))) (car-exp (lst-exp) (interp-exp/k lst-exp env (car-exp-cont cont))) (cdr-exp (lst-exp) (interp-exp/k lst-exp env (cdr-exp-cont cont))) (empty-lst-exp () (apply-cont cont (listval '()))) (is-empty-exp (lst-exp) (interp-exp/k lst-exp env (is-empty-exp-cont cont))) (list-exp (exps) (interp-exps/k exps (lambda (val accum) (listval (append (expval->listval accum) (list val)))) (listval '()) env cont)) (compound-exp (exps) (interp-exps/k exps (lambda (val accum) val) (listval '()) env cont)) (set-exp (var exp) (interp-exp/k exp env (set-rhs-cont (apply-env env var) env cont))) (mult-exp (exp1 exp2) (interp-exp/k exp1 env (mult-cont1 exp2 env cont))) (print-exp (exp) (interp-exp/k exp env (print-cont cont))) (spawn-exp (exp) (interp-exp/k exp env (spawn-cont cont))) (mutex-exp () (apply-cont cont (mutexval (make-new-mutex)))) (wait-exp (exp) (interp-exp/k exp env (wait-cont cont))) (signal-exp (exp) (interp-exp/k exp env (signal-cont cont))) ))) (define interp (lambda (datum) (cases program datum (a-program (exp) (initialize-store!) (initialize-scheduler! 5) (interp-exp/k exp (empty-env) (end-mainthread-cont)) (expval->normalval (final-answer))))))
25c65668a44de24649fb9884e57cd612cbf3268706a0e75223ae309e08031a92
diku-dk/futhark
Query.hs
-- | @futhark query@ module Futhark.CLI.Query (main) where import Futhark.Compiler import Futhark.Util.Loc import Futhark.Util.Options import Language.Futhark.Query import Language.Futhark.Syntax import Text.Read (readMaybe) -- | Run @futhark query@. main :: String -> [String] -> IO () main = mainWithOptions () [] "program line col" $ \args () -> case args of [file, line, col] -> do line' <- readMaybe line col' <- readMaybe col Just $ do (_, imports, _) <- readProgramOrDie file -- The 'offset' part of the Pos is not used and can be arbitrary. case atPos imports $ Pos file line' col' 0 of Nothing -> putStrLn "No information available." Just (AtName qn def loc) -> do putStrLn $ "Name: " ++ prettyString qn putStrLn $ "Position: " ++ locStr (srclocOf loc) case def of Nothing -> pure () Just (BoundTerm t defloc) -> do putStrLn $ "Type: " ++ prettyString t putStrLn $ "Definition: " ++ locStr (srclocOf defloc) Just (BoundType defloc) -> putStrLn $ "Definition: " ++ locStr (srclocOf defloc) Just (BoundModule defloc) -> putStrLn $ "Definition: " ++ locStr (srclocOf defloc) Just (BoundModuleType defloc) -> putStrLn $ "Definition: " ++ locStr (srclocOf defloc) _ -> Nothing
null
https://raw.githubusercontent.com/diku-dk/futhark/156f24a8d0fdb7d9ad853b074e786849998ce602/src/Futhark/CLI/Query.hs
haskell
| @futhark query@ | Run @futhark query@. The 'offset' part of the Pos is not used and can be arbitrary.
module Futhark.CLI.Query (main) where import Futhark.Compiler import Futhark.Util.Loc import Futhark.Util.Options import Language.Futhark.Query import Language.Futhark.Syntax import Text.Read (readMaybe) main :: String -> [String] -> IO () main = mainWithOptions () [] "program line col" $ \args () -> case args of [file, line, col] -> do line' <- readMaybe line col' <- readMaybe col Just $ do (_, imports, _) <- readProgramOrDie file case atPos imports $ Pos file line' col' 0 of Nothing -> putStrLn "No information available." Just (AtName qn def loc) -> do putStrLn $ "Name: " ++ prettyString qn putStrLn $ "Position: " ++ locStr (srclocOf loc) case def of Nothing -> pure () Just (BoundTerm t defloc) -> do putStrLn $ "Type: " ++ prettyString t putStrLn $ "Definition: " ++ locStr (srclocOf defloc) Just (BoundType defloc) -> putStrLn $ "Definition: " ++ locStr (srclocOf defloc) Just (BoundModule defloc) -> putStrLn $ "Definition: " ++ locStr (srclocOf defloc) Just (BoundModuleType defloc) -> putStrLn $ "Definition: " ++ locStr (srclocOf defloc) _ -> Nothing
c55a2497c4ed59bc1346e997fa4d773e06b1693307f86132cf4d68e9bed7f0d4
deis/example-clojure-ring
web.clj
(ns helloworld.web (:use compojure.core [ring.adapter.jetty :only [run-jetty]]) (:require [compojure.route :as route] [compojure.handler :as handler])) (def message (get (System/getenv) "POWERED_BY" "Deis")) (defroutes main-routes (GET "/" [] (apply str "Powered by " message)) (route/resources "/") (route/not-found "Page not found")) (def app (handler/api main-routes)) (defn -main [] (def port (get (System/getenv) "PORT" 5000)) (run-jetty app {:port (Integer. port)}))
null
https://raw.githubusercontent.com/deis/example-clojure-ring/878bd7802fb6f35058e9a6478cbab01595835fb0/src/helloworld/web.clj
clojure
(ns helloworld.web (:use compojure.core [ring.adapter.jetty :only [run-jetty]]) (:require [compojure.route :as route] [compojure.handler :as handler])) (def message (get (System/getenv) "POWERED_BY" "Deis")) (defroutes main-routes (GET "/" [] (apply str "Powered by " message)) (route/resources "/") (route/not-found "Page not found")) (def app (handler/api main-routes)) (defn -main [] (def port (get (System/getenv) "PORT" 5000)) (run-jetty app {:port (Integer. port)}))
96225e406637a257fc8d1ce09d15f43106a26a4cbb9966343e9c062f1e493f55
digitallyinduced/ihp
ValidateField.hs
| Module : . Description : Validation for records Copyright : ( c ) digitally induced GmbH , 2020 Use ' ' and ' validateFieldIO ' together with the validation functions to do simple validations . Also take a look at ' IHP.ValidationSupport . ValidateIsUnique.validateIsUnique ' for e.g. checking that an email is unique . Module: IHP.ValidationSupport.ValidateField Description: Validation for records Copyright: (c) digitally induced GmbH, 2020 Use 'validateField' and 'validateFieldIO' together with the validation functions to do simple validations. Also take a look at 'IHP.ValidationSupport.ValidateIsUnique.validateIsUnique' for e.g. checking that an email is unique. -} module IHP.ValidationSupport.ValidateField where import ClassyPrelude import Data.Proxy import IHP.ValidationSupport.Types import GHC.TypeLits (KnownSymbol) import GHC.Records import IHP.ModelSupport import IHP.HaskellSupport import Text.Regex.TDFA import Data.List ((!!)) | A function taking some value and returning a ' ' -- -- >>> Validator Text Text - > -- -- >>> Validator Int Int - > type Validator valueType = valueType -> ValidatorResult -- | Validates a record field using a given validator function. -- When the validation fails , the validation error is saved inside the @meta : : MetaBag@ field of the record . You can retrieve a possible validation error using ' IHP.ValidationSupport . Types.getValidationFailure ' . -- _ _ Example : _ _ ' nonEmpty ' validation for a record -- -- > let project :: Project = newRecord -- > project > | > # name nonEmpty -- > |> getValidationFailure #name -- Just "This field cannot be empty" -- > -- > -- > project > | > set # name " Hello World " > | > # name nonEmpty -- > |> getValidationFailure #name -- Nothing -- -- _ _ Example : _ _ Using ' IHP.Controller . ' for branching -- -- > let project :: Project = newRecord -- > -- > project > | > # name nonEmpty -- > |> ifValid \case -- > Left project -> do -- > putStrLn "Invalid project. Please try again" -- > Right project -> do > putStrLn " Project is valid . Saving to database . " > project validateField :: forall field fieldValue model. ( KnownSymbol field , HasField field model fieldValue , HasField "meta" model MetaBag , SetField "meta" model MetaBag ) => Proxy field -> Validator fieldValue -> model -> model validateField field validator model = attachValidatorResult field (validator (getField @field model)) model # INLINE validateField # | A function taking some value and returning a ' IO ' -- -- >>> ValidatorIO Text Text - > IO -- > > > ValidatorIO Int Int - > IO type ValidatorIO value = value -> IO ValidatorResult -- | Validates a record field using a given validator function. -- The same as ' ' , but works with IO and can e.g. access the database . -- When the validation fails , the validation error is saved inside the @meta : : MetaBag@ field of the record . You can retrieve a possible validation error using ' IHP.ValidationSupport . Types.getValidationFailure ' . -- validateFieldIO :: forall field model fieldValue. ( ?modelContext :: ModelContext , KnownSymbol field , HasField field model fieldValue , HasField "meta" model MetaBag , SetField "meta" model MetaBag ) => Proxy field -> ValidatorIO fieldValue -> model -> IO model validateFieldIO fieldProxy customValidation model = do let value :: fieldValue = getField @field model result <- customValidation value pure (attachValidatorResult fieldProxy result model) # INLINE validateFieldIO # -- | Overrides the error message of a given validator function. -- > > > ( nonEmpty | > withCustomErrorMessage " Custom error message " ) " " -- Failure "Custom error message" -- -- -- >>> (isEmail |> withCustomErrorMessage "We only accept valid email addresses") "not valid email" -- Failure "We only accept valid email addresses" withCustomErrorMessage :: Text -> (value -> ValidatorResult) -> value -> ValidatorResult withCustomErrorMessage errorMessage validator value = case validator value of Failure _ -> Failure errorMessage Success -> Success # INLINABLE withCustomErrorMessage # | Validates that value passes at least one of the given validators -- -- >>> "" |> validateAny([isEmptyValue, isEmail]) Success -- -- >>> "" |> validateAny([isEmptyValue, isEmail]) Success -- -- >>> "no spam plz" |> validateAny([empty, isEmail]) -- Failure "did not pass any validators" validateAny :: [value -> ValidatorResult] -> value -> ValidatorResult validateAny validators text = case any isSuccess $ map ($ text) validators of True -> Success False -> Failure "did not pass any validators" # INLINABLE validateAny # -- | Validates that value passes all of the given validators -- In case of multiple failures , the first Failure is returned . -- > > > 2016 | > validateAll([isGreaterThan(1900 ) , isLessThan(2020 ) ] ) Success -- > > > 1899 | > validateAll([isGreaterThan(1900 ) , isLessThan(2020 ) ] ) -- Failure "has to be greater than 1900" validateAll :: [value -> ValidatorResult] -> value -> ValidatorResult validateAll validators text = let results = map ($ text) validators in case all isSuccess results of True -> Success False -> (filter isFailure results) !! 0 # INLINABLE validateAll # -- | Validates that value is not empty -- -- >>> nonEmpty "hello world" Success -- -- >>> nonEmpty "" -- Failure "This field cannot be empty" -- > > > nonEmpty ( Just " hello " ) Success -- -- >>> nonEmpty Nothing -- Failure "This field cannot be empty" nonEmpty :: IsEmpty value => value -> ValidatorResult nonEmpty value | isEmpty value = Failure "This field cannot be empty" nonEmpty _ = Success # INLINABLE nonEmpty # -- | Validates that value is empty -- -- >>> isEmptyValue "hello world" -- Failure "This field must be empty" -- -- >>> ieEmptyValue "" Success -- -- >>> isEmptyValue (Just "hello") -- Failure "This field must be empty" -- -- >>> isEmptyValue Nothing Success isEmptyValue :: IsEmpty value => value -> ValidatorResult isEmptyValue value | isEmpty value = Success isEmptyValue _ = Failure "This field must be empty" # INLINABLE isEmptyValue # -- | Validates that value looks like a phone number -- Values needs to start with @\+@ and has to have atleast 5 characters -- -- >>> isPhoneNumber "1337" -- Failure ".." -- -- >>> isPhoneNumber "+49123456789" Success isPhoneNumber :: Text -> ValidatorResult isPhoneNumber text | "+" `isPrefixOf` text && length text > 5 = Success isPhoneNumber text = Failure "is not a valid phone number (has to start with +, at least 5 characters)" # INLINABLE isPhoneNumber # -- | Validates that value is an email address -- The validation is not meant to be compliant with RFC 822 . Its purpose is to -- reject obviously invalid values without false-negatives. -- -- >>> isEmail "" Success -- -- >>> isEmail "" -- subdomains are fine Success -- -- >>> isEmail "ॐ@मणिपद्मे.हूँ" Success -- > > > isEmail " marc@localhost " -- Although discouraged by ICANN , dotless TLDs are legal . See -2013-08-30-en Success -- > > > isEmail " loremipsum " -- Failure "is not a valid email" -- -- >>> isEmail "A@b@" -- Failure "is not a valid email" isEmail :: Text -> ValidatorResult isEmail text | text =~ ("^[^ @]+@[^ @_+]+\\.?[^ @_+-]+$" :: Text) = Success isEmail text = Failure "is not a valid email" # INLINABLE isEmail # | Validates that value is between min and -- > > > isInRange ( 0 , 10 ) 5 Success -- > > > isInRange ( 0 , 10 ) 0 Success -- > > > isInRange ( 0 , 10 ) 1337 Failure " has to be between 0 and 10 " -- > > > let isHumanAge = isInRange ( 0 , 100 ) > > > isHumanAge 22 Success isInRange :: (Show value, Ord value) => (value, value) -> value -> ValidatorResult isInRange (min, max) value | value >= min && value <= max = Success isInRange (min, max) value = Failure ("has to be between " <> tshow min <> " and " <> tshow max) {-# INLINABLE isInRange #-} -- | Validates that value is less than a max value -- -- >>> isLessThan 10 5 Success -- > > > isLessThan 10 20 Failure " has to be less than 10 " isLessThan :: (Show value, Ord value) => value -> value -> ValidatorResult isLessThan max value | value < max = Success isLessThan max value = Failure ("has to be less than " <> tshow max) {-# INLINABLE isLessThan #-} -- | Validates that value is greater than a min value -- -- >>> isGreaterThan 10 20 Success -- -- >>> isGreaterThan 10 5 Failure " has to be greater than 10 " isGreaterThan :: (Show value, Ord value) => value -> value -> ValidatorResult isGreaterThan min value | value > min = Success isGreaterThan min value = Failure ("has to be greater than " <> tshow min) {-# INLINABLE isGreaterThan #-} -- | Validates that value has a max length -- > > > hasMaxLength 10 " IHP " Success -- > > > hasMaxLength 2 " IHP " Failure " is longer than 2 characters " hasMaxLength :: Int -> Text -> ValidatorResult hasMaxLength max text | length text <= max = Success hasMaxLength max text = Failure ("is longer than " <> tshow max <> " characters") # INLINABLE hasMaxLength # -- | Validates that value has a min length -- > > > hasMinLength 2 " IHP " Success -- > > > hasMinLength 10 " IHP " Failure " is shorter than 10 characters " hasMinLength :: Int -> Text -> ValidatorResult hasMinLength min text | length text >= min = Success hasMinLength min text = Failure ("is shorter than " <> tshow min <> " characters") # INLINABLE hasMinLength # | Validates that value is a hex - based rgb color string -- -- >>> isRgbHexColor "#ffffff" Success -- -- >>> isRgbHexColor "#fff" Success -- > > > isRgbHexColor " rgb(0 , 0 , 0 ) " -- Failure "is not a valid rgb hex color" isRgbHexColor :: Text -> ValidatorResult isRgbHexColor text | text =~ ("^#([0-9a-f]{3}|[0-9a-f]{6})$" :: Text) = Success isRgbHexColor text = Failure "is not a valid rgb hex color" # INLINABLE isRgbHexColor # | Validates that value is a hex - based rgb color string -- > > > isRgbaHexColor " # ffffffff " Success -- > > > isRgbaHexColor " # ffff " Success -- > > > isRgbaHexColor " rgb(0 , 0 , 0 , 1 ) " -- Failure "is not a valid rgba hex color" isRgbaHexColor :: Text -> ValidatorResult isRgbaHexColor text | text =~ ("^#([0-9a-f]{4}|[0-9a-f]{8})$" :: Text) = Success isRgbaHexColor text = Failure "is not a valid rgba hex color" # INLINABLE isRgbaHexColor # -- | Validates that value is a hex-based rgb(a) color string -- > > > isHexColor " # ffffff " Success -- > > > isHexColor " # ffffffff " Success -- -- >>> isHexColor "rgb(0, 0, 0)" -- Failure "is not a valid hex color" isHexColor :: Text -> ValidatorResult isHexColor = validateAny [isRgbHexColor, isRgbaHexColor] |> withCustomErrorMessage "is not a valid hex color" # INLINABLE isHexColor # -- | Validates that value is a rgb() color string -- > > > isRgbColor " rgb(255 , 0 , 0 ) " Success -- -- >>> isRgbColor "#f00" Failure " is not a valid rgb ( ) color " isRgbColor :: Text -> ValidatorResult isRgbColor text | text =~ ("^rgb\\( *([0-9]*\\.)?[0-9]+ *, *([0-9]*\\.)?[0-9]+ *, *([0-9]*\\.)?[0-9]+ *\\)$" :: Text) = Success isRgbColor text = Failure "is not a valid rgb() color" # INLINABLE isRgbColor # -- | Validates that value is a rgba() color string -- > > > isRgbaColor " rgb(255 , 0 , 0 , 1.0 ) " Success -- > > > isRgbaColor " # f00f " -- Failure "is not a valid rgba() color" isRgbaColor :: Text -> ValidatorResult isRgbaColor text | text =~ ("^rgba\\( *([0-9]*\\.)?[0-9]+ *, *([0-9]*\\.)?[0-9]+ *, *([0-9]*\\.)?[0-9]+ *, *([0-9]*\\.)?[0-9]+ *\\)$" :: Text) = Success isRgbaColor text = Failure "is not a valid rgba() color" # INLINABLE isRgbaColor # -- | Validates that value is a hex-based or rgb(a) color string -- -- >>> isColor "#ffffff" Success -- > > > isColor " rgba(255 , 0 , 0 , 0.5 ) " Success -- -- >>> isColor "rgb(0, 0, 0)" -- Failure "is not a valid color" isColor :: Text -> ValidatorResult isColor = validateAny [isRgbHexColor, isRgbaHexColor, isRgbColor, isRgbaColor] |> withCustomErrorMessage "is not a valid color" # INLINABLE isColor # -- | Validates string starts with @http://@ or @https://@ -- -- >>> isUrl "" Success -- -- >>> isUrl "digitallyinduced.com" -- Failure "is not a valid url. It needs to start with http:// or https://" isUrl :: Text -> ValidatorResult isUrl text | "http://" `isPrefixOf` text || "https://" `isPrefixOf` text = Success isUrl text = Failure "is not a valid url. It needs to start with http:// or https://" # INLINABLE isUrl # isInList :: (Eq value, Show value) => [value] -> value -> ValidatorResult isInList list value | list |> includes value = Success isInList list value = Failure ("is not allowed. It needs to be one of the following: " <> (tshow list)) # INLINABLE isInList # -- | Validates that value is True -- -- >>> isTrue True Success -- -- >>> isTrue False -- Failure "This field cannot be false" isTrue :: Bool -> ValidatorResult isTrue value = if value then Success else Failure "This field cannot be false" # INLINABLE isTrue # -- | Validates that value is False -- -- >>> isFalse False Success -- -- >>> isFalse True -- Failure "This field cannot be true" isFalse :: Bool -> ValidatorResult isFalse value = if not value then Success else Failure "This field cannot be true" # INLINABLE isFalse # -- | Validates that value is matched by the regular expression -- > > > matchesRegex " ^[0 - 9]{4}$ " " 2016 " Success -- > > > matchesRegex " ^[0 - 9]{4}$ " " 16 " -- Failure "This field does not match the regular expression \"^[0-9]{4}$\"" -- -- >>> matchesRegex "[0-9]{4}" "xx2016xx" Success -- regex is missing ^ and $ -- matchesRegex :: Text -> Text -> ValidatorResult matchesRegex regex text = if text =~ regex then Success else Failure $ "This field does not match the regular expression \"" <> regex <> "\"" # INLINABLE matchesRegex # -- | Validates that value is a valid slug -- -- >>> isSlug "i-am-a-slug" Success -- -- >>> isSlug "I-AM-A-Slug (Copy)" -- Failure "is not a valid slug (consisting of only letters, numbers, underscores or hyphens)" isSlug :: Text -> ValidatorResult isSlug text | text =~ ("^[a-zA-Z0-9_-]+$" :: Text) = Success isSlug text = Failure "is not a valid slug (consisting of only letters, numbers, underscores or hyphens)" # INLINABLE isSlug #
null
https://raw.githubusercontent.com/digitallyinduced/ihp/62ca014a3d986e35da0fb05a4b1e84e5831e87cf/IHP/ValidationSupport/ValidateField.hs
haskell
>>> Validator Text >>> Validator Int | Validates a record field using a given validator function. > let project :: Project = newRecord > project > |> getValidationFailure #name -- Just "This field cannot be empty" > > > project > |> getValidationFailure #name -- Nothing > let project :: Project = newRecord > > project > |> ifValid \case > Left project -> do > putStrLn "Invalid project. Please try again" > Right project -> do >>> ValidatorIO Text | Validates a record field using a given validator function. | Overrides the error message of a given validator function. Failure "Custom error message" >>> (isEmail |> withCustomErrorMessage "We only accept valid email addresses") "not valid email" Failure "We only accept valid email addresses" >>> "" |> validateAny([isEmptyValue, isEmail]) >>> "" |> validateAny([isEmptyValue, isEmail]) >>> "no spam plz" |> validateAny([empty, isEmail]) Failure "did not pass any validators" | Validates that value passes all of the given validators Failure "has to be greater than 1900" | Validates that value is not empty >>> nonEmpty "hello world" >>> nonEmpty "" Failure "This field cannot be empty" >>> nonEmpty Nothing Failure "This field cannot be empty" | Validates that value is empty >>> isEmptyValue "hello world" Failure "This field must be empty" >>> ieEmptyValue "" >>> isEmptyValue (Just "hello") Failure "This field must be empty" >>> isEmptyValue Nothing | Validates that value looks like a phone number >>> isPhoneNumber "1337" Failure ".." >>> isPhoneNumber "+49123456789" | Validates that value is an email address reject obviously invalid values without false-negatives. >>> isEmail "" >>> isEmail "" -- subdomains are fine >>> isEmail "ॐ@मणिपद्मे.हूँ" Although discouraged by ICANN , dotless TLDs are legal . See -2013-08-30-en Failure "is not a valid email" >>> isEmail "A@b@" Failure "is not a valid email" # INLINABLE isInRange # | Validates that value is less than a max value >>> isLessThan 10 5 # INLINABLE isLessThan # | Validates that value is greater than a min value >>> isGreaterThan 10 20 >>> isGreaterThan 10 5 # INLINABLE isGreaterThan # | Validates that value has a max length | Validates that value has a min length >>> isRgbHexColor "#ffffff" >>> isRgbHexColor "#fff" Failure "is not a valid rgb hex color" Failure "is not a valid rgba hex color" | Validates that value is a hex-based rgb(a) color string >>> isHexColor "rgb(0, 0, 0)" Failure "is not a valid hex color" | Validates that value is a rgb() color string >>> isRgbColor "#f00" | Validates that value is a rgba() color string Failure "is not a valid rgba() color" | Validates that value is a hex-based or rgb(a) color string >>> isColor "#ffffff" >>> isColor "rgb(0, 0, 0)" Failure "is not a valid color" | Validates string starts with @http://@ or @https://@ >>> isUrl "" >>> isUrl "digitallyinduced.com" Failure "is not a valid url. It needs to start with http:// or https://" | Validates that value is True >>> isTrue True >>> isTrue False Failure "This field cannot be false" | Validates that value is False >>> isFalse False >>> isFalse True Failure "This field cannot be true" | Validates that value is matched by the regular expression Failure "This field does not match the regular expression \"^[0-9]{4}$\"" >>> matchesRegex "[0-9]{4}" "xx2016xx" regex is missing ^ and $ | Validates that value is a valid slug >>> isSlug "i-am-a-slug" >>> isSlug "I-AM-A-Slug (Copy)" Failure "is not a valid slug (consisting of only letters, numbers, underscores or hyphens)"
| Module : . Description : Validation for records Copyright : ( c ) digitally induced GmbH , 2020 Use ' ' and ' validateFieldIO ' together with the validation functions to do simple validations . Also take a look at ' IHP.ValidationSupport . ValidateIsUnique.validateIsUnique ' for e.g. checking that an email is unique . Module: IHP.ValidationSupport.ValidateField Description: Validation for records Copyright: (c) digitally induced GmbH, 2020 Use 'validateField' and 'validateFieldIO' together with the validation functions to do simple validations. Also take a look at 'IHP.ValidationSupport.ValidateIsUnique.validateIsUnique' for e.g. checking that an email is unique. -} module IHP.ValidationSupport.ValidateField where import ClassyPrelude import Data.Proxy import IHP.ValidationSupport.Types import GHC.TypeLits (KnownSymbol) import GHC.Records import IHP.ModelSupport import IHP.HaskellSupport import Text.Regex.TDFA import Data.List ((!!)) | A function taking some value and returning a ' ' Text - > Int - > type Validator valueType = valueType -> ValidatorResult When the validation fails , the validation error is saved inside the @meta : : MetaBag@ field of the record . You can retrieve a possible validation error using ' IHP.ValidationSupport . Types.getValidationFailure ' . _ _ Example : _ _ ' nonEmpty ' validation for a record > | > # name nonEmpty > | > set # name " Hello World " > | > # name nonEmpty _ _ Example : _ _ Using ' IHP.Controller . ' for branching > | > # name nonEmpty > putStrLn " Project is valid . Saving to database . " > project validateField :: forall field fieldValue model. ( KnownSymbol field , HasField field model fieldValue , HasField "meta" model MetaBag , SetField "meta" model MetaBag ) => Proxy field -> Validator fieldValue -> model -> model validateField field validator model = attachValidatorResult field (validator (getField @field model)) model # INLINE validateField # | A function taking some value and returning a ' IO ' Text - > IO > > > ValidatorIO Int Int - > IO type ValidatorIO value = value -> IO ValidatorResult The same as ' ' , but works with IO and can e.g. access the database . When the validation fails , the validation error is saved inside the @meta : : MetaBag@ field of the record . You can retrieve a possible validation error using ' IHP.ValidationSupport . Types.getValidationFailure ' . validateFieldIO :: forall field model fieldValue. ( ?modelContext :: ModelContext , KnownSymbol field , HasField field model fieldValue , HasField "meta" model MetaBag , SetField "meta" model MetaBag ) => Proxy field -> ValidatorIO fieldValue -> model -> IO model validateFieldIO fieldProxy customValidation model = do let value :: fieldValue = getField @field model result <- customValidation value pure (attachValidatorResult fieldProxy result model) # INLINE validateFieldIO # > > > ( nonEmpty | > withCustomErrorMessage " Custom error message " ) " " withCustomErrorMessage :: Text -> (value -> ValidatorResult) -> value -> ValidatorResult withCustomErrorMessage errorMessage validator value = case validator value of Failure _ -> Failure errorMessage Success -> Success # INLINABLE withCustomErrorMessage # | Validates that value passes at least one of the given validators Success Success validateAny :: [value -> ValidatorResult] -> value -> ValidatorResult validateAny validators text = case any isSuccess $ map ($ text) validators of True -> Success False -> Failure "did not pass any validators" # INLINABLE validateAny # In case of multiple failures , the first Failure is returned . > > > 2016 | > validateAll([isGreaterThan(1900 ) , isLessThan(2020 ) ] ) Success > > > 1899 | > validateAll([isGreaterThan(1900 ) , isLessThan(2020 ) ] ) validateAll :: [value -> ValidatorResult] -> value -> ValidatorResult validateAll validators text = let results = map ($ text) validators in case all isSuccess results of True -> Success False -> (filter isFailure results) !! 0 # INLINABLE validateAll # Success > > > nonEmpty ( Just " hello " ) Success nonEmpty :: IsEmpty value => value -> ValidatorResult nonEmpty value | isEmpty value = Failure "This field cannot be empty" nonEmpty _ = Success # INLINABLE nonEmpty # Success Success isEmptyValue :: IsEmpty value => value -> ValidatorResult isEmptyValue value | isEmpty value = Success isEmptyValue _ = Failure "This field must be empty" # INLINABLE isEmptyValue # Values needs to start with @\+@ and has to have atleast 5 characters Success isPhoneNumber :: Text -> ValidatorResult isPhoneNumber text | "+" `isPrefixOf` text && length text > 5 = Success isPhoneNumber text = Failure "is not a valid phone number (has to start with +, at least 5 characters)" # INLINABLE isPhoneNumber # The validation is not meant to be compliant with RFC 822 . Its purpose is to Success Success Success Success > > > isEmail " loremipsum " isEmail :: Text -> ValidatorResult isEmail text | text =~ ("^[^ @]+@[^ @_+]+\\.?[^ @_+-]+$" :: Text) = Success isEmail text = Failure "is not a valid email" # INLINABLE isEmail # | Validates that value is between min and > > > isInRange ( 0 , 10 ) 5 Success > > > isInRange ( 0 , 10 ) 0 Success > > > isInRange ( 0 , 10 ) 1337 Failure " has to be between 0 and 10 " > > > let isHumanAge = isInRange ( 0 , 100 ) > > > isHumanAge 22 Success isInRange :: (Show value, Ord value) => (value, value) -> value -> ValidatorResult isInRange (min, max) value | value >= min && value <= max = Success isInRange (min, max) value = Failure ("has to be between " <> tshow min <> " and " <> tshow max) Success > > > isLessThan 10 20 Failure " has to be less than 10 " isLessThan :: (Show value, Ord value) => value -> value -> ValidatorResult isLessThan max value | value < max = Success isLessThan max value = Failure ("has to be less than " <> tshow max) Success Failure " has to be greater than 10 " isGreaterThan :: (Show value, Ord value) => value -> value -> ValidatorResult isGreaterThan min value | value > min = Success isGreaterThan min value = Failure ("has to be greater than " <> tshow min) > > > hasMaxLength 10 " IHP " Success > > > hasMaxLength 2 " IHP " Failure " is longer than 2 characters " hasMaxLength :: Int -> Text -> ValidatorResult hasMaxLength max text | length text <= max = Success hasMaxLength max text = Failure ("is longer than " <> tshow max <> " characters") # INLINABLE hasMaxLength # > > > hasMinLength 2 " IHP " Success > > > hasMinLength 10 " IHP " Failure " is shorter than 10 characters " hasMinLength :: Int -> Text -> ValidatorResult hasMinLength min text | length text >= min = Success hasMinLength min text = Failure ("is shorter than " <> tshow min <> " characters") # INLINABLE hasMinLength # | Validates that value is a hex - based rgb color string Success Success > > > isRgbHexColor " rgb(0 , 0 , 0 ) " isRgbHexColor :: Text -> ValidatorResult isRgbHexColor text | text =~ ("^#([0-9a-f]{3}|[0-9a-f]{6})$" :: Text) = Success isRgbHexColor text = Failure "is not a valid rgb hex color" # INLINABLE isRgbHexColor # | Validates that value is a hex - based rgb color string > > > isRgbaHexColor " # ffffffff " Success > > > isRgbaHexColor " # ffff " Success > > > isRgbaHexColor " rgb(0 , 0 , 0 , 1 ) " isRgbaHexColor :: Text -> ValidatorResult isRgbaHexColor text | text =~ ("^#([0-9a-f]{4}|[0-9a-f]{8})$" :: Text) = Success isRgbaHexColor text = Failure "is not a valid rgba hex color" # INLINABLE isRgbaHexColor # > > > isHexColor " # ffffff " Success > > > isHexColor " # ffffffff " Success isHexColor :: Text -> ValidatorResult isHexColor = validateAny [isRgbHexColor, isRgbaHexColor] |> withCustomErrorMessage "is not a valid hex color" # INLINABLE isHexColor # > > > isRgbColor " rgb(255 , 0 , 0 ) " Success Failure " is not a valid rgb ( ) color " isRgbColor :: Text -> ValidatorResult isRgbColor text | text =~ ("^rgb\\( *([0-9]*\\.)?[0-9]+ *, *([0-9]*\\.)?[0-9]+ *, *([0-9]*\\.)?[0-9]+ *\\)$" :: Text) = Success isRgbColor text = Failure "is not a valid rgb() color" # INLINABLE isRgbColor # > > > isRgbaColor " rgb(255 , 0 , 0 , 1.0 ) " Success > > > isRgbaColor " # f00f " isRgbaColor :: Text -> ValidatorResult isRgbaColor text | text =~ ("^rgba\\( *([0-9]*\\.)?[0-9]+ *, *([0-9]*\\.)?[0-9]+ *, *([0-9]*\\.)?[0-9]+ *, *([0-9]*\\.)?[0-9]+ *\\)$" :: Text) = Success isRgbaColor text = Failure "is not a valid rgba() color" # INLINABLE isRgbaColor # Success > > > isColor " rgba(255 , 0 , 0 , 0.5 ) " Success isColor :: Text -> ValidatorResult isColor = validateAny [isRgbHexColor, isRgbaHexColor, isRgbColor, isRgbaColor] |> withCustomErrorMessage "is not a valid color" # INLINABLE isColor # Success isUrl :: Text -> ValidatorResult isUrl text | "http://" `isPrefixOf` text || "https://" `isPrefixOf` text = Success isUrl text = Failure "is not a valid url. It needs to start with http:// or https://" # INLINABLE isUrl # isInList :: (Eq value, Show value) => [value] -> value -> ValidatorResult isInList list value | list |> includes value = Success isInList list value = Failure ("is not allowed. It needs to be one of the following: " <> (tshow list)) # INLINABLE isInList # Success isTrue :: Bool -> ValidatorResult isTrue value = if value then Success else Failure "This field cannot be false" # INLINABLE isTrue # Success isFalse :: Bool -> ValidatorResult isFalse value = if not value then Success else Failure "This field cannot be true" # INLINABLE isFalse # > > > matchesRegex " ^[0 - 9]{4}$ " " 2016 " Success > > > matchesRegex " ^[0 - 9]{4}$ " " 16 " matchesRegex :: Text -> Text -> ValidatorResult matchesRegex regex text = if text =~ regex then Success else Failure $ "This field does not match the regular expression \"" <> regex <> "\"" # INLINABLE matchesRegex # Success isSlug :: Text -> ValidatorResult isSlug text | text =~ ("^[a-zA-Z0-9_-]+$" :: Text) = Success isSlug text = Failure "is not a valid slug (consisting of only letters, numbers, underscores or hyphens)" # INLINABLE isSlug #
8b296c804a51a62c4034cdd7d625c3ea16a624e04918f727a2663f5eb7e70773
gafiatulin/codewars
FactorialTail.hs
-- Factorial tail -- / module Codewars.Kata.FactorialTail where import Data.List (group) import Control.Arrow ((&&&)) zeroes :: Integral a => a -> a -> a zeroes base n = minimum . map (f . (head &&& length)) . group . pd $ base where f (a, b) = (`div` fromIntegral b) . sum . map (n `div`) $ [a^i | i <- [1.. floor (logBase (fromIntegral a) (fromIntegral n))]] pd x | x == 1 = [] | null d = [x] | otherwise = head d : pd (x `div` head d) where d = filter ((==0) . (x `mod`)) [2.. floor . sqrt . fromIntegral $ x]
null
https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/4%20kyu/FactorialTail.hs
haskell
Factorial tail /
module Codewars.Kata.FactorialTail where import Data.List (group) import Control.Arrow ((&&&)) zeroes :: Integral a => a -> a -> a zeroes base n = minimum . map (f . (head &&& length)) . group . pd $ base where f (a, b) = (`div` fromIntegral b) . sum . map (n `div`) $ [a^i | i <- [1.. floor (logBase (fromIntegral a) (fromIntegral n))]] pd x | x == 1 = [] | null d = [x] | otherwise = head d : pd (x `div` head d) where d = filter ((==0) . (x `mod`)) [2.. floor . sqrt . fromIntegral $ x]
51bfd7f27376005f07499aa9f150e4e1ad67c175c904e66c5a6b8d3ecfa9f0d5
polyfy/polylith
interface.clj
(ns polylith.clj.core.migrator.interface (:require [polylith.clj.core.migrator.core :as core])) (defn migrate [ws-dir workspace] (core/migrate ws-dir workspace))
null
https://raw.githubusercontent.com/polyfy/polylith/febea3d8a9b30a60397594dda3cb0f25154b8d8d/components/migrator/src/polylith/clj/core/migrator/interface.clj
clojure
(ns polylith.clj.core.migrator.interface (:require [polylith.clj.core.migrator.core :as core])) (defn migrate [ws-dir workspace] (core/migrate ws-dir workspace))
b6a2c0f9e2156b54293add5c0d4a7fcb70452005ac9806ac90506f9338e03dd3
nasa/PRECiSA
LexRawSpecLang.hs
-- Notices: -- Copyright 2020 United States Government as represented by the Administrator of the National Aeronautics and Space Administration . All Rights Reserved . -- Disclaimers No Warranty : THE SUBJECT SOFTWARE IS PROVIDED " AS IS " WITHOUT ANY WARRANTY OF ANY KIND , EITHER EXPRESSED , IMPLIED , OR STATUTORY , INCLUDING , BUT NOT LIMITED TO , ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS , ANY IMPLIED WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE , OR FREEDOM FROM INFRINGEMENT , ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE , OR ANY WARRANTY THAT DOCUMENTATION , IF PROVIDED , WILL CONFORM TO THE SUBJECT SOFTWARE . THIS AGREEMENT DOES NOT , IN ANY MANNER , CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS , RESULTING DESIGNS , HARDWARE , SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT SOFTWARE . FURTHER , GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD - PARTY SOFTWARE , IF PRESENT IN THE ORIGINAL SOFTWARE , AND DISTRIBUTES IT " AS IS . " Waiver and Indemnity : RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES GOVERNMENT , ITS CONTRACTORS AND SUBCONTRACTORS , AS WELL AS ANY PRIOR RECIPIENT . IF RECIPIENT 'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES , DEMANDS , DAMAGES , EXPENSES OR LOSSES ARISING FROM SUCH USE , INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON , OR RESULTING FROM , RECIPIENT 'S USE OF THE SUBJECT SOFTWARE , RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE UNITED STATES GOVERNMENT , ITS CONTRACTORS AND SUBCONTRACTORS , AS WELL AS ANY PRIOR RECIPIENT , TO THE EXTENT PERMITTED BY LAW . RECIPIENT 'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE , UNILATERAL TERMINATION OF THIS AGREEMENT . # OPTIONS_GHC -fno - warn - unused - binds -fno - warn - missing - signatures # # LANGUAGE CPP # {-# LINE 3 "LexSpecLang.x" #-} {-# OPTIONS -fno-warn-incomplete-patterns #-} # OPTIONS_GHC -w # module Parser.LexRawSpecLang where import qualified Data.Bits import Data.Word (Word8) import Data.Char (ord) #if __GLASGOW_HASKELL__ >= 603 #include "ghcconfig.h" #elif defined(__GLASGOW_HASKELL__) #include "config.h" #endif #if __GLASGOW_HASKELL__ >= 503 import Data.Array import Data.Array.Base (unsafeAt) #else import Array #endif alex_tab_size :: Int alex_tab_size = 8 alex_base :: Array Int Int alex_base = listArray (0 :: Int, 15) [ -8 , -99 , -103 , -37 , -13 , 60 , 124 , -93 , 307 , -95 , 0 , 292 , 391 , 490 , 369 , 381 ] alex_table :: Array Int Int alex_table = listArray (0 :: Int, 745) [ 0 , 8 , 8 , 8 , 8 , 8 , 2 , 7 , 3 , 10 , 2 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 0 , 0 , 0 , 8 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 10 , 10 , 0 , 1 , 10 , 9 , 0 , 0 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 10 , 0 , 0 , 0 , 0 , 0 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 10 , 0 , 10 , 0 , 0 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 5 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 0 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 0 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 8 , 8 , 8 , 8 , 8 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 13 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 8 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 0 , 0 , 0 , 0 , 0 , 12 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 0 , 0 , 0 , 0 , 11 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 3 , 0 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 0 , 0 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 0 , 0 , 0 , 0 , 0 , 12 , 0 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 3 , 0 , 0 , 0 , 12 , 5 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 13 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 0 , 0 , 0 , 13 , 6 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 4 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] alex_check :: Array Int Int alex_check = listArray (0 :: Int, 745) [ -1 , 9 , 10 , 11 , 12 , 13 , 105 , 110 , 45 , 102 , 105 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , -1 , -1 , -1 , 32 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 40 , 41 , -1 , 43 , 44 , 45 , -1 , -1 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 58 , -1 , -1 , -1 , -1 , -1 , -1 , 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 91 , -1 , 93 , -1 , -1 , -1 , 97 , 98 , 99 , 100 , 101 , 102 , 103 , 104 , 105 , 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , 140 , 141 , 142 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , 150 , -1 , 152 , 153 , 154 , 155 , 156 , 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , 174 , 175 , 176 , 177 , 178 , 179 , 180 , 181 , 182 , -1 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 195 , 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , 140 , 141 , 142 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , 150 , -1 , 152 , 153 , 154 , 155 , 156 , 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , 174 , 175 , 176 , 177 , 178 , 179 , 180 , 181 , 182 , -1 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , 140 , 141 , 142 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , 150 , -1 , 152 , 153 , 154 , 155 , 156 , 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , 174 , 175 , 176 , 177 , 178 , 179 , 180 , 181 , 182 , -1 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , 9 , 10 , 11 , 12 , 13 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 39 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 32 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , -1 , -1 , -1 , -1 , -1 , 63 , -1 , 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , -1 , -1 , -1 , -1 , 95 , -1 , 97 , 98 , 99 , 100 , 101 , 102 , 103 , 104 , 105 , 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , 46 , -1 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , -1 , -1 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , -1 , -1 , -1 , -1 , -1 , 63 , -1 , 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 101 , -1 , -1 , -1 , 95 , 195 , 97 , 98 , 99 , 100 , 101 , 102 , 103 , 104 , 105 , 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 39 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , -1 , -1 , -1 , -1 , 95 , 195 , 97 , 98 , 99 , 100 , 101 , 102 , 103 , 104 , 105 , 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 195 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ] alex_deflt :: Array Int Int alex_deflt = listArray (0 :: Int, 15) [ -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ] alex_accept = listArray (0 :: Int, 15) [ AlexAccNone , AlexAccNone , AlexAccNone , AlexAccNone , AlexAccNone , AlexAccNone , AlexAccNone , AlexAccNone , AlexAccSkip , AlexAcc 6 , AlexAcc 5 , AlexAcc 4 , AlexAcc 3 , AlexAcc 2 , AlexAcc 1 , AlexAcc 0 ] alex_actions = array (0 :: Int, 7) [ (6,alex_action_1) , (5,alex_action_1) , (4,alex_action_2) , (3,alex_action_2) , (2,alex_action_3) , (1,alex_action_4) , (0,alex_action_5) ] # LINE 43 " LexSpecLang.x " # tok :: (Posn -> String -> Token) -> (Posn -> String -> Token) tok f p s = f p s share :: String -> String share = id data Tok = TS !String !Int -- reserved words and symbols | TL !String -- string literals | TI !String -- integer literals | TV !String -- identifiers | TD !String -- double precision float literals | TC !String -- character literals | T_Id !String deriving (Eq,Show,Ord) data Token = PT Posn Tok | Err Posn deriving (Eq,Show,Ord) printPosn :: Posn -> String printPosn (Pn _ l c) = "line " ++ show l ++ ", column " ++ show c tokenPos :: [Token] -> String tokenPos (t:_) = printPosn (tokenPosn t) tokenPos [] = "end of file" tokenPosn :: Token -> Posn tokenPosn (PT p _) = p tokenPosn (Err p) = p tokenLineCol :: Token -> (Int, Int) tokenLineCol = posLineCol . tokenPosn posLineCol :: Posn -> (Int, Int) posLineCol (Pn _ l c) = (l,c) mkPosToken :: Token -> ((Int, Int), String) mkPosToken t@(PT p _) = (posLineCol p, prToken t) prToken :: Token -> String prToken t = case t of PT _ (TS s _) -> s PT _ (TL s) -> show s PT _ (TI s) -> s PT _ (TV s) -> s PT _ (TD s) -> s PT _ (TC s) -> s Err _ -> "#error" PT _ (T_Id s) -> s data BTree = N | B String Tok BTree BTree deriving (Show) eitherResIdent :: (String -> Tok) -> String -> Tok eitherResIdent tv s = treeFind resWords where treeFind N = tv s treeFind (B a t left right) | s < a = treeFind left | s > a = treeFind right | s == a = t resWords :: BTree resWords = b "-inf" 6 (b "+inf" 3 (b ")" 2 (b "(" 1 N N) N) (b "-" 5 (b "," 4 N N) N)) (b "]" 9 (b "[" 8 (b ":" 7 N N) N) (b "in" 10 N N)) where b s n = let bs = id s in B bs (TS bs n) unescapeInitTail :: String -> String unescapeInitTail = id . unesc . tail . id where unesc s = case s of '\\':c:cs | elem c ['\"', '\\', '\''] -> c : unesc cs '\\':'n':cs -> '\n' : unesc cs '\\':'t':cs -> '\t' : unesc cs '\\':'r':cs -> '\r' : unesc cs '\\':'f':cs -> '\f' : unesc cs '"':[] -> [] c:cs -> c : unesc cs _ -> [] ------------------------------------------------------------------- wrapper code . -- A modified "posn" wrapper. ------------------------------------------------------------------- data Posn = Pn !Int !Int !Int deriving (Eq, Show,Ord) alexStartPos :: Posn alexStartPos = Pn 0 1 1 alexMove :: Posn -> Char -> Posn alexMove (Pn a l c) '\t' = Pn (a+1) l (((c+7) `div` 8)*8+1) alexMove (Pn a l c) '\n' = Pn (a+1) (l+1) 1 alexMove (Pn a l c) _ = Pn (a+1) l (c+1) type Byte = Word8 type AlexInput = (Posn, -- current position, Char, -- previous char [Byte], -- pending bytes on the current char String) -- current input string tokens :: String -> [Token] tokens str = go (alexStartPos, '\n', [], str) where go :: AlexInput -> [Token] go inp@(pos, _, _, str) = case alexScan inp 0 of AlexEOF -> [] AlexError (pos, _, _, _) -> [Err pos] AlexSkip inp' len -> go inp' AlexToken inp' len act -> act pos (take len str) : (go inp') alexGetByte :: AlexInput -> Maybe (Byte,AlexInput) alexGetByte (p, c, (b:bs), s) = Just (b, (p, c, bs, s)) alexGetByte (p, _, [], s) = case s of [] -> Nothing (c:s) -> let p' = alexMove p c (b:bs) = utf8Encode c in p' `seq` Just (b, (p', c, bs, s)) alexInputPrevChar :: AlexInput -> Char alexInputPrevChar (p, c, bs, s) = c -- | Encode a Haskell String to a list of Word8 values, in UTF8 format. utf8Encode :: Char -> [Word8] utf8Encode = map fromIntegral . go . ord where go oc | oc <= 0x7f = [oc] | oc <= 0x7ff = [ 0xc0 + (oc `Data.Bits.shiftR` 6) , 0x80 + oc Data.Bits..&. 0x3f ] | oc <= 0xffff = [ 0xe0 + (oc `Data.Bits.shiftR` 12) , 0x80 + ((oc `Data.Bits.shiftR` 6) Data.Bits..&. 0x3f) , 0x80 + oc Data.Bits..&. 0x3f ] | otherwise = [ 0xf0 + (oc `Data.Bits.shiftR` 18) , 0x80 + ((oc `Data.Bits.shiftR` 12) Data.Bits..&. 0x3f) , 0x80 + ((oc `Data.Bits.shiftR` 6) Data.Bits..&. 0x3f) , 0x80 + oc Data.Bits..&. 0x3f ] alex_action_1 = tok (\p s -> PT p (eitherResIdent (TV . share) s)) alex_action_2 = tok (\p s -> PT p (eitherResIdent (T_Id . share) s)) alex_action_3 = tok (\p s -> PT p (eitherResIdent (TV . share) s)) alex_action_4 = tok (\p s -> PT p (TI $ share s)) alex_action_5 = tok (\p s -> PT p (TD $ share s)) {-# LINE 1 "templates/GenericTemplate.hs" #-} -- ----------------------------------------------------------------------------- -- ALEX TEMPLATE -- -- This code is in the PUBLIC DOMAIN; you may copy it freely and use -- it for any purpose whatsoever. -- ----------------------------------------------------------------------------- INTERNALS and main scanner engine alexIndexInt16OffAddr arr off = arr ! off alexIndexInt32OffAddr arr off = arr ! off quickIndex arr i = arr ! i -- ----------------------------------------------------------------------------- -- Main lexing routines data AlexReturn a = AlexEOF | AlexError !AlexInput | AlexSkip !AlexInput !Int | AlexToken !AlexInput !Int a alexScan : : - > StartCode - > AlexReturn a alexScan input__ (sc) = alexScanUser undefined input__ (sc) alexScanUser user__ input__ (sc) = case alex_scan_tkn user__ input__ (0) input__ sc AlexNone of (AlexNone, input__') -> case alexGetByte input__ of Nothing -> AlexEOF Just _ -> AlexError input__' (AlexLastSkip input__'' len, _) -> AlexSkip input__'' len (AlexLastAcc k input__''' len, _) -> AlexToken input__''' len (alex_actions ! k) Push the input through the DFA , remembering the most recent accepting -- state it encountered. alex_scan_tkn user__ orig_input len input__ s last_acc = input__ `seq` -- strict in the input let new_acc = (check_accs (alex_accept `quickIndex` (s))) in new_acc `seq` case alexGetByte input__ of Nothing -> (new_acc, input__) Just (c, new_input) -> case fromIntegral c of { (ord_c) -> let base = alexIndexInt32OffAddr alex_base s offset = (base + ord_c) check = alexIndexInt16OffAddr alex_check offset new_s = if (offset >= (0)) && (check == ord_c) then alexIndexInt16OffAddr alex_table offset else alexIndexInt16OffAddr alex_deflt s in case new_s of (-1) -> (new_acc, input__) -- on an error, we want to keep the input *before* the -- character that failed, not after. _ -> alex_scan_tkn user__ orig_input (if c < 0x80 || c >= 0xC0 then (len + (1)) else len) note that the length is increased ONLY if this is the 1st byte in a char encoding ) new_input new_s new_acc } where check_accs (AlexAccNone) = last_acc check_accs (AlexAcc a ) = AlexLastAcc a input__ (len) check_accs (AlexAccSkip) = AlexLastSkip input__ (len) check_accs (AlexAccPred a predx rest) | predx user__ orig_input (len) input__ = AlexLastAcc a input__ (len) | otherwise = check_accs rest check_accs (AlexAccSkipPred predx rest) | predx user__ orig_input (len) input__ = AlexLastSkip input__ (len) | otherwise = check_accs rest data AlexLastAcc = AlexNone | AlexLastAcc !Int !AlexInput !Int | AlexLastSkip !AlexInput !Int data AlexAcc user = AlexAccNone | AlexAcc Int | AlexAccSkip | AlexAccPred Int (AlexAccPred user) (AlexAcc user) | AlexAccSkipPred (AlexAccPred user) (AlexAcc user) type AlexAccPred user = user -> AlexInput -> Int -> AlexInput -> Bool -- ----------------------------------------------------------------------------- -- Predicates on a rule alexAndPred p1 p2 user__ in1 len in2 = p1 user__ in1 len in2 && p2 user__ in1 len in2 alexPrevCharIsPred : : AlexAccPred _ alexPrevCharIs c _ input__ _ _ = c == alexInputPrevChar input__ alexPrevCharMatches f _ input__ _ _ = f (alexInputPrevChar input__) alexPrevCharIsOneOfPred : : AlexAccPred _ alexPrevCharIsOneOf arr _ input__ _ _ = arr ! alexInputPrevChar input__ --alexRightContext :: Int -> AlexAccPred _ alexRightContext (sc) user__ _ _ input__ = case alex_scan_tkn user__ input__ (0) input__ sc AlexNone of (AlexNone, _) -> False _ -> True -- TODO: there's no need to find the longest -- match when checking the right context, just the first match will do .
null
https://raw.githubusercontent.com/nasa/PRECiSA/91e1e7543c5888ad5fb123d3462f71d085b99741/PRECiSA/src/Parser/LexRawSpecLang.hs
haskell
Notices: Disclaimers # LINE 3 "LexSpecLang.x" # # OPTIONS -fno-warn-incomplete-patterns # reserved words and symbols string literals integer literals identifiers double precision float literals character literals ----------------------------------------------------------------- A modified "posn" wrapper. ----------------------------------------------------------------- current position, previous char pending bytes on the current char current input string | Encode a Haskell String to a list of Word8 values, in UTF8 format. # LINE 1 "templates/GenericTemplate.hs" # ----------------------------------------------------------------------------- ALEX TEMPLATE This code is in the PUBLIC DOMAIN; you may copy it freely and use it for any purpose whatsoever. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Main lexing routines state it encountered. strict in the input on an error, we want to keep the input *before* the character that failed, not after. ----------------------------------------------------------------------------- Predicates on a rule alexRightContext :: Int -> AlexAccPred _ TODO: there's no need to find the longest match when checking the right context, just
Copyright 2020 United States Government as represented by the Administrator of the National Aeronautics and Space Administration . All Rights Reserved . No Warranty : THE SUBJECT SOFTWARE IS PROVIDED " AS IS " WITHOUT ANY WARRANTY OF ANY KIND , EITHER EXPRESSED , IMPLIED , OR STATUTORY , INCLUDING , BUT NOT LIMITED TO , ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS , ANY IMPLIED WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE , OR FREEDOM FROM INFRINGEMENT , ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE , OR ANY WARRANTY THAT DOCUMENTATION , IF PROVIDED , WILL CONFORM TO THE SUBJECT SOFTWARE . THIS AGREEMENT DOES NOT , IN ANY MANNER , CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS , RESULTING DESIGNS , HARDWARE , SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT SOFTWARE . FURTHER , GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD - PARTY SOFTWARE , IF PRESENT IN THE ORIGINAL SOFTWARE , AND DISTRIBUTES IT " AS IS . " Waiver and Indemnity : RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES GOVERNMENT , ITS CONTRACTORS AND SUBCONTRACTORS , AS WELL AS ANY PRIOR RECIPIENT . IF RECIPIENT 'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES , DEMANDS , DAMAGES , EXPENSES OR LOSSES ARISING FROM SUCH USE , INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON , OR RESULTING FROM , RECIPIENT 'S USE OF THE SUBJECT SOFTWARE , RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE UNITED STATES GOVERNMENT , ITS CONTRACTORS AND SUBCONTRACTORS , AS WELL AS ANY PRIOR RECIPIENT , TO THE EXTENT PERMITTED BY LAW . RECIPIENT 'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE , UNILATERAL TERMINATION OF THIS AGREEMENT . # OPTIONS_GHC -fno - warn - unused - binds -fno - warn - missing - signatures # # LANGUAGE CPP # # OPTIONS_GHC -w # module Parser.LexRawSpecLang where import qualified Data.Bits import Data.Word (Word8) import Data.Char (ord) #if __GLASGOW_HASKELL__ >= 603 #include "ghcconfig.h" #elif defined(__GLASGOW_HASKELL__) #include "config.h" #endif #if __GLASGOW_HASKELL__ >= 503 import Data.Array import Data.Array.Base (unsafeAt) #else import Array #endif alex_tab_size :: Int alex_tab_size = 8 alex_base :: Array Int Int alex_base = listArray (0 :: Int, 15) [ -8 , -99 , -103 , -37 , -13 , 60 , 124 , -93 , 307 , -95 , 0 , 292 , 391 , 490 , 369 , 381 ] alex_table :: Array Int Int alex_table = listArray (0 :: Int, 745) [ 0 , 8 , 8 , 8 , 8 , 8 , 2 , 7 , 3 , 10 , 2 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 0 , 0 , 0 , 8 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 10 , 10 , 0 , 1 , 10 , 9 , 0 , 0 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 10 , 0 , 0 , 0 , 0 , 0 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 10 , 0 , 10 , 0 , 0 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 5 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 0 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 0 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 8 , 8 , 8 , 8 , 8 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 13 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 8 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 0 , 0 , 0 , 0 , 0 , 12 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 0 , 0 , 0 , 0 , 11 , 0 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 , 3 , 0 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 14 , 0 , 0 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 15 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 0 , 0 , 0 , 0 , 0 , 12 , 0 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 3 , 0 , 0 , 0 , 12 , 5 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 13 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 0 , 0 , 0 , 13 , 6 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 13 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 4 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] alex_check :: Array Int Int alex_check = listArray (0 :: Int, 745) [ -1 , 9 , 10 , 11 , 12 , 13 , 105 , 110 , 45 , 102 , 105 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , -1 , -1 , -1 , 32 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 40 , 41 , -1 , 43 , 44 , 45 , -1 , -1 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 58 , -1 , -1 , -1 , -1 , -1 , -1 , 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 91 , -1 , 93 , -1 , -1 , -1 , 97 , 98 , 99 , 100 , 101 , 102 , 103 , 104 , 105 , 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , 140 , 141 , 142 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , 150 , -1 , 152 , 153 , 154 , 155 , 156 , 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , 174 , 175 , 176 , 177 , 178 , 179 , 180 , 181 , 182 , -1 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 195 , 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , 140 , 141 , 142 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , 150 , -1 , 152 , 153 , 154 , 155 , 156 , 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , 174 , 175 , 176 , 177 , 178 , 179 , 180 , 181 , 182 , -1 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , 140 , 141 , 142 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , 150 , -1 , 152 , 153 , 154 , 155 , 156 , 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , 174 , 175 , 176 , 177 , 178 , 179 , 180 , 181 , 182 , -1 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , 9 , 10 , 11 , 12 , 13 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 39 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 32 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , -1 , -1 , -1 , -1 , -1 , 63 , -1 , 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , -1 , -1 , -1 , -1 , 95 , -1 , 97 , 98 , 99 , 100 , 101 , 102 , 103 , 104 , 105 , 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , 46 , -1 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , -1 , -1 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , -1 , -1 , -1 , -1 , -1 , 63 , -1 , 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 101 , -1 , -1 , -1 , 95 , 195 , 97 , 98 , 99 , 100 , 101 , 102 , 103 , 104 , 105 , 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 39 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , -1 , -1 , -1 , -1 , 95 , 195 , 97 , 98 , 99 , 100 , 101 , 102 , 103 , 104 , 105 , 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 195 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ] alex_deflt :: Array Int Int alex_deflt = listArray (0 :: Int, 15) [ -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 ] alex_accept = listArray (0 :: Int, 15) [ AlexAccNone , AlexAccNone , AlexAccNone , AlexAccNone , AlexAccNone , AlexAccNone , AlexAccNone , AlexAccNone , AlexAccSkip , AlexAcc 6 , AlexAcc 5 , AlexAcc 4 , AlexAcc 3 , AlexAcc 2 , AlexAcc 1 , AlexAcc 0 ] alex_actions = array (0 :: Int, 7) [ (6,alex_action_1) , (5,alex_action_1) , (4,alex_action_2) , (3,alex_action_2) , (2,alex_action_3) , (1,alex_action_4) , (0,alex_action_5) ] # LINE 43 " LexSpecLang.x " # tok :: (Posn -> String -> Token) -> (Posn -> String -> Token) tok f p s = f p s share :: String -> String share = id data Tok = | T_Id !String deriving (Eq,Show,Ord) data Token = PT Posn Tok | Err Posn deriving (Eq,Show,Ord) printPosn :: Posn -> String printPosn (Pn _ l c) = "line " ++ show l ++ ", column " ++ show c tokenPos :: [Token] -> String tokenPos (t:_) = printPosn (tokenPosn t) tokenPos [] = "end of file" tokenPosn :: Token -> Posn tokenPosn (PT p _) = p tokenPosn (Err p) = p tokenLineCol :: Token -> (Int, Int) tokenLineCol = posLineCol . tokenPosn posLineCol :: Posn -> (Int, Int) posLineCol (Pn _ l c) = (l,c) mkPosToken :: Token -> ((Int, Int), String) mkPosToken t@(PT p _) = (posLineCol p, prToken t) prToken :: Token -> String prToken t = case t of PT _ (TS s _) -> s PT _ (TL s) -> show s PT _ (TI s) -> s PT _ (TV s) -> s PT _ (TD s) -> s PT _ (TC s) -> s Err _ -> "#error" PT _ (T_Id s) -> s data BTree = N | B String Tok BTree BTree deriving (Show) eitherResIdent :: (String -> Tok) -> String -> Tok eitherResIdent tv s = treeFind resWords where treeFind N = tv s treeFind (B a t left right) | s < a = treeFind left | s > a = treeFind right | s == a = t resWords :: BTree resWords = b "-inf" 6 (b "+inf" 3 (b ")" 2 (b "(" 1 N N) N) (b "-" 5 (b "," 4 N N) N)) (b "]" 9 (b "[" 8 (b ":" 7 N N) N) (b "in" 10 N N)) where b s n = let bs = id s in B bs (TS bs n) unescapeInitTail :: String -> String unescapeInitTail = id . unesc . tail . id where unesc s = case s of '\\':c:cs | elem c ['\"', '\\', '\''] -> c : unesc cs '\\':'n':cs -> '\n' : unesc cs '\\':'t':cs -> '\t' : unesc cs '\\':'r':cs -> '\r' : unesc cs '\\':'f':cs -> '\f' : unesc cs '"':[] -> [] c:cs -> c : unesc cs _ -> [] wrapper code . data Posn = Pn !Int !Int !Int deriving (Eq, Show,Ord) alexStartPos :: Posn alexStartPos = Pn 0 1 1 alexMove :: Posn -> Char -> Posn alexMove (Pn a l c) '\t' = Pn (a+1) l (((c+7) `div` 8)*8+1) alexMove (Pn a l c) '\n' = Pn (a+1) (l+1) 1 alexMove (Pn a l c) _ = Pn (a+1) l (c+1) type Byte = Word8 tokens :: String -> [Token] tokens str = go (alexStartPos, '\n', [], str) where go :: AlexInput -> [Token] go inp@(pos, _, _, str) = case alexScan inp 0 of AlexEOF -> [] AlexError (pos, _, _, _) -> [Err pos] AlexSkip inp' len -> go inp' AlexToken inp' len act -> act pos (take len str) : (go inp') alexGetByte :: AlexInput -> Maybe (Byte,AlexInput) alexGetByte (p, c, (b:bs), s) = Just (b, (p, c, bs, s)) alexGetByte (p, _, [], s) = case s of [] -> Nothing (c:s) -> let p' = alexMove p c (b:bs) = utf8Encode c in p' `seq` Just (b, (p', c, bs, s)) alexInputPrevChar :: AlexInput -> Char alexInputPrevChar (p, c, bs, s) = c utf8Encode :: Char -> [Word8] utf8Encode = map fromIntegral . go . ord where go oc | oc <= 0x7f = [oc] | oc <= 0x7ff = [ 0xc0 + (oc `Data.Bits.shiftR` 6) , 0x80 + oc Data.Bits..&. 0x3f ] | oc <= 0xffff = [ 0xe0 + (oc `Data.Bits.shiftR` 12) , 0x80 + ((oc `Data.Bits.shiftR` 6) Data.Bits..&. 0x3f) , 0x80 + oc Data.Bits..&. 0x3f ] | otherwise = [ 0xf0 + (oc `Data.Bits.shiftR` 18) , 0x80 + ((oc `Data.Bits.shiftR` 12) Data.Bits..&. 0x3f) , 0x80 + ((oc `Data.Bits.shiftR` 6) Data.Bits..&. 0x3f) , 0x80 + oc Data.Bits..&. 0x3f ] alex_action_1 = tok (\p s -> PT p (eitherResIdent (TV . share) s)) alex_action_2 = tok (\p s -> PT p (eitherResIdent (T_Id . share) s)) alex_action_3 = tok (\p s -> PT p (eitherResIdent (TV . share) s)) alex_action_4 = tok (\p s -> PT p (TI $ share s)) alex_action_5 = tok (\p s -> PT p (TD $ share s)) INTERNALS and main scanner engine alexIndexInt16OffAddr arr off = arr ! off alexIndexInt32OffAddr arr off = arr ! off quickIndex arr i = arr ! i data AlexReturn a = AlexEOF | AlexError !AlexInput | AlexSkip !AlexInput !Int | AlexToken !AlexInput !Int a alexScan : : - > StartCode - > AlexReturn a alexScan input__ (sc) = alexScanUser undefined input__ (sc) alexScanUser user__ input__ (sc) = case alex_scan_tkn user__ input__ (0) input__ sc AlexNone of (AlexNone, input__') -> case alexGetByte input__ of Nothing -> AlexEOF Just _ -> AlexError input__' (AlexLastSkip input__'' len, _) -> AlexSkip input__'' len (AlexLastAcc k input__''' len, _) -> AlexToken input__''' len (alex_actions ! k) Push the input through the DFA , remembering the most recent accepting alex_scan_tkn user__ orig_input len input__ s last_acc = let new_acc = (check_accs (alex_accept `quickIndex` (s))) in new_acc `seq` case alexGetByte input__ of Nothing -> (new_acc, input__) Just (c, new_input) -> case fromIntegral c of { (ord_c) -> let base = alexIndexInt32OffAddr alex_base s offset = (base + ord_c) check = alexIndexInt16OffAddr alex_check offset new_s = if (offset >= (0)) && (check == ord_c) then alexIndexInt16OffAddr alex_table offset else alexIndexInt16OffAddr alex_deflt s in case new_s of (-1) -> (new_acc, input__) _ -> alex_scan_tkn user__ orig_input (if c < 0x80 || c >= 0xC0 then (len + (1)) else len) note that the length is increased ONLY if this is the 1st byte in a char encoding ) new_input new_s new_acc } where check_accs (AlexAccNone) = last_acc check_accs (AlexAcc a ) = AlexLastAcc a input__ (len) check_accs (AlexAccSkip) = AlexLastSkip input__ (len) check_accs (AlexAccPred a predx rest) | predx user__ orig_input (len) input__ = AlexLastAcc a input__ (len) | otherwise = check_accs rest check_accs (AlexAccSkipPred predx rest) | predx user__ orig_input (len) input__ = AlexLastSkip input__ (len) | otherwise = check_accs rest data AlexLastAcc = AlexNone | AlexLastAcc !Int !AlexInput !Int | AlexLastSkip !AlexInput !Int data AlexAcc user = AlexAccNone | AlexAcc Int | AlexAccSkip | AlexAccPred Int (AlexAccPred user) (AlexAcc user) | AlexAccSkipPred (AlexAccPred user) (AlexAcc user) type AlexAccPred user = user -> AlexInput -> Int -> AlexInput -> Bool alexAndPred p1 p2 user__ in1 len in2 = p1 user__ in1 len in2 && p2 user__ in1 len in2 alexPrevCharIsPred : : AlexAccPred _ alexPrevCharIs c _ input__ _ _ = c == alexInputPrevChar input__ alexPrevCharMatches f _ input__ _ _ = f (alexInputPrevChar input__) alexPrevCharIsOneOfPred : : AlexAccPred _ alexPrevCharIsOneOf arr _ input__ _ _ = arr ! alexInputPrevChar input__ alexRightContext (sc) user__ _ _ input__ = case alex_scan_tkn user__ input__ (0) input__ sc AlexNone of (AlexNone, _) -> False _ -> True the first match will do .
10f7c766bfe2e0abd31365309dbad8a62efc5dbdd90db428b5143802fbebb0df
reanimate/reanimate
doc_seqA.hs
#!/usr/bin/env stack -- stack runghc --package reanimate module Main(main) where import Reanimate import Reanimate.Builtin.Documentation main :: IO () main = reanimate $ docEnv (drawBox `seqA` drawCircle)
null
https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/examples/doc_seqA.hs
haskell
stack runghc --package reanimate
#!/usr/bin/env stack module Main(main) where import Reanimate import Reanimate.Builtin.Documentation main :: IO () main = reanimate $ docEnv (drawBox `seqA` drawCircle)
b0518cf9dd1cb141c00200834474d3e4df82c3cd4d433d324b601fe7053b8c01
dselsam/arc
Grid.hs
Copyright ( c ) 2020 Microsoft Corporation . All rights reserved . Released under Apache 2.0 license as described in the file LICENSE . Authors : , , . # LANGUAGE MultiParamTypeClasses # # LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # # LANGUAGE InstanceSigs # # LANGUAGE TypeFamilies # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE DeriveGeneric # {-# LANGUAGE StrictData #-} module Lib.Grid where import GHC.Generics (Generic, Generic1) import Control.DeepSeq import qualified Data.Maybe as Maybe import Data.Foldable import qualified Data.List as List import Data.Map (Map) import Data.Hashable import Data.Vector.Instances import qualified Data.Map as Map import Data.Maybe (listToMaybe, isJust) import Data.Monoid import Data.Monoid (mempty) import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Vector as BVector import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as Vector import Data.Vector.Unboxed.Base (Unbox) import Data.Vector.Unboxed.Deriving import Debug.Trace import Lib.Axis import qualified Lib.Axis as Axis import Lib.Direction (Direction(..)) import qualified Lib.Direction as Direction import Lib.Blank (HasBlank(..), blank, isBlank, nonBlank) import qualified Lib.Blank as Blank import Lib.Color (Color, enumColorsCtx) import qualified Lib.Dims as Dims import Lib.Dims (Dims (Dims)) import Synth1.Synth1Context import qualified Lib.Index as Index import Lib.Index (Index (Index)) import qualified Lib.Line as Line import Util.Imports import qualified Util.Int as Int import Util.List (uncurry3, range) import qualified Util.Int as Int import qualified Util.List as List import Lib.Shape (Shape) import qualified Lib.Shape as Shape import Lib.Rect (Rect(Rect)) import qualified Lib.Rect as Rect import qualified Lib.BGrid as Box import Search.SearchT import Synth1.Basic import Synth.Ex (Ex(..)) import qualified Synth.Ex as Ex data Grid a = Grid { dims :: Dims, gridData :: !(Vector a) } deriving (Eq, Ord, Generic, Generic1) instance NFData a => NFData (Grid a) instance (Unbox a, Hashable a) => Hashable (Grid a) where hashWithSalt salt g = hashWithSalt salt (dims g, gridData g) nRows g = Dims.nRows . dims $ g nCols g = Dims.nCols . dims $ g nCells g = nRows g * nCols g fromArray :: (Unbox a) => Dims -> Vector a -> Grid a fromArray dims v | Dims.nCells dims == Vector.length v = Grid dims v fromList :: (Unbox a) => Dims -> [a] -> Grid a fromList dims elems = fromArray dims (Vector.fromList elems) fromLists :: (Unbox a) => [[a]] -> Grid a fromLists [] = Grid (Dims 0 0) (Vector.fromList []) fromLists elems = let m = length elems n = length (head elems) in fromArray (Dims m n) (Vector.fromList $ concat elems) fromBox :: (Unbox a) => Box.Grid a -> Grid a fromBox box = Grid (Box.dims box) (Vector.fromList $ Box.toList box) fromIntLists :: [[Int]] -> Grid Int fromIntLists elems = fromLists elems -- TODO: duplication fromFuncM :: (Unbox a, Monad m) => Dims -> (Index -> m a) -> m (Grid a) fromFuncM dims@(Dims m n) f = do elems <- Vector.generateM (m*n) $ \i -> f (Dims.int2index dims i) pure $ fromArray dims elems fromFunc :: (Unbox a) => Dims -> (Index -> a) -> Grid a fromFunc dims@(Dims m n) f = fromArray dims $ Vector.generate (m*n) $ \i -> f (Dims.int2index dims i) const :: (Unbox a) => Dims -> a -> Grid a const dims@(Dims m n) x = fromArray dims $ Vector.replicate (m*n) x allBlank :: (Unbox a, HasBlank a) => Grid a -> Bool allBlank g = Dims.all (dims g) $ \idx -> isBlank (getG g idx) nBlanks :: (Unbox a, HasBlank a) => Grid a -> Int nBlanks g = Dims.iter (dims g) 0 $ \acc idx -> if isBlank (getG g idx) then pure (acc + 1) else pure acc nNonBlanks :: (Unbox a, HasBlank a) => Grid a -> Int nNonBlanks g = Dims.iter (dims g) 0 $ \acc idx -> if nonBlank (getG g idx) then pure (acc + 1) else pure acc nPoints g = let (Dims nRows nCols) = dims g in nRows * nCols nonBlankFrac :: (Unbox a, HasBlank a) => Grid a -> Float nonBlankFrac g = (fromIntegral $ nNonBlanks g)/(fromIntegral $ nPoints g) nVal :: (Unbox a, HasBlank a) => Grid a -> a -> Int nVal g x = Dims.iter (dims g) 0 $ \acc idx -> if (getG g idx) == x then pure (acc + 1) else pure acc -- g1 takes precedence! union :: (Unbox a, HasBlank a) => Grid a -> Grid a -> Maybe (Grid a) union g1 g2 = do guard $ sameDims g1 g2 pure $ fromFunc (dims g1) $ \idx -> if nonBlank (getG g1 idx) then (getG g1 idx) else (getG g2 idx) safeUnion :: (Unbox a, HasBlank a) => Grid a -> Grid a -> Maybe (Grid a) safeUnion g1 g2 = do guard $ sameDims g1 g2 fromFuncM (dims g1) $ \idx -> do let x1 = getG g1 idx let x2 = getG g2 idx when (nonBlank x1 && nonBlank x2) $ guard $ x1 == x2 pure $ if isBlank x1 then x2 else x1 toOffset :: (Unbox a) => Grid a -> Index -> Int toOffset g (Index i j) = i * nCols g + j toOffsetSafe :: (Unbox a) => Grid a -> Index -> Maybe Int toOffsetSafe g idx = do guard $ Dims.inBounds (dims g) idx pure $ toOffset g idx getD :: (Unbox a, HasBlank a) => Grid a -> Index -> a getD g idx = case toOffsetSafe g idx of Just i -> gridData g Vector.! i Nothing -> blank get :: (Unbox a) => Grid a -> Index -> a get g idx = gridData g Vector.! (toOffset g idx) -- Just for this file, since we can't qualify `Grid` here getG :: (Unbox a) => Grid a -> Index -> a getG = Lib.Grid.get setD :: (Unbox a) => Grid a -> a -> Index -> Grid a setD g@(Grid gDims gData) val idx = case toOffsetSafe g idx of Just i -> Grid gDims $ gData Vector.// [(i, val)] Nothing -> g set :: (Unbox a) => Grid a -> a -> Index -> Grid a set g@(Grid gDims gData) val idx = Grid gDims $ gData Vector.// [(offset, val)] where offset = (toOffset g idx) setPairsD :: (Unbox a) => Grid a -> [(Index, a)] -> Grid a setPairsD g@(Grid gDims gData) pairs = runIdentity $ do let mappedPairs = flip Prelude.mapM pairs $ \(idx, val) -> case toOffsetSafe g idx of Just i -> pure $ (i, val) Nothing -> Nothing case mappedPairs of Just mPairs -> pure $ Grid gDims $ gData Vector.// mPairs Nothing -> pure g -- unsafe setPairs :: (Unbox a) => Grid a -> [(Index, a)] -> Grid a setPairs g@(Grid gDims gData) pairs = let mappedPairs = flip Prelude.map pairs $ \(idx, val) -> (toOffset g idx, val) in Grid gDims $ gData Vector.// mappedPairs -- unsafe setIdxsToVal :: (Unbox a) => Grid a -> [Index] -> a -> Grid a setIdxsToVal g@(Grid gDims gData) idxs val = let pairs = flip Prelude.map idxs (\idx -> (idx, val)) in Lib.Grid.setPairs g pairs getRow :: (Unbox a) => Grid a -> Int -> [a] getRow g rIdx = [getG g (Index rIdx k) | k <- range $ nCols g] getCol :: (Unbox a) => Grid a -> Int -> [a] getCol g cIdx = [getG g (Index k cIdx) | k <- range $ nRows g] nonBlankRows :: (Unbox a, HasBlank a) => Grid a -> [Int] nonBlankRows g = flip List.filter (range $ nRows g) $ \i -> flip any (getRow g i) $ \val -> nonBlank val nonBlankCols :: (Unbox a, HasBlank a) => Grid a -> [Int] nonBlankCols g = flip List.filter (range $ nCols g) $ \j -> flip any (getCol g j) $ \val -> nonBlank val sameBlanks :: (Unbox a, HasBlank a) => Grid a -> Grid a -> Bool sameBlanks g1 g2 = sameDims g1 g2 && core g1 g2 where core g1 g2 = Dims.all (dims g1) $ \idx -> isBlank (getG g1 idx) == isBlank (getG g2 idx) showGrid :: (Unbox a, Show a) => Grid a -> String showGrid g = let header = "Grid " ++ show (nRows g) ++ " " ++ show (nCols g) ++ "\n" in Int.iter (nRows g) header $ \acc i -> acc ++ "\n" ++ (showRow g i) where showRow :: (Unbox a, Show a) => Grid a -> Int -> String showRow g i = Int.iter (nCols g) "" $ \acc j -> acc ++ " " ++ show (getG g (Index i j)) ++ " " instance (Unbox a, Show a) => Show (Grid a) where show = showGrid neighbors :: (Unbox a) => Grid a -> Index -> [Index] neighbors input idx0 = do ax <- [Horizontal, Vertical, DownRight, DownLeft] dir <- [Normal, Reverse] let idx = idx0 + Index.scale (Direction.toScale dir) (Axis.toDelta ax) guard $ Dims.inBounds (dims input) idx pure idx neighborsOrtho :: (Unbox a) => Grid a -> Index -> [Index] neighborsOrtho input idx0 = do ax <- [Horizontal, Vertical] dir <- [Normal, Reverse] let idx = idx0 + Index.scale (Direction.toScale dir) (Axis.toDelta ax) guard $ Dims.inBounds (dims input) idx pure idx neighborsDiag :: (Unbox a) => Grid a -> Index -> [Index] neighborsDiag input idx0 = do ax <- [DownRight, DownLeft] dir <- [Normal, Reverse] let idx = idx0 + Index.scale (Direction.toScale dir) (Axis.toDelta ax) guard $ Dims.inBounds (dims input) idx pure idx showGridDiff :: Grid Color -> Grid Color -> Box.Grid String showGridDiff g1 g2 | sameDims g1 g2 = Box.fromFunc (dims g1) $ \idx -> if getG g1 idx == getG g2 idx then " " ++ show (getG g1 idx) ++ " " else "[" ++ show (getG g1 idx) ++ "|" ++ show (getG g2 idx) ++ "]" | otherwise = Box.const (Dims 1 1) (show (dims g1) ++ " != " ++ show (dims g2)) g1 is a subset of subset :: (Unbox a, HasBlank a, Eq a) => Grid a -> Grid a -> Bool subset g1 g2 = sameDims g1 g2 && subsetElems g1 g2 where subsetElems g1 g2 = Dims.all (dims g1) $ \idx -> (nonBlank $ getG g1 idx) <= (getG g1 idx == getG g2 idx) isNull :: (Unbox a) => Grid a -> Bool isNull g = dims g == Dims 0 0 transpose :: (Unbox a) => Grid a -> Grid a transpose g = fromFunc (Dims.transpose $ dims g) $ getG g . Index.transpose sameDims :: (Unbox a) => Grid a -> Grid b -> Bool sameDims g1 g2 = dims g1 == dims g2 beqUpto :: (Unbox a, Eq a) => Grid a -> Grid a -> Grid Bool -> Bool beqUpto g1 g2 mask = (isNull mask && g1 == g2) || (sameDims g1 g2 && sameDims g1 mask && beqUptoCore g1 g2 mask) where beqUptoCore g1 g2 mask = Dims.all (dims g1) $ \idx -> getG mask idx || getG g1 idx == getG g2 idx wherever appears in g1 , it is also val in interpretation : g1 is input , is output subsetForVal :: (Unbox a, Eq a) => Grid a -> Grid a -> a -> Bool -- redundant sameDims check, but helpful short circuit subsetForVal g1 g2 val = (sameDims g1 g2) && beqUpto g1 g2 mask where mask = fromFunc (dims g1) $ \idx -> if (getG g1 idx) == val then False else True allSameDims :: (Unbox a, Unbox b) => Box.Grid (Grid a) -> Box.Grid (Grid b) -> Bool allSameDims g1 g2 = Box.sameDims g1 g2 && (Dims.all (Box.dims g1) $ \idx -> sameDims (Box.getG g1 idx) (Box.getG g2 idx)) uniformDims :: (Unbox a) => Box.Grid (Grid a) -> Bool uniformDims gs = let innerDims = dims (Box.get gs (Index 0 0)) in Dims.all (Box.dims gs) $ \idx -> dims (Box.get gs idx) == innerDims containsVal :: (Unbox a, Eq a) => a -> Grid a -> Bool containsVal x g = Dims.any (dims g) $ \idx -> getG g idx == x -- TODO: throw error or keep Maybe? concatRows :: (Unbox a) => Grid a -> Grid a -> Maybe (Grid a) concatRows g1 g2 = do guard $ nCols g1 == nCols g2 pure $ fromFunc (Dims (nRows g1 + nRows g2) (nCols g2)) $ \idx@(Index i j) -> if i < nRows g1 then getG g1 (Index i j) else getG g2 (Index (i-nRows g1) j) concatCols :: (Unbox a) => Grid a -> Grid a -> Maybe (Grid a) concatCols g1 g2 = do guard $ nRows g1 == nRows g2 pure $ fromFunc (Dims (nRows g1) (nCols g1 + nCols g2)) $ \idx@(Index i j) -> if i < nCols g1 then getG g1 (Index i j) else getG g2 (Index i (j-nCols g1)) map :: (Unbox a, Unbox b) => (Index -> a -> b) -> Grid a -> Grid b map f g = fromFunc (dims g) $ \idx -> f idx $ getG g idx mapM :: (Unbox a, Unbox b, Monad m) => (Index -> a -> m b) -> Grid a -> m (Grid b) mapM f g = fromFuncM (dims g) $ \idx -> f idx $ getG g idx filter :: (Unbox a, HasBlank a) => (Index -> a -> Bool) -> Grid a -> Grid a filter f g = flip Lib.Grid.map g $ \idx x -> if f idx x then x else blank upscale :: (Unbox a) => Grid a -> Dims -> Box.Grid (Grid a) upscale g ds@(Dims km kn) = Box.fromFunc (dims g) (\idx -> Lib.Grid.const ds (getG g idx)) tile :: (Unbox a) => Grid a -> Dims -> Box.Grid (Grid a) tile g dims = Box.fromFunc dims $ \idx -> g TODO : these are pointlessly slow , better to use a Foldable / / whatever whenever needed toList :: (Unbox a) => Grid a -> [a] toList g = reverse $ Dims.iter (dims g) [] $ \acc idx -> pure $ (getG g idx):acc toListWithIndices :: (Unbox a) => Grid a -> [(Index, a)] toListWithIndices g = reverse $ Dims.iter (dims g) [] $ \acc idx -> pure $ (idx, getG g idx):acc ----------------- Subgrids ----------------- getSubgridUnsafe :: (Unbox a) => Grid a -> Dims -> Index -> Grid a getSubgridUnsafe g dims idx0 = fromFunc dims $ \idx -> getG g (idx0 + idx) getSubgridOpt :: (Unbox a) => Grid a -> Dims -> Index -> Maybe (Grid a) getSubgridOpt g sgDims@(Dims dx dy) idx0@(Index i j) = do let Dims gx gy = dims g guard $ dx + i <= gx guard $ dy + j <= gy pure $ fromFunc sgDims $ \idx -> getG g (idx0 + idx) findSubgrids :: (Unbox a) => Grid a -> Dims -> (Grid a -> Bool) -> [Index] findSubgrids g dims2@(Dims m2 n2) p = let Dims m1 n1 = dims g in Dims.iter (Dims (m1+1-m2) (n1+1-n2)) [] $ \acc idx -> pure $ if p (getSubgridUnsafe g dims2 idx) then idx:acc else acc replaceSubgridUnsafeM :: (Unbox a, Monad m) => Grid a -> Dims -> Index -> (Grid a -> m (Grid a)) -> m (Grid a) replaceSubgridUnsafeM grid dims idx0 grid2grid = let subgrid = getSubgridUnsafe grid dims idx0 in flip Lib.Grid.mapM grid $ \idx c -> do if Dims.inBounds dims (idx - idx0) then do newSubgrid <- grid2grid subgrid pure $ Lib.Grid.get newSubgrid (idx - idx0) else pure c ----------------- -- Combinator Instances ----------------- instance Functor Grid where fmap : : ( Unbox a ) = > ( a - > b ) - > Grid a - > Grid b fmap f = Lib.Grid.map ( \ _ - > f ) instance Foldable Grid where foldMap : : ( Monoid m ) = > ( a - > m ) - > Grid a - > m foldMap f g = Dims.iter ( ) $ \acc idx - > pure $ acc < > f ( ) instance Grid where -- TODO : does this get used ? Why not have a typeclass just for mapM and friends ? -- Can we get away with this ? ? traverse : : ( Applicative m ) = > ( a - > m b ) - > Grid a - > m ( Grid b ) traverse _ _ = error " traverse not implemented for Grid " instance Functor Grid where fmap :: (Unbox a) => (a -> b) -> Grid a -> Grid b fmap f = Lib.Grid.map (\_ -> f) instance Foldable Grid where foldMap :: (Monoid m) => (a -> m) -> Grid a -> m foldMap f g = Dims.iter (dims g) mempty $ \acc idx -> pure $ acc <> f (getG g idx) instance Traversable Grid where -- TODO: does this get used? Why not have a typeclass just for mapM and friends? -- Can we get away with this?? traverse :: (Applicative m) => (a -> m b) -> Grid a -> m (Grid b) traverse _ _ = error "traverse not implemented for Grid" -} --mapM :: (Monad m) => (a -> m b) -> Grid a -> m (Grid b) --mapM f = Lib.Grid.mapM (\_ -> f) sequence : : = > Grid ( m a ) - > m ( Grid a ) sequence g = fromFuncM ( ) $ ----------------- -- Partitioning ----------------- type UnpartitionFn a = Box.Grid (Grid a) -> Grid a partitionEven :: (Unbox a) => Dims -> Dims -> Grid a -> Maybe (Box.Grid (Grid a)) partitionEven outerDims@(Dims mOut nOut) innerDims@(Dims mIn nIn) g = do guard $ nRows g == mOut * mIn guard $ nCols g == nOut * nIn pure $ Box.fromFunc outerDims $ \(Index i j) -> getSubgridUnsafe g innerDims (Index (i * mIn) (j * nIn)) partitionEvenOuterDims :: (Unbox a) => Dims -> Grid a -> Maybe (Box.Grid (Grid a)) partitionEvenOuterDims dims@(Dims m n) g = do guard $ mod (nRows g) m == 0 guard $ mod (nCols g) n == 0 partitionEven dims (Dims (div (nRows g) m) (div (nCols g) n)) g partitionEvenInnerDims :: (Unbox a) => Dims -> Grid a -> Maybe (Box.Grid (Grid a)) partitionEvenInnerDims dims@(Dims m n) g = do guard $ mod (nRows g) m == 0 guard $ mod (nCols g) n == 0 partitionEven (Dims (div (nRows g) m) (div (nCols g) n)) dims g unpartitionEven :: (Unbox a) => Box.Grid (Grid a) -> Maybe (Grid a) unpartitionEven gs = do let innerDims = dims (Box.getG gs (Index 0 0)) guard $ Dims.all (Box.dims gs) $ \idx -> dims (Box.getG gs idx) == innerDims let Dims mIn nIn = innerDims let newDims = Dims (Box.nRows gs * mIn) (Box.nCols gs * nIn) pure $ fromFunc newDims $ \(Index i j) -> let g = Box.getG gs $ Index (div i mIn) (div j nIn) in getG g $ Index (mod i mIn) (mod j nIn) data RePartitionData = RePartitionData { structure :: Grid (Dims, Index) } -- TODO: this and others that are unsafe may cause problems! -- Worth always returning maybes? rePartitionNoSepWith :: (Unbox a) => Grid a -> RePartitionData -> Maybe (Box.Grid (Grid a)) rePartitionNoSepWith g (RePartitionData structure) = do let outerDims = dims structure Box.fromFuncM outerDims $ \outerIdx -> do let (innerDims, oldIdx) = getG structure outerIdx getSubgridOpt g innerDims oldIdx computeRePartitionData :: (Unbox a) => Box.Grid (Grid a) -> Maybe RePartitionData computeRePartitionData gs = do guard $ Int.all (Box.nRows gs) $ \i -> Int.allSame (Box.nCols gs) $ \j -> nRows (Box.getG gs (Index i j)) guard $ Int.all (Box.nCols gs) $ \j -> Int.allSame (Box.nRows gs) $ \i -> nCols (Box.getG gs (Index i j)) let nRowList = Prelude.map (\i -> nRows (Box.getG gs (Index i 0))) (List.range $ Box.nRows gs) let nColList = Prelude.map (\j -> nCols (Box.getG gs (Index 0 j))) (List.range $ Box.nCols gs) let rowOffsets = 0 : scanl1 (+) nRowList let colOffsets = 0 : scanl1 (+) nColList pure $ RePartitionData $ fromFunc (Dims (length nRowList) (length nColList)) $ \idx@(Index i j) -> let innerDims :: Dims = dims (Box.getG gs idx) innerIdx :: Index = Index (rowOffsets List.!! i) (colOffsets List.!! j) in (innerDims, innerIdx) unpartitionNoSep :: (Unbox a) => Box.Grid (Grid a) -> Maybe (Grid a) unpartitionNoSep gs = do guard $ Int.all (Box.nRows gs) $ \i -> Int.allSame (Box.nCols gs) $ \j -> nRows (Box.getG gs (Index i j)) guard $ Int.all (Box.nCols gs) $ \j -> Int.allSame (Box.nRows gs) $ \i -> nCols (Box.getG gs (Index i j)) let nRowList = Prelude.map (\i -> nRows (Box.getG gs (Index i 0))) (List.range $ Box.nRows gs) let nColList = Prelude.map (\j -> nCols (Box.getG gs (Index 0 j))) (List.range $ Box.nCols gs) let rowOffsets = scanl1 (+) nRowList let colOffsets = scanl1 (+) nColList pure $ fromFunc (Dims (sum nRowList) (sum nColList)) $ \(Index i j) -> runIdentity $ do let Just (iOuter, iInner) = flip List.first (zip3 [0..] (0:init rowOffsets) rowOffsets) $ \(iOuter, start, end) -> if i >= start && i < end then Just (iOuter, i - start) else Nothing let Just (jOuter, jInner) = flip List.first (zip3 [0..] (0:init colOffsets) colOffsets) $ \(jOuter, start, end) -> if j >= start && j < end then Just (jOuter, j - start) else Nothing let g = Box.getG gs (Index iOuter jOuter) pure $ getG g (Index iInner jInner) data PartitionSepData = PartitionSepData { hLines :: [Int], vLines :: [Int] } deriving (Eq, Ord, Show) sameUnpartitionSep :: (Unbox a, HasBlank a) => PartitionSepData -> Grid a -> Grid a -> Bool sameUnpartitionSep pData g1 g2 = sameDims g1 g2 && List.all (\i -> Int.all (nCols g1) (\j -> getG g1 (Index i j) == getG g2 (Index i j))) (hLines pData) && List.all (\j -> Int.all (nRows g1) (\i -> getG g1 (Index i j) == getG g2 (Index i j))) (vLines pData) unpartitionSep :: (Unbox a, HasBlank a) => Grid a -> PartitionSepData -> Box.Grid (Grid a) -> Maybe (Grid a) unpartitionSep g0 (PartitionSepData hLines vLines) gs = do guard $ Int.all (Box.nRows gs) $ \i -> Int.allSame (Box.nCols gs) $ \j -> nRows (Box.getG gs (Index i j)) guard $ Int.all (Box.nCols gs) $ \j -> Int.allSame (Box.nRows gs) $ \i -> nCols (Box.getG gs (Index i j)) let rowStartCounts = computeSepStartCounts (nRows g0) hLines let colStartCounts = computeSepStartCounts (nCols g0) vLines pure $ fromFunc (dims g0) $ \idx@(Index i j) -> if elem i hLines || elem j vLines then getG g0 idx else let (outerRow, innerRow) = findOffsets rowStartCounts i (outerCol, innerCol) = findOffsets colStartCounts j in getG (Box.getG gs (Index outerRow outerCol)) (Index innerRow innerCol) where findOffsets :: [(Int, Int)] -> Int -> (Int, Int) findOffsets rowStartCounts i = Maybe.fromJust $ List.first (\(outerRow, (rowStart, nRows)) -> do guard $ rowStart <= i && i < rowStart + nRows pure (outerRow, i - rowStart)) (List.zip [0..] rowStartCounts) partitionSepWith :: (Unbox a, HasBlank a) => Grid a -> PartitionSepData -> Maybe (Box.Grid (Grid a)) partitionSepWith g (PartitionSepData hLines vLines) = do let rowStartCounts = computeSepStartCounts (nRows g) hLines let colStartCounts = computeSepStartCounts (nCols g) vLines guard $ length rowStartCounts > 0 && length colStartCounts > 0 let gs = Box.fromFunc (Dims (length rowStartCounts) (length colStartCounts)) $ \(Index i j) -> let (rowStart, nRows) = rowStartCounts List.!! i (colStart, nCols) = colStartCounts List.!! j in getSubgridUnsafe g (Dims nRows nCols) (Index rowStart colStart) pure gs computeSepStartCounts :: Int -> [Int] -> [(Int, Int)] computeSepStartCounts k lines = let segments = List.zip ([-1] ++ lines) (lines ++ [k]) in Prelude.map (\(start, next) -> (start + 1, next-start-1)) $ List.filter (\(start, next) -> next > start + 1) segments ----------------- Coloring Utilities ----------------- changeVal :: (Unbox a, Eq a) => Grid a -> a -> a -> Grid a changeVal g val1 val2 = flip Lib.Grid.map g $ \_ val -> if val == val1 then val2 else val swapVals :: (Unbox a, Eq a) => Grid a -> a -> a -> Grid a swapVals g val1 val2 = flip Lib.Grid.map g $ \_ val -> if val == val1 then val2 else if val == val2 then val1 else val distinctValsInGrids :: (Unbox a, Eq a, Ord a) => (a -> Bool) -> [Grid a] -> Set a distinctValsInGrids f gs = List.reduce (Set.union) id $ flip Prelude.map gs (\g -> distinctVals f g) pickColor :: (Unbox a, Monad m, Eq a, Ord a, HasBlank a) => SearchT m (Grid a -> Maybe a) pickColor = do choice "Grid.pickColor" [ ("majorityVal", pure (\g -> do let gMajority = fst (majorityVals g) guard $ (length gMajority) == 1 pure $ head gMajority)) , ("minorityVal", pure (\g -> do let gMinority = fst (minorityVals g) guard $ (length gMinority) == 1 pure $ head gMinority)) , ("majorityNonBlankVal", pure (\g -> do let (gMajority, maxCount) = majorityNonBlankVals g guard $ (length gMajority) == 1 && maxCount > 0 pure $ head gMajority)) , ("minorityNonBlankVal", pure (\g -> do let (gMinority, minCount) = minorityNonBlankVals g guard $ (length gMinority) == 1 && minCount > 0 pure $ head gMinority)) ] FIXME : should this just be StdGoal - > SearchT m ( Ex Color ) ? enumRelevantColors :: (Monad m, HasTrainTest m, HasSynth1Context m Color) => Ex (Grid Color) -> Ex.ForTrain (Grid Color) -> SearchT m (Ex Color) enumRelevantColors inputs outputs = choice "enumRelevantColors" [ ("ctx", synthCtx) , ("noCtx", do let distinctColors = distinctValsInGrids (\_ -> True) $ (Ex.toBigList inputs) ++ outputs c <- oneOf "Color.enumVals" $ flip Prelude.map (Data.Foldable.toList distinctColors) $ \k -> (show k, k) Ex.map (\_ -> c) <$> getDummyEx) , ("func", do phi <- pickColor (mappedColors :: Ex Color) <- liftO $ flip Ex.mapM inputs (\ig -> phi ig) pure $ mappedColors) ] | enumRelevantInts : : Ex ( Grid Color ) - > [ ( [ ] , Int , Maybe ( Ex Int ) ) ] enumRelevantInts inputs = [ ( " m - 1 " , 0 , pure $ Ex.map ( \ig - > ( Lib . Grid.nRows ig ) - 1 ) inputs ) , ( " n - 1 " , 0 , pure $ Ex.map ( \ig - > ( Lib . Grid.nCols ig ) - 1 ) inputs ) , ( " middleRow " , 1 , do guard $ flip Ex.all inputs $ \ig - > ( ( Lib . Grid.nRows ig ) ` mod ` 2 ) = = 1 pure $ flip Ex.map inputs $ \ig - > ( ( Lib . Grid.nRows ig ) ` div ` 2 ) + 1 ) , ( " middleCol " , 1 , do guard $ flip Ex.all inputs $ \ig - > ( ( Lib . Grid.nCols ig ) ` mod ` 2 ) = = 1 pure $ flip Ex.map inputs $ \ig - > ( ( Lib . Grid.nCols ig ) ` div ` 2 ) + 1 ) , ( " nDistinctVals " , 2 , pure $ Ex.map ( \ig - > Lib . Grid.nDistinctVals ( \ _ - > True ) ig ) inputs ) , ( " nDistinctNonBlanks " , 2 , pure $ Ex.map ( \ig - > Lib . Grid.nDistinctVals ig ) inputs ) ] enumRelevantInts :: Ex (Grid Color) -> [([Char], Int, Maybe (Ex Int))] enumRelevantInts inputs = [ ("m - 1", 0, pure $ Ex.map (\ig -> (Lib.Grid.nRows ig) - 1) inputs) , ("n - 1", 0, pure $ Ex.map (\ig -> (Lib.Grid.nCols ig) - 1) inputs) , ("middleRow", 1, do guard $ flip Ex.all inputs $ \ig -> ((Lib.Grid.nRows ig) `mod` 2) == 1 pure $ flip Ex.map inputs $ \ig -> ((Lib.Grid.nRows ig) `div` 2) + 1) , ("middleCol", 1, do guard $ flip Ex.all inputs $ \ig -> ((Lib.Grid.nCols ig) `mod` 2) == 1 pure $ flip Ex.map inputs $ \ig -> ((Lib.Grid.nCols ig) `div` 2) + 1) , ("nDistinctVals", 2, pure $ Ex.map (\ig -> Lib.Grid.nDistinctVals (\_ -> True) ig) inputs) , ("nDistinctNonBlanks", 2, pure $ Ex.map (\ig -> Lib.Grid.nDistinctVals nonBlank ig) inputs) ] -} enumRelevantInts :: (Monad m) => Ex (Grid Color) -> SearchT m (Ex Int) enumRelevantInts inputs = choice "enumRelevantInts" [ ("m - 1", pure $ Ex.map (\ig -> (Lib.Grid.nRows ig) - 1) inputs) , ("n - 1", pure $ Ex.map (\ig -> (Lib.Grid.nCols ig) - 1) inputs) , ("middleRow", do guard $ flip Ex.all inputs $ \ig -> ((Lib.Grid.nRows ig) `mod` 2) == 1 pure $ flip Ex.map inputs $ \ig -> ((Lib.Grid.nRows ig) `div` 2) + 1) , ("middleCol", do guard $ flip Ex.all inputs $ \ig -> ((Lib.Grid.nCols ig) `mod` 2) == 1 pure $ flip Ex.map inputs $ \ig -> ((Lib.Grid.nCols ig) `div` 2) + 1) , ("nDistinctVals", pure $ Ex.map (\ig -> Lib.Grid.nDistinctVals (\_ -> True) ig) inputs) , ("nDistinctNonBlanks", pure $ Ex.map (\ig -> Lib.Grid.nDistinctVals nonBlank ig) inputs) ] ----------------- -- Features ----------------- rowIsUniform :: (Unbox a, Eq a) => Grid a -> Int -> Maybe a rowIsUniform g i = do guard $ Int.allSame (nCols g) $ \j -> getG g (Index i j) pure $ getG g (Index i 0) colIsUniform :: (Unbox a, Eq a) => Grid a -> Int -> Maybe a colIsUniform g j = do guard $ Int.allSame (nRows g) $ \i -> getG g (Index i j) pure $ getG g (Index 0 j) isUniform :: (Unbox a, Eq a) => Grid a -> Maybe a isUniform g = do guard $ Int.allSame (nRows g * nCols g) $ \i -> getG g (Dims.int2index (dims g) i) pure $ getG g (Index 0 0) firstVal :: (Unbox a, Eq a) => (a -> Bool) -> Grid a -> Maybe a firstVal p g = Dims.first (dims g) $ \idx -> pure $ do guard $ p (getG g idx) pure $ getG g idx isSquare :: (Unbox a) => Grid a -> Maybe Int isSquare g = do guard $ nRows g == nCols g pure $ nRows g reflectAround :: (Unbox a) => Grid a -> Axis -> Grid a reflectAround g ax = flip Lib.Grid.map g $ \idx _ -> getG g (Axis.reflectAround (dims g) ax idx) isSymmetricAround :: (Unbox a, Eq a) => Axis -> Grid a -> Bool isSymmetricAround ax g = Dims.all (dims g) $ \idx -> getG g idx == getG g (Axis.reflectAround (dims g) ax idx) distinctVals :: (Unbox a, Eq a, Ord a) => (a -> Bool) -> Grid a -> Set a distinctVals p g = Dims.iter (dims g) Set.empty $ \acc idx -> pure $ if p (getG g idx) then Set.insert (getG g idx) acc else acc nDistinctVals :: (Unbox a, Eq a, Ord a) => (a -> Bool) -> Grid a -> Int nDistinctVals p g = Set.size $ distinctVals p g buildCounts :: (Unbox a, Eq a, Ord a) => (a -> Bool) -> Grid a -> Map a Int buildCounts p g = Dims.iter (dims g) Map.empty $ \acc idx -> let x = getG g idx in pure $ if p x then Map.insertWith (+) x 1 acc else acc maxValCount :: (Unbox a, Eq a, Ord a) => (a -> Bool) -> Grid a -> Int maxValCount p g = maximum . (0:) . Map.elems $ buildCounts p g nNonBlankVals :: (Unbox a, HasBlank a) => Grid a -> Int nNonBlankVals g = Dims.iter (dims g) 0 $ \acc idx -> pure $ if nonBlank (getG g idx) then acc + 1 else acc predIdxs :: (Unbox a) => Grid a -> (Index -> a -> Bool) -> Set Index predIdxs g f = Dims.iter (dims g) Set.empty $ \acc idx -> pure $ if f idx (getG g idx) then Set.insert idx acc else acc nonBlankIdxs :: (Unbox a, HasBlank a) => Grid a -> Set Index nonBlankIdxs g = predIdxs g (\_ val -> nonBlank val) valIdxs :: (Unbox a, Eq a) => Grid a -> a -> Set Index valIdxs g val = Dims.iter (dims g) Set.empty $ \acc idx -> pure $ if (getG g idx) == val then Set.insert idx acc else acc majorityVals :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> ([a], Int) majorityVals g = let counts = Map.toList $ buildCounts (\_ -> True) g in let biggestCount = snd $ List.maximumBy (\(c1, k1) (c2, k2) -> compare k1 k2) counts in (Prelude.map fst $ List.filter (\(_, count) -> count == biggestCount) counts, biggestCount) minorityVals :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> ([a], Int) minorityVals g = let counts = Map.toList $ buildCounts (\_ -> True) g in let smallestCount = snd $ List.minimumBy (\(c1, k1) (c2, k2) -> compare k1 k2) counts in (Prelude.map fst $ List.filter (\(_, count) -> count == smallestCount) counts, smallestCount) majorityNonBlankVals :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> ([a], Int) majorityNonBlankVals g = let counts = Map.toList $ buildCounts nonBlank g in if null counts then ([blank], 0) else let biggestCount = snd $ List.maximumBy (\(c1, k1) (c2, k2) -> compare k1 k2) counts in (Prelude.map fst $ List.filter (\(_, count) -> count == biggestCount) counts, biggestCount) majorityNonBlankVal :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> Maybe a majorityNonBlankVal g = case majorityNonBlankVals g of ([x], _) -> pure x _ -> Nothing minorityNonBlankVals :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> ([a], Int) minorityNonBlankVals g = let counts = Map.toList $ buildCounts nonBlank g in if null counts then ([blank], 0) else let smallestCount = snd $ List.minimumBy (\(c1, k1) (c2, k2) -> compare k1 k2) counts in (Prelude.map fst $ List.filter (\(_, count) -> count == smallestCount) counts, smallestCount) minorityNonBlankVal :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> Maybe a minorityNonBlankVal g = case minorityNonBlankVals g of ([x], _) -> pure x _ -> Nothing TODO : result in SearchT ? mapBinOp :: (Unbox a) => (a -> a -> a) -> Grid a -> Grid a -> Grid a mapBinOp f g1 g2 = if dims g1 == dims g2 then fromFunc (dims g1) $ \idx -> f (getG g1 idx) (getG g2 idx) else error "mapBinOp called with bad dims" map3Op1 :: (Unbox a) => (a -> a -> a -> a) -> Grid a -> Grid a -> Grid a map3Op1 f g1 g2 = if dims g1 == dims g2 then fromFunc (dims g1) $ \idx -> f (getG g1 idx) (getG g1 idx) (getG g2 idx) else error "map3Op1 called with bad dims" -- TODO: parameterize by ordering --reduceBinOp :: (a -> a -> a) -> Grid a -> a --reduceBinOp f g = let ( Index 0 0 ) in Dims.iter ( ) x0 $ \acc idx - > pure $ if idx = = Index 0 0 then acc else f acc ( ) reduceBinOp :: (Unbox a) => (a -> a -> a) -> Grid a -> [Index] -> a reduceBinOp f g ordering = List.reduce (\acc val -> f acc val) (\idx -> getG g idx) ordering -- TODO: move to features as it is specialized to color? -- TODO: is Data.Foldable.toList too slow? Is using Set wrong here? FIXME : do we want to use Axis.orthoDist ? the nearest val that ISNT YOUR nearestNonSelfVal :: Grid Color -> Grid Color nearestNonSelfVal g = let nonSelfNonBlanks :: Map Color (Set Index) = List.iter distinctGridVals Map.empty $ \acc val -> pure $ Map.insert val (flip Set.filter gridNonBlanks (\idx -> (getG g idx) /= val)) acc in fromFunc (dims g) $ \idx -> let nonValNonBlanks :: Set Index = Maybe.fromJust $ Map.lookup (getG g idx) nonSelfNonBlanks in if null nonValNonBlanks then blank else let closestIdxs :: [Index] = List.argminsKey (\idx2 -> Axis.dist OrthoDist idx idx2) (Set.toList nonValNonBlanks) in if length closestIdxs == 1 || List.allSame (flip Prelude.map closestIdxs (\idx -> getG g idx)) then getG g (closestIdxs !! 0) else blank where gridNonBlanks = Lib.Grid.nonBlankIdxs g -- we don't consider blanks distinctGridVals = Set.toList $ distinctVals (\_ -> True) g -- in this feature, you are allowed to be yourself! (so, all non-blanks will be themselves) nearestNonBlank :: Grid Color -> Grid Color nearestNonBlank g = -- if all blank then blank if Lib.Grid.allBlank g then g if only have one distinct nonblank , then const grid of that nonblank else if (Lib.Grid.nDistinctVals nonBlank g) == 1 then Lib.Grid.const (dims g) (Set.elemAt 0 (distinctVals nonBlank g)) else fromFunc (dims g) $ \idx -> if null gridNonBlanks then blank else let closestIdxs = List.argminsKey (\idx2 -> Axis.dist OrthoDist idx idx2) gridNonBlanks in if length closestIdxs == 1 || List.allSame (flip Prelude.map closestIdxs (\idx -> getG g idx)) then getG g (closestIdxs !! 0) else blank where gridNonBlanks = Set.toList (Lib.Grid.nonBlankIdxs g) -- we don't consider blanks -- the nearest non-blank that isn't at your index! nearestNonSelfIdx :: Grid Color -> Grid Color nearestNonSelfIdx g = -- if all blank then blank if Lib.Grid.allBlank g then g else let gridNonBlanks = Set.toList (Lib.Grid.nonBlankIdxs g) in -- we don't consider blanks fromFunc (dims g) $ \idx -> if null gridNonBlanks then blank else case Prelude.filter (\idx2 -> idx /= idx2) gridNonBlanks of [] -> blank xs -> let closestIdxs = List.argminsKey (\idx2 -> Axis.dist OrthoDist idx idx2) xs in if length closestIdxs == 1 || List.allSame (flip Prelude.map closestIdxs (\idx -> getG g idx)) then getG g (closestIdxs !! 0) else blank extremeNonBlankDistances :: (Monad m) => Ex (Grid Color) -> SearchT m (Ex (Grid Int)) extremeNonBlankDistances inputs = do ensure that each input grid has at least one non - blank ( not always true ! ) guard $ flip Ex.all inputs $ \ig -> not (Lib.Grid.allBlank ig) guard that there are n't too many non - blanks ( currently 1/3 , which is fairly strict ) guard $ flip Ex.all inputs $ \ig -> (Lib.Grid.nNonBlanks ig) < ((Dims.nCells (dims ig)) `div` 3) distFunc <- oneOf "extremeNonBlankDistances.distFunc" [("ortho", Axis.dist OrthoDist), ("diag", Axis.dist DiagDist)] extreme <- oneOf "extremeNonBlankDistances.extreme" [("max", 1), ("min", -1)] pure $ flip Ex.map inputs $ \ig -> Lib.Grid.extremeDistToNonBlank (\idx1 idx2 -> extreme * (distFunc idx1 idx2)) ig extremeBlankDistances :: (Monad m) => Ex (Grid Color) -> SearchT m (Ex (Grid Int)) extremeBlankDistances inputs = do ensure that each input grid has at least one non - blank ( not always true ! ) guard $ flip Ex.all inputs $ \ig -> containsVal blank ig TODO : currently not guarding that there is some amoutn of to limit perf distFunc <- oneOf "extremeBlankDistances.distFunc" [("ortho", Axis.dist OrthoDist), ("diag", Axis.dist DiagDist)] currently just using min , not extreme <- oneOf "extremeBlankDistances.extreme" [("min", -1)] pure $ flip Ex.map inputs $ \ig -> Lib.Grid.extremeDistToBlank (\idx1 idx2 -> extreme * (distFunc idx1 idx2)) ig -- this is only Maybe Int instead of Int because we want to allow a grid not having the color at all extremeDistancesToVal :: (Monad m) => Ex (Grid Color) -> Ex Color -> SearchT m (Ex (Grid (Maybe Int))) extremeDistancesToVal inputs cs = do -- note we check the majority rather than all -- check that the majority ofe inputs have this color guard $ flip List.majority (Ex.toBigList (Ex.zip inputs cs)) $ \(ig, c) -> containsVal c ig distFunc <- oneOf "extremeDistancesToVal.distFunc" [("ortho", Axis.dist OrthoDist), ("diag", Axis.dist DiagDist)] extreme <- oneOf "extremeDistancesToVal.extreme" [("max", 1), ("min", -1)] pure $ flip Ex.map (Ex.zip inputs cs) $ \(ig, c) -> -- only have to do this because of majority rather than all check if not (containsVal c ig) then Lib.Grid.const (dims ig) Nothing else -- inefficient Lib.Grid.map (\idx val -> Just val) $ Lib.Grid.extremeDistToVal (\idx1 idx2 -> extreme * (distFunc idx1 idx2)) ig c -- note use of getD nNeighborsAxDirs :: (Unbox a, HasBlank a) => Grid a -> [(Axis, Direction)] -> Index -> Int nNeighborsAxDirs g axDirs idx = flip List.count axDirs $ \(ax, dir) -> let idxInAxDir = Direction.step idx 1 ax dir in nonBlank (getD g idxInAxDir) -- note use of getD -- distinct non-blank colors among immediate neighbors nNeighborColorsAxDirs :: (Unbox a, Ord a, HasBlank a) => Grid a -> [(Axis, Direction)] -> Index -> Int nNeighborColorsAxDirs g axDirs idx = List.countDistinct id (List.filter (\x -> nonBlank x) neighborColors) where neighborColors = flip List.map axDirs $ \(ax, dir) -> getD g (Direction.step idx 1 ax dir) -- how to make this quadratic? isSurrounded :: (Unbox a, HasBlank a) => Grid a -> Grid Bool isSurrounded g = flip Lib.Grid.map g $ \idx _ -> (nNeighborsAxDirs g axDirs idx) == 8 where axDirs = [(ax, dir) | ax <- [Horizontal, Vertical, DownRight, DownLeft], dir <- [Normal, Reverse]] ---------------------- -- enumMaybeIndices ---------------------- -- TODO: handle "group" variants of this, where the predicate itself is determined per-example. -- TODO: some typeclass for this Note : motivated by 6d0160f0 findIndices :: (Unbox a) => (a -> Bool) -> Grid a -> [Index] findIndices p g = Dims.iter (dims g) [] $ \acc idx -> pure $ if p (getG g idx) then idx:acc else acc enumMaybeIndices :: (Monad m, HasSynth1Context m Color) => SearchT m (Ex (Grid Color -> [Index])) enumMaybeIndices = choice "Grid.enumMaybeIndices" [ ("ofColor", Ex.map (\c -> \g -> findIndices (==c) g) <$> enumColorsCtx) ] enumColorSets :: (Monad m) => SearchT m (Grid Color -> Set Color) enumColorSets = choice "Grid.enumColorSets" [ ("distinctNonBlankVals", pure $ \g -> distinctVals nonBlank g) ] enumGridPreserving :: (Unbox a, Monad m) => SearchT m (Grid a -> Grid a) enumGridPreserving = oneOf "Grid.enumPreservingTrans" [ ("id", id), ("reflectHorizontal", flip Lib.Grid.reflectAround Horizontal), ("reflectVertical", flip Lib.Grid.reflectAround Vertical) ] ---------------------- -- Line ---------------------- -- TODO: upto mask? -- TODO: get all lines, greedily, upto mask? -- TODO: blanks? guarantee that adjacent lines have the same color? horizontalLines :: (Unbox a, HasBlank a, Eq a) => Grid a -> [Int] horizontalLines g = flip List.filter (range $ nRows g) $ \i -> let x = getG g (Index i 0) in (x /= blank) && (Int.all (nCols g) $ \j -> getG g (Index i j) == x) verticalLines :: (Unbox a, HasBlank a, Eq a) => Grid a -> [Int] verticalLines g = flip List.filter (range $ nCols g) $ \j -> let x = getG g (Index 0 j) in (x /= blank) && (Int.all (nRows g) $ \i -> getG g (Index i j) == x) getDominantElem :: (Unbox a, Eq a, Ord a, Show a) => [a] -> Float -> Maybe a getDominantElem r frac = do guard . not . null $ r let domElems = maximumBy (comparing length) . List.group $ (List.sort r) guard . not . null $ domElems let domElemFrac = (fromIntegral $ length domElems)/(fromIntegral $ length r) guard (frac <= domElemFrac) pure . head $ domElems existsDominantElem :: (Unbox a, Eq a, Ord a, Show a) => [a] -> Float -> Bool existsDominantElem r frac = isJust $ getDominantElem r frac fuzzyHorizontalLines :: (Unbox a, HasBlank a, Eq a, Show a, Ord a) => Grid a -> Float -> [Int] fuzzyHorizontalLines g frac = flip List.filter (range $ nRows g) $ \i -> existsDominantElem (getRow g i) frac fuzzyVerticalLines :: (Unbox a, HasBlank a, Eq a, Show a, Ord a) => Grid a -> Float -> [Int] fuzzyVerticalLines g frac = flip List.filter (range $ nCols g) $ \j -> existsDominantElem (getCol g j) frac horizontalLinesColor :: (Unbox a, HasBlank a, Eq a) => a -> Grid a -> [Int] horizontalLinesColor x0 g = flip List.filter (range $ nRows g) $ \i -> let x = getG g (Index i 0) in (x == x0) && (Int.all (nCols g) $ \j -> getG g (Index i j) == x) verticalLinesColor :: (Unbox a, HasBlank a, Eq a) => a -> Grid a -> [Int] verticalLinesColor x0 g = flip List.filter (range $ nCols g) $ \j -> let x = getG g (Index 0 j) in (x == x0) && (Int.all (nRows g) $ \i -> getG g (Index i j) == x) lineBoolVals :: (Unbox a) => Grid a -> ([a] -> Bool) -> Axis -> Map Int Bool lineBoolVals g f ax = List.iter (range (Line.numAxLines (dims g) ax)) Map.empty $ \acc ident -> let lineVals = Prelude.map (\idx -> getG g idx) $ Line.idxsOfId (dims g) ax ident in pure $ Map.insert ident (f lineVals) acc -- FIXME: generalize with lineBoolVals lineIntVals :: (Unbox a) => Grid a -> ([a] -> Int) -> Axis -> Map Int Int lineIntVals g f ax = List.iter (range (Line.numAxLines (dims g) ax)) Map.empty $ \acc ident -> let lineVals = Prelude.map (\idx -> getG g idx) $ Line.idxsOfId (dims g) ax ident in pure $ Map.insert ident (f lineVals) acc -- FIXME: generalize with lineBoolVals lineColorVals :: (Unbox a) => Grid a -> ([a] -> Color) -> Axis -> Map Int Color lineColorVals g f ax = List.iter (range (Line.numAxLines (dims g) ax)) Map.empty $ \acc ident -> let lineVals = Prelude.map (\idx -> getG g idx) $ Line.idxsOfId (dims g) ax ident in pure $ Map.insert ident (f lineVals) acc lineIdxsP :: (Unbox a, HasBlank a) => Grid a -> (Index -> a -> Bool) -> Axis -> Direction -> Int -> [Index] lineIdxsP g f ax dir ident = let predIdxs = flip List.filter (Line.idxsOfId (dims g) ax ident) $ \idx -> f idx (getG g idx) in if dir == Reverse then reverse predIdxs else predIdxs nonBlankLineIdxs :: (Unbox a, HasBlank a) => Grid a -> Axis -> Direction -> Int -> [Index] nonBlankLineIdxs g ax dir ident = lineIdxsP g (\idx val -> nonBlank val) ax dir ident blankLineIdxs :: (Unbox a, HasBlank a) => Grid a -> Axis -> Direction -> Int -> [Index] blankLineIdxs g ax dir ident = lineIdxsP g (\idx val -> isBlank val) ax dir ident valLineIdxs :: (Unbox a, HasBlank a, Eq a) => Grid a -> a -> Axis -> Direction -> Int -> [Index] valLineIdxs g x ax dir ident = lineIdxsP g (\idx val -> val == x) ax dir ident axisBlank :: (Unbox a, HasBlank a) => Grid a -> Axis -> Grid Bool axisBlank g ax = let vals :: Map Int Bool = lineBoolVals g (\lineVals -> flip Prelude.all lineVals $ \val -> isBlank val) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals axHasVal :: (Unbox a, HasBlank a) => Grid a -> a -> Axis -> Grid Bool axHasVal g x ax = let vals :: Map Int Bool = lineBoolVals g (\lineVals -> flip Prelude.any lineVals $ \val -> val == x) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals nInAxis :: (Unbox a, HasBlank a, Ord a, Eq a) => Grid a -> Axis -> Grid Int nInAxis g ax = let vals :: Map Int Int = lineIntVals g (\lineVals -> List.count nonBlank lineVals) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals nBlankInAxis :: (Unbox a, HasBlank a, Ord a, Eq a) => Grid a -> Axis -> Grid Int nBlankInAxis g ax = let vals :: Map Int Int = lineIntVals g (\lineVals -> List.count isBlank lineVals) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals idxInAxis :: Grid a -> Index -> Axis -> Grid Bool idxInAxis g idx ax = let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax identOfIdx :: Int = idxMapper idx in fromFunc (dims g) $ \idx2 -> if (idxMapper idx2) == identOfIdx then True else False idxInAxDir :: (Unbox a) => Grid a -> Index -> Axis -> Direction -> Grid Bool idxInAxDir g idx ax dir = let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax identOfIdx :: Int = idxMapper idx in fromFunc (dims g) $ \idx2 -> if (idxMapper idx2) == identOfIdx && Direction.precedes ax dir idx2 idx then True else False anyIdxInAxDir :: (Unbox a) => Grid a -> [Index] -> Axis -> Direction -> Grid Bool anyIdxInAxDir g idxs ax dir = List.reduce (\g1 g2 -> mapBinOp (Blank.orD True) g1 g2) (\idx -> idxInAxDir g idx ax dir) idxs axMax :: Grid Color -> Axis -> Grid Color axMax g ax = let vals :: Map Int Color = lineColorVals g (\lineVals -> flip List.argmaxKey (List.nub lineVals) $ \val -> if val == blank then 0 else (List.count (\val2 -> val2 == val) lineVals)) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals nDistinctInAxis :: (Unbox a, Ord a, Eq a) => Grid a -> Axis -> Grid Int nDistinctInAxis g ax = let vals :: Map Int Int = lineIntVals g (\lineVals -> List.countDistinct id lineVals) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals nearestValInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid a nearestValInAxDir g ax dir = let axesNonBlanks :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> nonBlankLineIdxs g ax dir ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in FIXME -- want to avoident ! ! constant time lookup . Use hashmap for vals ? fromFunc (dims g) $ \idx -> case flip List.first (axesNonBlanks !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing of Nothing -> blank Just idx2 -> getG g idx2 furthestValInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid a furthestValInAxDir g ax dir = let axesNonBlanks :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> nonBlankLineIdxs g ax (Direction.reverse dir) ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in FIXME -- want to avoident ! ! constant time lookup . Use hashmap for vals ? fromFunc (dims g) $ \idx -> case flip List.first (axesNonBlanks !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing of Nothing -> blank Just idx2 -> getG g idx2 idxOfNearestInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid (Maybe Index) idxOfNearestInAxDir g ax dir = let axesNonBlanks :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> nonBlankLineIdxs g ax dir ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in FIXME -- want to avoident ! ! constant time lookup . Use hashmap for vals ? fromFunc (dims g) $ \idx -> flip List.first (axesNonBlanks !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing note the use of diagDist rather than orthoDist because we know we will be in the same axDir distToNearestNonBlankInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid (Maybe Int) distToNearestNonBlankInAxDir g ax dir = let axesNonBlanks :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> nonBlankLineIdxs g ax dir ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in FIXME -- want to avoident ! ! constant time lookup . Use hashmap for vals ? fromFunc (dims g) $ \idx -> case flip List.first (axesNonBlanks !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing of Nothing -> Nothing Just idx2 -> Just $ Axis.dist DiagDist idx idx2 -- duplicate code with distToNearestNonBlankInAxDir note the use of diagDist rather than orthoDist because we know we will be in the same axDir distToNearestBlankInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid (Maybe Int) distToNearestBlankInAxDir g ax dir = let axesBlanks :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> blankLineIdxs g ax dir ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in FIXME -- want to avoident ! ! constant time lookup . Use hashmap for vals ? fromFunc (dims g) $ \idx -> case flip List.first (axesBlanks !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing of Nothing -> Nothing Just idx2 -> Just $ Axis.dist DiagDist idx idx2 distToNearestValInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> a -> Axis -> Direction -> Grid (Maybe Int) distToNearestValInAxDir g x ax dir = if not (containsVal x g) then Lib.Grid.const (dims g) Nothing else let axesVals :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> valLineIdxs g x ax dir ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> case flip List.first (axesVals !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing of Nothing -> Nothing Just idx2 -> Just $ Axis.dist DiagDist idx idx2 -- TODO: how to make this faster? extremeDistToPred :: (Unbox a, HasBlank a) => (Index -> Index -> Int) -> (Index -> a -> Bool) -> Grid a -> Grid Int extremeDistToPred distFunc predF g = flip Lib.Grid.map g $ \idx _ -> abs (List.maximum (List.map (distFunc idx) gridPredIdxs)) where gridPredIdxs = Set.toList $ predIdxs g predF -- TODO: how to make this faster? FIXME : Could currently include 0s . Do we want this ? If not , we have to guard that there are at least 2 non blanks in the grid extremeDistToNonBlank :: (Unbox a, HasBlank a) => (Index -> Index -> Int) -> Grid a -> Grid Int extremeDistToNonBlank distFunc g = extremeDistToPred distFunc (\_ val -> nonBlank val) g extremeDistToBlank :: (Unbox a, HasBlank a) => (Index -> Index -> Int) -> Grid a -> Grid Int extremeDistToBlank distFunc g = extremeDistToPred distFunc (\_ val -> isBlank val) g extremeDistToVal :: (Unbox a, Eq a, HasBlank a) => (Index -> Index -> Int) -> Grid a -> a -> Grid Int extremeDistToVal distFunc g x = extremeDistToPred distFunc (\_ val -> val == x) g distToNonBlankLineInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid (Maybe Int) distToNonBlankLineInAxDir g ax dir = runIdentity $ do let linesWithNonBlank :: [Int] = flip List.filter (range (Line.numAxLines (dims g) ax)) $ \lineId -> flip Prelude.any (Line.idxsOfId (dims g) ax lineId) $ \idx -> nonBlank (getG g idx) let orderedNonBlankLines :: [Int] = if dir == Reverse then reverse linesWithNonBlank else linesWithNonBlank let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax let decider :: Int -> Int -> Bool = case dir of Normal -> \i1 i2 -> i1 > i2 Reverse -> \i1 i2 -> i1 < i2 let distPerLine :: [Maybe Int] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \lineId -> case flip List.first orderedNonBlankLines (\ident -> if decider ident lineId then Just ident else Nothing) of Nothing -> Nothing Just ident1 -> Just (abs (lineId - ident1)) pure $ fromFunc (dims g) $ \idx -> (distPerLine !! (idxMapper idx)) nonBlankLineExistsInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid Bool nonBlankLineExistsInAxDir g ax dir = runIdentity $ do let linesWithNonBlank :: [Int] = flip List.filter (range (Line.numAxLines (dims g) ax)) $ \lineId -> flip Prelude.any (Line.idxsOfId (dims g) ax lineId) $ \idx -> nonBlank (getG g idx) -- ordering is just an optimization in this case let orderedNonBlankLines :: [Int] = if dir == Reverse then reverse linesWithNonBlank else linesWithNonBlank let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax let decider :: Int -> Int -> Bool = case dir of Normal -> \i1 i2 -> i1 > i2 Reverse -> \i1 i2 -> i1 < i2 let decisionPerLine :: [Bool] = flip Prelude.map (range (Line.numAxLines (dims g) ax )) $ \lineId -> flip Prelude.any orderedNonBlankLines $ \ident -> decider ident lineId pure $ fromFunc (dims g) $ \idx -> (decisionPerLine !! (idxMapper idx)) lineWithValExistsInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> a -> Axis -> Direction -> Grid Bool lineWithValExistsInAxDir g x ax dir = runIdentity $ do let linesWithVal :: [Int] = flip List.filter (range (Line.numAxLines (dims g) ax)) $ \lineId -> flip Prelude.any (Line.idxsOfId (dims g) ax lineId) $ \idx -> (getG g idx) == x -- ordering is just an optimization in this case let orderedLinesWithVal :: [Int] = if dir == Reverse then reverse linesWithVal else linesWithVal let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax let decider :: Int -> Int -> Bool = case dir of Normal -> \i1 i2 -> i1 > i2 Reverse -> \i1 i2 -> i1 < i2 let decisionPerLine :: [Bool] = flip Prelude.map (range (Line.numAxLines (dims g) ax )) $ \lineId -> flip Prelude.any orderedLinesWithVal $ \ident -> decider ident lineId pure $ fromFunc (dims g) $ \idx -> (decisionPerLine !! (idxMapper idx)) nonBlankExistsToAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid Bool nonBlankExistsToAxDir g ax dir = do let axesMaxNonBlanks :: [Index] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> do let lineNonBlankIdxs = flip List.filter (Line.idxsOfId (dims g) ax ident) $ \idx -> nonBlank (getG g idx) -- (-1, -1) indicates the non-existence of blanks if null lineNonBlankIdxs then (Index (-1) (-1)) else Direction.furthestInAxDir lineNonBlankIdxs ax dir let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax FIXME -- want to avoident ! ! constant time lookup . Use hashmap for vals ? fromFunc (dims g) $ \idx -> do let maxInLine :: Index = axesMaxNonBlanks !! (idxMapper idx) if maxInLine == Index (-1) (-1) then False else Direction.precedes ax dir idx maxInLine valExistsToAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> a -> Axis -> Direction -> Grid Bool valExistsToAxDir g x ax dir = do let axesMaxVals :: [Index] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> do let lineValIdxs = flip List.filter (Line.idxsOfId (dims g) ax ident) $ \idx -> (getG g idx) == x ( -1 , -1 ) indicates the non - existence of a val in axdir if null lineValIdxs then (Index (-1) (-1)) else Direction.furthestInAxDir lineValIdxs ax dir let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax FIXME -- want to avoident ! ! constant time lookup . Use hashmap for vals ? fromFunc (dims g) $ \idx -> do let maxInLine :: Index = axesMaxVals !! (idxMapper idx) if maxInLine == Index (-1) (-1) then False else Direction.precedes ax dir idx maxInLine ---------------------- -- Rects ---------------------- cropDeltas :: Grid a -> Axis -> [Int] cropDeltas grid ax = case ax of Horizontal -> List.range $ nCols grid Vertical -> List.range $ nRows grid _ -> List.range $ min (nRows grid) (nCols grid) cropAlongAxDirOpt :: Grid a -> Axis -> Direction -> Int -> Maybe Rect cropAlongAxDirOpt grid ax dir delta = case (ax, dir) of (Horizontal, Normal) -> do guard $ delta < nCols grid pure $ Rect (Index 0 delta) (Dims (nRows grid) ((nCols grid) - delta)) (Horizontal, Reverse) -> do guard $ delta < nCols grid pure $ Rect (Index 0 0) (Dims (nRows grid) ((nCols grid) - delta)) (Vertical, Normal) -> do guard $ delta < nRows grid pure $ Rect (Index delta 0) (Dims ((nRows grid) - delta) (nCols grid)) (Vertical, Reverse) -> do guard $ delta < nRows grid pure $ Rect (Index 0 0) (Dims ((nRows grid) - delta) (nCols grid)) (DownRight, Normal) -> do guard $ delta < min (nRows grid) (nCols grid) pure $ Rect (Index delta delta) (Dims ((nRows grid) - delta) ((nCols grid) - delta)) (DownRight, Reverse) -> do guard $ delta < min (nRows grid) (nCols grid) pure $ Rect (Index 0 0) (Dims ((nRows grid) - delta) ((nCols grid) - delta)) (DownLeft, Normal) -> do guard $ delta < min (nRows grid) (nCols grid) pure $ Rect (Index delta 0) (Dims ((nRows grid) - delta) ((nCols grid) - delta)) (DownLeft, Reverse) -> do guard $ delta < min (nRows grid) (nCols grid) pure $ Rect (Index 0 delta) (Dims ((nRows grid) - delta) ((nCols grid) - delta)) rectInBounds :: (Unbox a) => Grid a -> Rect -> Bool rectInBounds g (Rect ul (Dims nR nC)) = Dims.inBounds (dims g) (ul + (Index (nR - 1) (nC - 1))) && Dims.inBounds (dims g) ul nonBlankRect :: (Unbox a, HasBlank a) => Grid a -> Maybe Rect nonBlankRect g = do let (minRow, maxRow, minCol, maxCol) = Dims.iter (dims g) (nRows g, 0, nCols g, 0) $ \vals@(minRow, maxRow, minCol, maxCol) idx@(Index i j) -> pure $ if nonBlank (getG g idx) then (min minRow i, max maxRow i, min minCol j, max maxCol j) else vals guard $ minRow < nRows g && minCol < nCols g pure $ Rect { Rect.upperLeft = Index minRow minCol, Rect.dims = Dims (maxRow + 1 - minRow) (maxCol + 1 - minCol) } getRect :: (Unbox a) => Grid a -> Rect -> Grid a getRect g (Rect ul dims) = getSubgridUnsafe g dims ul embedRectIn :: (Unbox a, HasBlank a) => Grid a -> Rect -> Grid a -> Maybe (Grid a) embedRectIn bg rect@(Rect (Index ri rj) rDims@(Dims dx dy)) g = do let outerDims = dims bg guard $ rDims == dims g guard $ ri + dx <= Dims.nRows outerDims guard $ rj + dy <= Dims.nCols outerDims pure $ fromFunc outerDims $ \idx@(Index i j) -> if (i >= ri && i < ri + dx && j >= rj && j < rj + dy) then getG g (idx - Index ri rj) else getG bg idx embedRectInBlank :: (Unbox a, HasBlank a) => Dims -> Rect -> Grid a -> Maybe (Grid a) embedRectInBlank outerDims = embedRectIn (Lib.Grid.const outerDims blank) ---------------------- -- Shapes ---------------------- nonBlankShape :: (Unbox a, HasBlank a) => Grid a -> Maybe (Shape a) nonBlankShape g = case nonBlankRect g of Just r -> Just $ Shape.fromList (flip Prelude.map (Rect.getIdxs r) (\idx -> (idx, getG g idx))) Nothing -> Nothing -- TODO: slow, but not perf critical and annoying to get destructive updates fromShapes :: (Unbox a, HasBlank a) => Dims -> [Shape a] -> Grid a fromShapes dims shapes = fromFunc dims $ \idx -> case flip List.first shapes $ \s -> Shape.lookupIndex s idx of Nothing -> blank Just x -> x replacingShapes :: (Unbox a, HasBlank a) => Grid a -> [Shape a] -> [Shape a] -> Grid a replacingShapes g oldShapes newShapes = flip Lib.Grid.map g $ \idx x0 -> case flip List.first newShapes $ \s -> Shape.lookupIndex s idx of Just x -> x Nothing -> case flip List.first oldShapes $ \s -> Shape.lookupIndex s idx of Just _ -> blank Nothing -> x0 lookupShape :: (Unbox a, HasBlank a) => Grid a -> Shape b -> Shape a lookupShape g s = Shape.fromList $ Prelude.map (\idx -> (idx, getG g idx)) $ Shape.indices s shapeOrthoNeighbors :: (Unbox a, Eq a, Ord a) => Grid a -> Shape a -> [Index] shapeOrthoNeighbors g s = let allNeighbors = List.nub $ List.iter (Shape.indices s) [] $ \acc sIdx -> pure $ acc ++ (neighborsOrtho g sIdx) in List.filter (\neighbIdx -> not (Shape.containsIndex s neighbIdx)) allNeighbors shapeDiagNeighbors :: (Unbox a, Eq a, Ord a) => Grid a -> Shape a -> [Index] shapeDiagNeighbors g s = let allNeighbors = List.nub $ List.iter (Shape.indices s) [] $ \acc sIdx -> pure $ acc ++ (neighborsDiag g sIdx) in List.filter (\neighbIdx -> not (Shape.containsIndex s neighbIdx)) allNeighbors shapeAllNeighbors :: (Unbox a, Eq a, Ord a) => Grid a -> Shape a -> [Index] shapeAllNeighbors g s = let allNeighbors = List.nub $ List.iter (Shape.indices s) [] $ \acc sIdx -> pure $ acc ++ (neighbors g sIdx) in List.filter (\neighbIdx -> not (Shape.containsIndex s neighbIdx)) allNeighbors shapesNeighbors :: (Unbox a, Eq a, Ord a) => Grid a -> [Shape a] -> (Grid a -> Shape a -> [Index]) -> [Index] shapesNeighbors g shapes neighborFn = List.nub $ List.iter shapes [] $ \acc s -> pure $ acc ++ (neighborFn g s)
null
https://raw.githubusercontent.com/dselsam/arc/7e68a7ed9508bf26926b0f68336db05505f4e765/src/Lib/Grid.hs
haskell
# LANGUAGE StrictData # TODO: duplication g1 takes precedence! Just for this file, since we can't qualify `Grid` here unsafe unsafe redundant sameDims check, but helpful short circuit TODO: throw error or keep Maybe? --------------- --------------- --------------- Combinator Instances --------------- TODO : does this get used ? Why not have a typeclass just for mapM and friends ? Can we get away with this ? ? TODO: does this get used? Why not have a typeclass just for mapM and friends? Can we get away with this?? mapM :: (Monad m) => (a -> m b) -> Grid a -> m (Grid b) mapM f = Lib.Grid.mapM (\_ -> f) --------------- Partitioning --------------- TODO: this and others that are unsafe may cause problems! Worth always returning maybes? --------------- --------------- --------------- Features --------------- TODO: parameterize by ordering reduceBinOp :: (a -> a -> a) -> Grid a -> a reduceBinOp f g = TODO: move to features as it is specialized to color? TODO: is Data.Foldable.toList too slow? Is using Set wrong here? we don't consider blanks in this feature, you are allowed to be yourself! (so, all non-blanks will be themselves) if all blank then blank we don't consider blanks the nearest non-blank that isn't at your index! if all blank then blank we don't consider blanks this is only Maybe Int instead of Int because we want to allow a grid not having the color at all note we check the majority rather than all check that the majority ofe inputs have this color only have to do this because of majority rather than all check inefficient note use of getD note use of getD distinct non-blank colors among immediate neighbors how to make this quadratic? -------------------- enumMaybeIndices -------------------- TODO: handle "group" variants of this, where the predicate itself is determined per-example. TODO: some typeclass for this -------------------- Line -------------------- TODO: upto mask? TODO: get all lines, greedily, upto mask? TODO: blanks? guarantee that adjacent lines have the same color? FIXME: generalize with lineBoolVals FIXME: generalize with lineBoolVals want to avoident ! ! constant time lookup . Use hashmap for vals ? want to avoident ! ! constant time lookup . Use hashmap for vals ? want to avoident ! ! constant time lookup . Use hashmap for vals ? want to avoident ! ! constant time lookup . Use hashmap for vals ? duplicate code with distToNearestNonBlankInAxDir want to avoident ! ! constant time lookup . Use hashmap for vals ? TODO: how to make this faster? TODO: how to make this faster? ordering is just an optimization in this case ordering is just an optimization in this case (-1, -1) indicates the non-existence of blanks want to avoident ! ! constant time lookup . Use hashmap for vals ? want to avoident ! ! constant time lookup . Use hashmap for vals ? -------------------- Rects -------------------- -------------------- Shapes -------------------- TODO: slow, but not perf critical and annoying to get destructive updates
Copyright ( c ) 2020 Microsoft Corporation . All rights reserved . Released under Apache 2.0 license as described in the file LICENSE . Authors : , , . # LANGUAGE MultiParamTypeClasses # # LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # # LANGUAGE InstanceSigs # # LANGUAGE TypeFamilies # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE DeriveGeneric # module Lib.Grid where import GHC.Generics (Generic, Generic1) import Control.DeepSeq import qualified Data.Maybe as Maybe import Data.Foldable import qualified Data.List as List import Data.Map (Map) import Data.Hashable import Data.Vector.Instances import qualified Data.Map as Map import Data.Maybe (listToMaybe, isJust) import Data.Monoid import Data.Monoid (mempty) import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Vector as BVector import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as Vector import Data.Vector.Unboxed.Base (Unbox) import Data.Vector.Unboxed.Deriving import Debug.Trace import Lib.Axis import qualified Lib.Axis as Axis import Lib.Direction (Direction(..)) import qualified Lib.Direction as Direction import Lib.Blank (HasBlank(..), blank, isBlank, nonBlank) import qualified Lib.Blank as Blank import Lib.Color (Color, enumColorsCtx) import qualified Lib.Dims as Dims import Lib.Dims (Dims (Dims)) import Synth1.Synth1Context import qualified Lib.Index as Index import Lib.Index (Index (Index)) import qualified Lib.Line as Line import Util.Imports import qualified Util.Int as Int import Util.List (uncurry3, range) import qualified Util.Int as Int import qualified Util.List as List import Lib.Shape (Shape) import qualified Lib.Shape as Shape import Lib.Rect (Rect(Rect)) import qualified Lib.Rect as Rect import qualified Lib.BGrid as Box import Search.SearchT import Synth1.Basic import Synth.Ex (Ex(..)) import qualified Synth.Ex as Ex data Grid a = Grid { dims :: Dims, gridData :: !(Vector a) } deriving (Eq, Ord, Generic, Generic1) instance NFData a => NFData (Grid a) instance (Unbox a, Hashable a) => Hashable (Grid a) where hashWithSalt salt g = hashWithSalt salt (dims g, gridData g) nRows g = Dims.nRows . dims $ g nCols g = Dims.nCols . dims $ g nCells g = nRows g * nCols g fromArray :: (Unbox a) => Dims -> Vector a -> Grid a fromArray dims v | Dims.nCells dims == Vector.length v = Grid dims v fromList :: (Unbox a) => Dims -> [a] -> Grid a fromList dims elems = fromArray dims (Vector.fromList elems) fromLists :: (Unbox a) => [[a]] -> Grid a fromLists [] = Grid (Dims 0 0) (Vector.fromList []) fromLists elems = let m = length elems n = length (head elems) in fromArray (Dims m n) (Vector.fromList $ concat elems) fromBox :: (Unbox a) => Box.Grid a -> Grid a fromBox box = Grid (Box.dims box) (Vector.fromList $ Box.toList box) fromIntLists :: [[Int]] -> Grid Int fromIntLists elems = fromLists elems fromFuncM :: (Unbox a, Monad m) => Dims -> (Index -> m a) -> m (Grid a) fromFuncM dims@(Dims m n) f = do elems <- Vector.generateM (m*n) $ \i -> f (Dims.int2index dims i) pure $ fromArray dims elems fromFunc :: (Unbox a) => Dims -> (Index -> a) -> Grid a fromFunc dims@(Dims m n) f = fromArray dims $ Vector.generate (m*n) $ \i -> f (Dims.int2index dims i) const :: (Unbox a) => Dims -> a -> Grid a const dims@(Dims m n) x = fromArray dims $ Vector.replicate (m*n) x allBlank :: (Unbox a, HasBlank a) => Grid a -> Bool allBlank g = Dims.all (dims g) $ \idx -> isBlank (getG g idx) nBlanks :: (Unbox a, HasBlank a) => Grid a -> Int nBlanks g = Dims.iter (dims g) 0 $ \acc idx -> if isBlank (getG g idx) then pure (acc + 1) else pure acc nNonBlanks :: (Unbox a, HasBlank a) => Grid a -> Int nNonBlanks g = Dims.iter (dims g) 0 $ \acc idx -> if nonBlank (getG g idx) then pure (acc + 1) else pure acc nPoints g = let (Dims nRows nCols) = dims g in nRows * nCols nonBlankFrac :: (Unbox a, HasBlank a) => Grid a -> Float nonBlankFrac g = (fromIntegral $ nNonBlanks g)/(fromIntegral $ nPoints g) nVal :: (Unbox a, HasBlank a) => Grid a -> a -> Int nVal g x = Dims.iter (dims g) 0 $ \acc idx -> if (getG g idx) == x then pure (acc + 1) else pure acc union :: (Unbox a, HasBlank a) => Grid a -> Grid a -> Maybe (Grid a) union g1 g2 = do guard $ sameDims g1 g2 pure $ fromFunc (dims g1) $ \idx -> if nonBlank (getG g1 idx) then (getG g1 idx) else (getG g2 idx) safeUnion :: (Unbox a, HasBlank a) => Grid a -> Grid a -> Maybe (Grid a) safeUnion g1 g2 = do guard $ sameDims g1 g2 fromFuncM (dims g1) $ \idx -> do let x1 = getG g1 idx let x2 = getG g2 idx when (nonBlank x1 && nonBlank x2) $ guard $ x1 == x2 pure $ if isBlank x1 then x2 else x1 toOffset :: (Unbox a) => Grid a -> Index -> Int toOffset g (Index i j) = i * nCols g + j toOffsetSafe :: (Unbox a) => Grid a -> Index -> Maybe Int toOffsetSafe g idx = do guard $ Dims.inBounds (dims g) idx pure $ toOffset g idx getD :: (Unbox a, HasBlank a) => Grid a -> Index -> a getD g idx = case toOffsetSafe g idx of Just i -> gridData g Vector.! i Nothing -> blank get :: (Unbox a) => Grid a -> Index -> a get g idx = gridData g Vector.! (toOffset g idx) getG :: (Unbox a) => Grid a -> Index -> a getG = Lib.Grid.get setD :: (Unbox a) => Grid a -> a -> Index -> Grid a setD g@(Grid gDims gData) val idx = case toOffsetSafe g idx of Just i -> Grid gDims $ gData Vector.// [(i, val)] Nothing -> g set :: (Unbox a) => Grid a -> a -> Index -> Grid a set g@(Grid gDims gData) val idx = Grid gDims $ gData Vector.// [(offset, val)] where offset = (toOffset g idx) setPairsD :: (Unbox a) => Grid a -> [(Index, a)] -> Grid a setPairsD g@(Grid gDims gData) pairs = runIdentity $ do let mappedPairs = flip Prelude.mapM pairs $ \(idx, val) -> case toOffsetSafe g idx of Just i -> pure $ (i, val) Nothing -> Nothing case mappedPairs of Just mPairs -> pure $ Grid gDims $ gData Vector.// mPairs Nothing -> pure g setPairs :: (Unbox a) => Grid a -> [(Index, a)] -> Grid a setPairs g@(Grid gDims gData) pairs = let mappedPairs = flip Prelude.map pairs $ \(idx, val) -> (toOffset g idx, val) in Grid gDims $ gData Vector.// mappedPairs setIdxsToVal :: (Unbox a) => Grid a -> [Index] -> a -> Grid a setIdxsToVal g@(Grid gDims gData) idxs val = let pairs = flip Prelude.map idxs (\idx -> (idx, val)) in Lib.Grid.setPairs g pairs getRow :: (Unbox a) => Grid a -> Int -> [a] getRow g rIdx = [getG g (Index rIdx k) | k <- range $ nCols g] getCol :: (Unbox a) => Grid a -> Int -> [a] getCol g cIdx = [getG g (Index k cIdx) | k <- range $ nRows g] nonBlankRows :: (Unbox a, HasBlank a) => Grid a -> [Int] nonBlankRows g = flip List.filter (range $ nRows g) $ \i -> flip any (getRow g i) $ \val -> nonBlank val nonBlankCols :: (Unbox a, HasBlank a) => Grid a -> [Int] nonBlankCols g = flip List.filter (range $ nCols g) $ \j -> flip any (getCol g j) $ \val -> nonBlank val sameBlanks :: (Unbox a, HasBlank a) => Grid a -> Grid a -> Bool sameBlanks g1 g2 = sameDims g1 g2 && core g1 g2 where core g1 g2 = Dims.all (dims g1) $ \idx -> isBlank (getG g1 idx) == isBlank (getG g2 idx) showGrid :: (Unbox a, Show a) => Grid a -> String showGrid g = let header = "Grid " ++ show (nRows g) ++ " " ++ show (nCols g) ++ "\n" in Int.iter (nRows g) header $ \acc i -> acc ++ "\n" ++ (showRow g i) where showRow :: (Unbox a, Show a) => Grid a -> Int -> String showRow g i = Int.iter (nCols g) "" $ \acc j -> acc ++ " " ++ show (getG g (Index i j)) ++ " " instance (Unbox a, Show a) => Show (Grid a) where show = showGrid neighbors :: (Unbox a) => Grid a -> Index -> [Index] neighbors input idx0 = do ax <- [Horizontal, Vertical, DownRight, DownLeft] dir <- [Normal, Reverse] let idx = idx0 + Index.scale (Direction.toScale dir) (Axis.toDelta ax) guard $ Dims.inBounds (dims input) idx pure idx neighborsOrtho :: (Unbox a) => Grid a -> Index -> [Index] neighborsOrtho input idx0 = do ax <- [Horizontal, Vertical] dir <- [Normal, Reverse] let idx = idx0 + Index.scale (Direction.toScale dir) (Axis.toDelta ax) guard $ Dims.inBounds (dims input) idx pure idx neighborsDiag :: (Unbox a) => Grid a -> Index -> [Index] neighborsDiag input idx0 = do ax <- [DownRight, DownLeft] dir <- [Normal, Reverse] let idx = idx0 + Index.scale (Direction.toScale dir) (Axis.toDelta ax) guard $ Dims.inBounds (dims input) idx pure idx showGridDiff :: Grid Color -> Grid Color -> Box.Grid String showGridDiff g1 g2 | sameDims g1 g2 = Box.fromFunc (dims g1) $ \idx -> if getG g1 idx == getG g2 idx then " " ++ show (getG g1 idx) ++ " " else "[" ++ show (getG g1 idx) ++ "|" ++ show (getG g2 idx) ++ "]" | otherwise = Box.const (Dims 1 1) (show (dims g1) ++ " != " ++ show (dims g2)) g1 is a subset of subset :: (Unbox a, HasBlank a, Eq a) => Grid a -> Grid a -> Bool subset g1 g2 = sameDims g1 g2 && subsetElems g1 g2 where subsetElems g1 g2 = Dims.all (dims g1) $ \idx -> (nonBlank $ getG g1 idx) <= (getG g1 idx == getG g2 idx) isNull :: (Unbox a) => Grid a -> Bool isNull g = dims g == Dims 0 0 transpose :: (Unbox a) => Grid a -> Grid a transpose g = fromFunc (Dims.transpose $ dims g) $ getG g . Index.transpose sameDims :: (Unbox a) => Grid a -> Grid b -> Bool sameDims g1 g2 = dims g1 == dims g2 beqUpto :: (Unbox a, Eq a) => Grid a -> Grid a -> Grid Bool -> Bool beqUpto g1 g2 mask = (isNull mask && g1 == g2) || (sameDims g1 g2 && sameDims g1 mask && beqUptoCore g1 g2 mask) where beqUptoCore g1 g2 mask = Dims.all (dims g1) $ \idx -> getG mask idx || getG g1 idx == getG g2 idx wherever appears in g1 , it is also val in interpretation : g1 is input , is output subsetForVal :: (Unbox a, Eq a) => Grid a -> Grid a -> a -> Bool subsetForVal g1 g2 val = (sameDims g1 g2) && beqUpto g1 g2 mask where mask = fromFunc (dims g1) $ \idx -> if (getG g1 idx) == val then False else True allSameDims :: (Unbox a, Unbox b) => Box.Grid (Grid a) -> Box.Grid (Grid b) -> Bool allSameDims g1 g2 = Box.sameDims g1 g2 && (Dims.all (Box.dims g1) $ \idx -> sameDims (Box.getG g1 idx) (Box.getG g2 idx)) uniformDims :: (Unbox a) => Box.Grid (Grid a) -> Bool uniformDims gs = let innerDims = dims (Box.get gs (Index 0 0)) in Dims.all (Box.dims gs) $ \idx -> dims (Box.get gs idx) == innerDims containsVal :: (Unbox a, Eq a) => a -> Grid a -> Bool containsVal x g = Dims.any (dims g) $ \idx -> getG g idx == x concatRows :: (Unbox a) => Grid a -> Grid a -> Maybe (Grid a) concatRows g1 g2 = do guard $ nCols g1 == nCols g2 pure $ fromFunc (Dims (nRows g1 + nRows g2) (nCols g2)) $ \idx@(Index i j) -> if i < nRows g1 then getG g1 (Index i j) else getG g2 (Index (i-nRows g1) j) concatCols :: (Unbox a) => Grid a -> Grid a -> Maybe (Grid a) concatCols g1 g2 = do guard $ nRows g1 == nRows g2 pure $ fromFunc (Dims (nRows g1) (nCols g1 + nCols g2)) $ \idx@(Index i j) -> if i < nCols g1 then getG g1 (Index i j) else getG g2 (Index i (j-nCols g1)) map :: (Unbox a, Unbox b) => (Index -> a -> b) -> Grid a -> Grid b map f g = fromFunc (dims g) $ \idx -> f idx $ getG g idx mapM :: (Unbox a, Unbox b, Monad m) => (Index -> a -> m b) -> Grid a -> m (Grid b) mapM f g = fromFuncM (dims g) $ \idx -> f idx $ getG g idx filter :: (Unbox a, HasBlank a) => (Index -> a -> Bool) -> Grid a -> Grid a filter f g = flip Lib.Grid.map g $ \idx x -> if f idx x then x else blank upscale :: (Unbox a) => Grid a -> Dims -> Box.Grid (Grid a) upscale g ds@(Dims km kn) = Box.fromFunc (dims g) (\idx -> Lib.Grid.const ds (getG g idx)) tile :: (Unbox a) => Grid a -> Dims -> Box.Grid (Grid a) tile g dims = Box.fromFunc dims $ \idx -> g TODO : these are pointlessly slow , better to use a Foldable / / whatever whenever needed toList :: (Unbox a) => Grid a -> [a] toList g = reverse $ Dims.iter (dims g) [] $ \acc idx -> pure $ (getG g idx):acc toListWithIndices :: (Unbox a) => Grid a -> [(Index, a)] toListWithIndices g = reverse $ Dims.iter (dims g) [] $ \acc idx -> pure $ (idx, getG g idx):acc Subgrids getSubgridUnsafe :: (Unbox a) => Grid a -> Dims -> Index -> Grid a getSubgridUnsafe g dims idx0 = fromFunc dims $ \idx -> getG g (idx0 + idx) getSubgridOpt :: (Unbox a) => Grid a -> Dims -> Index -> Maybe (Grid a) getSubgridOpt g sgDims@(Dims dx dy) idx0@(Index i j) = do let Dims gx gy = dims g guard $ dx + i <= gx guard $ dy + j <= gy pure $ fromFunc sgDims $ \idx -> getG g (idx0 + idx) findSubgrids :: (Unbox a) => Grid a -> Dims -> (Grid a -> Bool) -> [Index] findSubgrids g dims2@(Dims m2 n2) p = let Dims m1 n1 = dims g in Dims.iter (Dims (m1+1-m2) (n1+1-n2)) [] $ \acc idx -> pure $ if p (getSubgridUnsafe g dims2 idx) then idx:acc else acc replaceSubgridUnsafeM :: (Unbox a, Monad m) => Grid a -> Dims -> Index -> (Grid a -> m (Grid a)) -> m (Grid a) replaceSubgridUnsafeM grid dims idx0 grid2grid = let subgrid = getSubgridUnsafe grid dims idx0 in flip Lib.Grid.mapM grid $ \idx c -> do if Dims.inBounds dims (idx - idx0) then do newSubgrid <- grid2grid subgrid pure $ Lib.Grid.get newSubgrid (idx - idx0) else pure c instance Functor Grid where fmap : : ( Unbox a ) = > ( a - > b ) - > Grid a - > Grid b fmap f = Lib.Grid.map ( \ _ - > f ) instance Foldable Grid where foldMap : : ( Monoid m ) = > ( a - > m ) - > Grid a - > m foldMap f g = Dims.iter ( ) $ \acc idx - > pure $ acc < > f ( ) instance Grid where traverse : : ( Applicative m ) = > ( a - > m b ) - > Grid a - > m ( Grid b ) traverse _ _ = error " traverse not implemented for Grid " instance Functor Grid where fmap :: (Unbox a) => (a -> b) -> Grid a -> Grid b fmap f = Lib.Grid.map (\_ -> f) instance Foldable Grid where foldMap :: (Monoid m) => (a -> m) -> Grid a -> m foldMap f g = Dims.iter (dims g) mempty $ \acc idx -> pure $ acc <> f (getG g idx) instance Traversable Grid where traverse :: (Applicative m) => (a -> m b) -> Grid a -> m (Grid b) traverse _ _ = error "traverse not implemented for Grid" -} sequence : : = > Grid ( m a ) - > m ( Grid a ) sequence g = fromFuncM ( ) $ type UnpartitionFn a = Box.Grid (Grid a) -> Grid a partitionEven :: (Unbox a) => Dims -> Dims -> Grid a -> Maybe (Box.Grid (Grid a)) partitionEven outerDims@(Dims mOut nOut) innerDims@(Dims mIn nIn) g = do guard $ nRows g == mOut * mIn guard $ nCols g == nOut * nIn pure $ Box.fromFunc outerDims $ \(Index i j) -> getSubgridUnsafe g innerDims (Index (i * mIn) (j * nIn)) partitionEvenOuterDims :: (Unbox a) => Dims -> Grid a -> Maybe (Box.Grid (Grid a)) partitionEvenOuterDims dims@(Dims m n) g = do guard $ mod (nRows g) m == 0 guard $ mod (nCols g) n == 0 partitionEven dims (Dims (div (nRows g) m) (div (nCols g) n)) g partitionEvenInnerDims :: (Unbox a) => Dims -> Grid a -> Maybe (Box.Grid (Grid a)) partitionEvenInnerDims dims@(Dims m n) g = do guard $ mod (nRows g) m == 0 guard $ mod (nCols g) n == 0 partitionEven (Dims (div (nRows g) m) (div (nCols g) n)) dims g unpartitionEven :: (Unbox a) => Box.Grid (Grid a) -> Maybe (Grid a) unpartitionEven gs = do let innerDims = dims (Box.getG gs (Index 0 0)) guard $ Dims.all (Box.dims gs) $ \idx -> dims (Box.getG gs idx) == innerDims let Dims mIn nIn = innerDims let newDims = Dims (Box.nRows gs * mIn) (Box.nCols gs * nIn) pure $ fromFunc newDims $ \(Index i j) -> let g = Box.getG gs $ Index (div i mIn) (div j nIn) in getG g $ Index (mod i mIn) (mod j nIn) data RePartitionData = RePartitionData { structure :: Grid (Dims, Index) } rePartitionNoSepWith :: (Unbox a) => Grid a -> RePartitionData -> Maybe (Box.Grid (Grid a)) rePartitionNoSepWith g (RePartitionData structure) = do let outerDims = dims structure Box.fromFuncM outerDims $ \outerIdx -> do let (innerDims, oldIdx) = getG structure outerIdx getSubgridOpt g innerDims oldIdx computeRePartitionData :: (Unbox a) => Box.Grid (Grid a) -> Maybe RePartitionData computeRePartitionData gs = do guard $ Int.all (Box.nRows gs) $ \i -> Int.allSame (Box.nCols gs) $ \j -> nRows (Box.getG gs (Index i j)) guard $ Int.all (Box.nCols gs) $ \j -> Int.allSame (Box.nRows gs) $ \i -> nCols (Box.getG gs (Index i j)) let nRowList = Prelude.map (\i -> nRows (Box.getG gs (Index i 0))) (List.range $ Box.nRows gs) let nColList = Prelude.map (\j -> nCols (Box.getG gs (Index 0 j))) (List.range $ Box.nCols gs) let rowOffsets = 0 : scanl1 (+) nRowList let colOffsets = 0 : scanl1 (+) nColList pure $ RePartitionData $ fromFunc (Dims (length nRowList) (length nColList)) $ \idx@(Index i j) -> let innerDims :: Dims = dims (Box.getG gs idx) innerIdx :: Index = Index (rowOffsets List.!! i) (colOffsets List.!! j) in (innerDims, innerIdx) unpartitionNoSep :: (Unbox a) => Box.Grid (Grid a) -> Maybe (Grid a) unpartitionNoSep gs = do guard $ Int.all (Box.nRows gs) $ \i -> Int.allSame (Box.nCols gs) $ \j -> nRows (Box.getG gs (Index i j)) guard $ Int.all (Box.nCols gs) $ \j -> Int.allSame (Box.nRows gs) $ \i -> nCols (Box.getG gs (Index i j)) let nRowList = Prelude.map (\i -> nRows (Box.getG gs (Index i 0))) (List.range $ Box.nRows gs) let nColList = Prelude.map (\j -> nCols (Box.getG gs (Index 0 j))) (List.range $ Box.nCols gs) let rowOffsets = scanl1 (+) nRowList let colOffsets = scanl1 (+) nColList pure $ fromFunc (Dims (sum nRowList) (sum nColList)) $ \(Index i j) -> runIdentity $ do let Just (iOuter, iInner) = flip List.first (zip3 [0..] (0:init rowOffsets) rowOffsets) $ \(iOuter, start, end) -> if i >= start && i < end then Just (iOuter, i - start) else Nothing let Just (jOuter, jInner) = flip List.first (zip3 [0..] (0:init colOffsets) colOffsets) $ \(jOuter, start, end) -> if j >= start && j < end then Just (jOuter, j - start) else Nothing let g = Box.getG gs (Index iOuter jOuter) pure $ getG g (Index iInner jInner) data PartitionSepData = PartitionSepData { hLines :: [Int], vLines :: [Int] } deriving (Eq, Ord, Show) sameUnpartitionSep :: (Unbox a, HasBlank a) => PartitionSepData -> Grid a -> Grid a -> Bool sameUnpartitionSep pData g1 g2 = sameDims g1 g2 && List.all (\i -> Int.all (nCols g1) (\j -> getG g1 (Index i j) == getG g2 (Index i j))) (hLines pData) && List.all (\j -> Int.all (nRows g1) (\i -> getG g1 (Index i j) == getG g2 (Index i j))) (vLines pData) unpartitionSep :: (Unbox a, HasBlank a) => Grid a -> PartitionSepData -> Box.Grid (Grid a) -> Maybe (Grid a) unpartitionSep g0 (PartitionSepData hLines vLines) gs = do guard $ Int.all (Box.nRows gs) $ \i -> Int.allSame (Box.nCols gs) $ \j -> nRows (Box.getG gs (Index i j)) guard $ Int.all (Box.nCols gs) $ \j -> Int.allSame (Box.nRows gs) $ \i -> nCols (Box.getG gs (Index i j)) let rowStartCounts = computeSepStartCounts (nRows g0) hLines let colStartCounts = computeSepStartCounts (nCols g0) vLines pure $ fromFunc (dims g0) $ \idx@(Index i j) -> if elem i hLines || elem j vLines then getG g0 idx else let (outerRow, innerRow) = findOffsets rowStartCounts i (outerCol, innerCol) = findOffsets colStartCounts j in getG (Box.getG gs (Index outerRow outerCol)) (Index innerRow innerCol) where findOffsets :: [(Int, Int)] -> Int -> (Int, Int) findOffsets rowStartCounts i = Maybe.fromJust $ List.first (\(outerRow, (rowStart, nRows)) -> do guard $ rowStart <= i && i < rowStart + nRows pure (outerRow, i - rowStart)) (List.zip [0..] rowStartCounts) partitionSepWith :: (Unbox a, HasBlank a) => Grid a -> PartitionSepData -> Maybe (Box.Grid (Grid a)) partitionSepWith g (PartitionSepData hLines vLines) = do let rowStartCounts = computeSepStartCounts (nRows g) hLines let colStartCounts = computeSepStartCounts (nCols g) vLines guard $ length rowStartCounts > 0 && length colStartCounts > 0 let gs = Box.fromFunc (Dims (length rowStartCounts) (length colStartCounts)) $ \(Index i j) -> let (rowStart, nRows) = rowStartCounts List.!! i (colStart, nCols) = colStartCounts List.!! j in getSubgridUnsafe g (Dims nRows nCols) (Index rowStart colStart) pure gs computeSepStartCounts :: Int -> [Int] -> [(Int, Int)] computeSepStartCounts k lines = let segments = List.zip ([-1] ++ lines) (lines ++ [k]) in Prelude.map (\(start, next) -> (start + 1, next-start-1)) $ List.filter (\(start, next) -> next > start + 1) segments Coloring Utilities changeVal :: (Unbox a, Eq a) => Grid a -> a -> a -> Grid a changeVal g val1 val2 = flip Lib.Grid.map g $ \_ val -> if val == val1 then val2 else val swapVals :: (Unbox a, Eq a) => Grid a -> a -> a -> Grid a swapVals g val1 val2 = flip Lib.Grid.map g $ \_ val -> if val == val1 then val2 else if val == val2 then val1 else val distinctValsInGrids :: (Unbox a, Eq a, Ord a) => (a -> Bool) -> [Grid a] -> Set a distinctValsInGrids f gs = List.reduce (Set.union) id $ flip Prelude.map gs (\g -> distinctVals f g) pickColor :: (Unbox a, Monad m, Eq a, Ord a, HasBlank a) => SearchT m (Grid a -> Maybe a) pickColor = do choice "Grid.pickColor" [ ("majorityVal", pure (\g -> do let gMajority = fst (majorityVals g) guard $ (length gMajority) == 1 pure $ head gMajority)) , ("minorityVal", pure (\g -> do let gMinority = fst (minorityVals g) guard $ (length gMinority) == 1 pure $ head gMinority)) , ("majorityNonBlankVal", pure (\g -> do let (gMajority, maxCount) = majorityNonBlankVals g guard $ (length gMajority) == 1 && maxCount > 0 pure $ head gMajority)) , ("minorityNonBlankVal", pure (\g -> do let (gMinority, minCount) = minorityNonBlankVals g guard $ (length gMinority) == 1 && minCount > 0 pure $ head gMinority)) ] FIXME : should this just be StdGoal - > SearchT m ( Ex Color ) ? enumRelevantColors :: (Monad m, HasTrainTest m, HasSynth1Context m Color) => Ex (Grid Color) -> Ex.ForTrain (Grid Color) -> SearchT m (Ex Color) enumRelevantColors inputs outputs = choice "enumRelevantColors" [ ("ctx", synthCtx) , ("noCtx", do let distinctColors = distinctValsInGrids (\_ -> True) $ (Ex.toBigList inputs) ++ outputs c <- oneOf "Color.enumVals" $ flip Prelude.map (Data.Foldable.toList distinctColors) $ \k -> (show k, k) Ex.map (\_ -> c) <$> getDummyEx) , ("func", do phi <- pickColor (mappedColors :: Ex Color) <- liftO $ flip Ex.mapM inputs (\ig -> phi ig) pure $ mappedColors) ] | enumRelevantInts : : Ex ( Grid Color ) - > [ ( [ ] , Int , Maybe ( Ex Int ) ) ] enumRelevantInts inputs = [ ( " m - 1 " , 0 , pure $ Ex.map ( \ig - > ( Lib . Grid.nRows ig ) - 1 ) inputs ) , ( " n - 1 " , 0 , pure $ Ex.map ( \ig - > ( Lib . Grid.nCols ig ) - 1 ) inputs ) , ( " middleRow " , 1 , do guard $ flip Ex.all inputs $ \ig - > ( ( Lib . Grid.nRows ig ) ` mod ` 2 ) = = 1 pure $ flip Ex.map inputs $ \ig - > ( ( Lib . Grid.nRows ig ) ` div ` 2 ) + 1 ) , ( " middleCol " , 1 , do guard $ flip Ex.all inputs $ \ig - > ( ( Lib . Grid.nCols ig ) ` mod ` 2 ) = = 1 pure $ flip Ex.map inputs $ \ig - > ( ( Lib . Grid.nCols ig ) ` div ` 2 ) + 1 ) , ( " nDistinctVals " , 2 , pure $ Ex.map ( \ig - > Lib . Grid.nDistinctVals ( \ _ - > True ) ig ) inputs ) , ( " nDistinctNonBlanks " , 2 , pure $ Ex.map ( \ig - > Lib . Grid.nDistinctVals ig ) inputs ) ] enumRelevantInts :: Ex (Grid Color) -> [([Char], Int, Maybe (Ex Int))] enumRelevantInts inputs = [ ("m - 1", 0, pure $ Ex.map (\ig -> (Lib.Grid.nRows ig) - 1) inputs) , ("n - 1", 0, pure $ Ex.map (\ig -> (Lib.Grid.nCols ig) - 1) inputs) , ("middleRow", 1, do guard $ flip Ex.all inputs $ \ig -> ((Lib.Grid.nRows ig) `mod` 2) == 1 pure $ flip Ex.map inputs $ \ig -> ((Lib.Grid.nRows ig) `div` 2) + 1) , ("middleCol", 1, do guard $ flip Ex.all inputs $ \ig -> ((Lib.Grid.nCols ig) `mod` 2) == 1 pure $ flip Ex.map inputs $ \ig -> ((Lib.Grid.nCols ig) `div` 2) + 1) , ("nDistinctVals", 2, pure $ Ex.map (\ig -> Lib.Grid.nDistinctVals (\_ -> True) ig) inputs) , ("nDistinctNonBlanks", 2, pure $ Ex.map (\ig -> Lib.Grid.nDistinctVals nonBlank ig) inputs) ] -} enumRelevantInts :: (Monad m) => Ex (Grid Color) -> SearchT m (Ex Int) enumRelevantInts inputs = choice "enumRelevantInts" [ ("m - 1", pure $ Ex.map (\ig -> (Lib.Grid.nRows ig) - 1) inputs) , ("n - 1", pure $ Ex.map (\ig -> (Lib.Grid.nCols ig) - 1) inputs) , ("middleRow", do guard $ flip Ex.all inputs $ \ig -> ((Lib.Grid.nRows ig) `mod` 2) == 1 pure $ flip Ex.map inputs $ \ig -> ((Lib.Grid.nRows ig) `div` 2) + 1) , ("middleCol", do guard $ flip Ex.all inputs $ \ig -> ((Lib.Grid.nCols ig) `mod` 2) == 1 pure $ flip Ex.map inputs $ \ig -> ((Lib.Grid.nCols ig) `div` 2) + 1) , ("nDistinctVals", pure $ Ex.map (\ig -> Lib.Grid.nDistinctVals (\_ -> True) ig) inputs) , ("nDistinctNonBlanks", pure $ Ex.map (\ig -> Lib.Grid.nDistinctVals nonBlank ig) inputs) ] rowIsUniform :: (Unbox a, Eq a) => Grid a -> Int -> Maybe a rowIsUniform g i = do guard $ Int.allSame (nCols g) $ \j -> getG g (Index i j) pure $ getG g (Index i 0) colIsUniform :: (Unbox a, Eq a) => Grid a -> Int -> Maybe a colIsUniform g j = do guard $ Int.allSame (nRows g) $ \i -> getG g (Index i j) pure $ getG g (Index 0 j) isUniform :: (Unbox a, Eq a) => Grid a -> Maybe a isUniform g = do guard $ Int.allSame (nRows g * nCols g) $ \i -> getG g (Dims.int2index (dims g) i) pure $ getG g (Index 0 0) firstVal :: (Unbox a, Eq a) => (a -> Bool) -> Grid a -> Maybe a firstVal p g = Dims.first (dims g) $ \idx -> pure $ do guard $ p (getG g idx) pure $ getG g idx isSquare :: (Unbox a) => Grid a -> Maybe Int isSquare g = do guard $ nRows g == nCols g pure $ nRows g reflectAround :: (Unbox a) => Grid a -> Axis -> Grid a reflectAround g ax = flip Lib.Grid.map g $ \idx _ -> getG g (Axis.reflectAround (dims g) ax idx) isSymmetricAround :: (Unbox a, Eq a) => Axis -> Grid a -> Bool isSymmetricAround ax g = Dims.all (dims g) $ \idx -> getG g idx == getG g (Axis.reflectAround (dims g) ax idx) distinctVals :: (Unbox a, Eq a, Ord a) => (a -> Bool) -> Grid a -> Set a distinctVals p g = Dims.iter (dims g) Set.empty $ \acc idx -> pure $ if p (getG g idx) then Set.insert (getG g idx) acc else acc nDistinctVals :: (Unbox a, Eq a, Ord a) => (a -> Bool) -> Grid a -> Int nDistinctVals p g = Set.size $ distinctVals p g buildCounts :: (Unbox a, Eq a, Ord a) => (a -> Bool) -> Grid a -> Map a Int buildCounts p g = Dims.iter (dims g) Map.empty $ \acc idx -> let x = getG g idx in pure $ if p x then Map.insertWith (+) x 1 acc else acc maxValCount :: (Unbox a, Eq a, Ord a) => (a -> Bool) -> Grid a -> Int maxValCount p g = maximum . (0:) . Map.elems $ buildCounts p g nNonBlankVals :: (Unbox a, HasBlank a) => Grid a -> Int nNonBlankVals g = Dims.iter (dims g) 0 $ \acc idx -> pure $ if nonBlank (getG g idx) then acc + 1 else acc predIdxs :: (Unbox a) => Grid a -> (Index -> a -> Bool) -> Set Index predIdxs g f = Dims.iter (dims g) Set.empty $ \acc idx -> pure $ if f idx (getG g idx) then Set.insert idx acc else acc nonBlankIdxs :: (Unbox a, HasBlank a) => Grid a -> Set Index nonBlankIdxs g = predIdxs g (\_ val -> nonBlank val) valIdxs :: (Unbox a, Eq a) => Grid a -> a -> Set Index valIdxs g val = Dims.iter (dims g) Set.empty $ \acc idx -> pure $ if (getG g idx) == val then Set.insert idx acc else acc majorityVals :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> ([a], Int) majorityVals g = let counts = Map.toList $ buildCounts (\_ -> True) g in let biggestCount = snd $ List.maximumBy (\(c1, k1) (c2, k2) -> compare k1 k2) counts in (Prelude.map fst $ List.filter (\(_, count) -> count == biggestCount) counts, biggestCount) minorityVals :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> ([a], Int) minorityVals g = let counts = Map.toList $ buildCounts (\_ -> True) g in let smallestCount = snd $ List.minimumBy (\(c1, k1) (c2, k2) -> compare k1 k2) counts in (Prelude.map fst $ List.filter (\(_, count) -> count == smallestCount) counts, smallestCount) majorityNonBlankVals :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> ([a], Int) majorityNonBlankVals g = let counts = Map.toList $ buildCounts nonBlank g in if null counts then ([blank], 0) else let biggestCount = snd $ List.maximumBy (\(c1, k1) (c2, k2) -> compare k1 k2) counts in (Prelude.map fst $ List.filter (\(_, count) -> count == biggestCount) counts, biggestCount) majorityNonBlankVal :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> Maybe a majorityNonBlankVal g = case majorityNonBlankVals g of ([x], _) -> pure x _ -> Nothing minorityNonBlankVals :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> ([a], Int) minorityNonBlankVals g = let counts = Map.toList $ buildCounts nonBlank g in if null counts then ([blank], 0) else let smallestCount = snd $ List.minimumBy (\(c1, k1) (c2, k2) -> compare k1 k2) counts in (Prelude.map fst $ List.filter (\(_, count) -> count == smallestCount) counts, smallestCount) minorityNonBlankVal :: (Unbox a, Eq a, Ord a, HasBlank a) => Grid a -> Maybe a minorityNonBlankVal g = case minorityNonBlankVals g of ([x], _) -> pure x _ -> Nothing TODO : result in SearchT ? mapBinOp :: (Unbox a) => (a -> a -> a) -> Grid a -> Grid a -> Grid a mapBinOp f g1 g2 = if dims g1 == dims g2 then fromFunc (dims g1) $ \idx -> f (getG g1 idx) (getG g2 idx) else error "mapBinOp called with bad dims" map3Op1 :: (Unbox a) => (a -> a -> a -> a) -> Grid a -> Grid a -> Grid a map3Op1 f g1 g2 = if dims g1 == dims g2 then fromFunc (dims g1) $ \idx -> f (getG g1 idx) (getG g1 idx) (getG g2 idx) else error "map3Op1 called with bad dims" let ( Index 0 0 ) in Dims.iter ( ) x0 $ \acc idx - > pure $ if idx = = Index 0 0 then acc else f acc ( ) reduceBinOp :: (Unbox a) => (a -> a -> a) -> Grid a -> [Index] -> a reduceBinOp f g ordering = List.reduce (\acc val -> f acc val) (\idx -> getG g idx) ordering FIXME : do we want to use Axis.orthoDist ? the nearest val that ISNT YOUR nearestNonSelfVal :: Grid Color -> Grid Color nearestNonSelfVal g = let nonSelfNonBlanks :: Map Color (Set Index) = List.iter distinctGridVals Map.empty $ \acc val -> pure $ Map.insert val (flip Set.filter gridNonBlanks (\idx -> (getG g idx) /= val)) acc in fromFunc (dims g) $ \idx -> let nonValNonBlanks :: Set Index = Maybe.fromJust $ Map.lookup (getG g idx) nonSelfNonBlanks in if null nonValNonBlanks then blank else let closestIdxs :: [Index] = List.argminsKey (\idx2 -> Axis.dist OrthoDist idx idx2) (Set.toList nonValNonBlanks) in if length closestIdxs == 1 || List.allSame (flip Prelude.map closestIdxs (\idx -> getG g idx)) then getG g (closestIdxs !! 0) else blank where distinctGridVals = Set.toList $ distinctVals (\_ -> True) g nearestNonBlank :: Grid Color -> Grid Color nearestNonBlank g = if Lib.Grid.allBlank g then g if only have one distinct nonblank , then const grid of that nonblank else if (Lib.Grid.nDistinctVals nonBlank g) == 1 then Lib.Grid.const (dims g) (Set.elemAt 0 (distinctVals nonBlank g)) else fromFunc (dims g) $ \idx -> if null gridNonBlanks then blank else let closestIdxs = List.argminsKey (\idx2 -> Axis.dist OrthoDist idx idx2) gridNonBlanks in if length closestIdxs == 1 || List.allSame (flip Prelude.map closestIdxs (\idx -> getG g idx)) then getG g (closestIdxs !! 0) else blank where nearestNonSelfIdx :: Grid Color -> Grid Color nearestNonSelfIdx g = if Lib.Grid.allBlank g then g else fromFunc (dims g) $ \idx -> if null gridNonBlanks then blank else case Prelude.filter (\idx2 -> idx /= idx2) gridNonBlanks of [] -> blank xs -> let closestIdxs = List.argminsKey (\idx2 -> Axis.dist OrthoDist idx idx2) xs in if length closestIdxs == 1 || List.allSame (flip Prelude.map closestIdxs (\idx -> getG g idx)) then getG g (closestIdxs !! 0) else blank extremeNonBlankDistances :: (Monad m) => Ex (Grid Color) -> SearchT m (Ex (Grid Int)) extremeNonBlankDistances inputs = do ensure that each input grid has at least one non - blank ( not always true ! ) guard $ flip Ex.all inputs $ \ig -> not (Lib.Grid.allBlank ig) guard that there are n't too many non - blanks ( currently 1/3 , which is fairly strict ) guard $ flip Ex.all inputs $ \ig -> (Lib.Grid.nNonBlanks ig) < ((Dims.nCells (dims ig)) `div` 3) distFunc <- oneOf "extremeNonBlankDistances.distFunc" [("ortho", Axis.dist OrthoDist), ("diag", Axis.dist DiagDist)] extreme <- oneOf "extremeNonBlankDistances.extreme" [("max", 1), ("min", -1)] pure $ flip Ex.map inputs $ \ig -> Lib.Grid.extremeDistToNonBlank (\idx1 idx2 -> extreme * (distFunc idx1 idx2)) ig extremeBlankDistances :: (Monad m) => Ex (Grid Color) -> SearchT m (Ex (Grid Int)) extremeBlankDistances inputs = do ensure that each input grid has at least one non - blank ( not always true ! ) guard $ flip Ex.all inputs $ \ig -> containsVal blank ig TODO : currently not guarding that there is some amoutn of to limit perf distFunc <- oneOf "extremeBlankDistances.distFunc" [("ortho", Axis.dist OrthoDist), ("diag", Axis.dist DiagDist)] currently just using min , not extreme <- oneOf "extremeBlankDistances.extreme" [("min", -1)] pure $ flip Ex.map inputs $ \ig -> Lib.Grid.extremeDistToBlank (\idx1 idx2 -> extreme * (distFunc idx1 idx2)) ig extremeDistancesToVal :: (Monad m) => Ex (Grid Color) -> Ex Color -> SearchT m (Ex (Grid (Maybe Int))) extremeDistancesToVal inputs cs = do guard $ flip List.majority (Ex.toBigList (Ex.zip inputs cs)) $ \(ig, c) -> containsVal c ig distFunc <- oneOf "extremeDistancesToVal.distFunc" [("ortho", Axis.dist OrthoDist), ("diag", Axis.dist DiagDist)] extreme <- oneOf "extremeDistancesToVal.extreme" [("max", 1), ("min", -1)] pure $ flip Ex.map (Ex.zip inputs cs) $ \(ig, c) -> if not (containsVal c ig) then Lib.Grid.const (dims ig) Nothing else Lib.Grid.map (\idx val -> Just val) $ Lib.Grid.extremeDistToVal (\idx1 idx2 -> extreme * (distFunc idx1 idx2)) ig c nNeighborsAxDirs :: (Unbox a, HasBlank a) => Grid a -> [(Axis, Direction)] -> Index -> Int nNeighborsAxDirs g axDirs idx = flip List.count axDirs $ \(ax, dir) -> let idxInAxDir = Direction.step idx 1 ax dir in nonBlank (getD g idxInAxDir) nNeighborColorsAxDirs :: (Unbox a, Ord a, HasBlank a) => Grid a -> [(Axis, Direction)] -> Index -> Int nNeighborColorsAxDirs g axDirs idx = List.countDistinct id (List.filter (\x -> nonBlank x) neighborColors) where neighborColors = flip List.map axDirs $ \(ax, dir) -> getD g (Direction.step idx 1 ax dir) isSurrounded :: (Unbox a, HasBlank a) => Grid a -> Grid Bool isSurrounded g = flip Lib.Grid.map g $ \idx _ -> (nNeighborsAxDirs g axDirs idx) == 8 where axDirs = [(ax, dir) | ax <- [Horizontal, Vertical, DownRight, DownLeft], dir <- [Normal, Reverse]] Note : motivated by 6d0160f0 findIndices :: (Unbox a) => (a -> Bool) -> Grid a -> [Index] findIndices p g = Dims.iter (dims g) [] $ \acc idx -> pure $ if p (getG g idx) then idx:acc else acc enumMaybeIndices :: (Monad m, HasSynth1Context m Color) => SearchT m (Ex (Grid Color -> [Index])) enumMaybeIndices = choice "Grid.enumMaybeIndices" [ ("ofColor", Ex.map (\c -> \g -> findIndices (==c) g) <$> enumColorsCtx) ] enumColorSets :: (Monad m) => SearchT m (Grid Color -> Set Color) enumColorSets = choice "Grid.enumColorSets" [ ("distinctNonBlankVals", pure $ \g -> distinctVals nonBlank g) ] enumGridPreserving :: (Unbox a, Monad m) => SearchT m (Grid a -> Grid a) enumGridPreserving = oneOf "Grid.enumPreservingTrans" [ ("id", id), ("reflectHorizontal", flip Lib.Grid.reflectAround Horizontal), ("reflectVertical", flip Lib.Grid.reflectAround Vertical) ] horizontalLines :: (Unbox a, HasBlank a, Eq a) => Grid a -> [Int] horizontalLines g = flip List.filter (range $ nRows g) $ \i -> let x = getG g (Index i 0) in (x /= blank) && (Int.all (nCols g) $ \j -> getG g (Index i j) == x) verticalLines :: (Unbox a, HasBlank a, Eq a) => Grid a -> [Int] verticalLines g = flip List.filter (range $ nCols g) $ \j -> let x = getG g (Index 0 j) in (x /= blank) && (Int.all (nRows g) $ \i -> getG g (Index i j) == x) getDominantElem :: (Unbox a, Eq a, Ord a, Show a) => [a] -> Float -> Maybe a getDominantElem r frac = do guard . not . null $ r let domElems = maximumBy (comparing length) . List.group $ (List.sort r) guard . not . null $ domElems let domElemFrac = (fromIntegral $ length domElems)/(fromIntegral $ length r) guard (frac <= domElemFrac) pure . head $ domElems existsDominantElem :: (Unbox a, Eq a, Ord a, Show a) => [a] -> Float -> Bool existsDominantElem r frac = isJust $ getDominantElem r frac fuzzyHorizontalLines :: (Unbox a, HasBlank a, Eq a, Show a, Ord a) => Grid a -> Float -> [Int] fuzzyHorizontalLines g frac = flip List.filter (range $ nRows g) $ \i -> existsDominantElem (getRow g i) frac fuzzyVerticalLines :: (Unbox a, HasBlank a, Eq a, Show a, Ord a) => Grid a -> Float -> [Int] fuzzyVerticalLines g frac = flip List.filter (range $ nCols g) $ \j -> existsDominantElem (getCol g j) frac horizontalLinesColor :: (Unbox a, HasBlank a, Eq a) => a -> Grid a -> [Int] horizontalLinesColor x0 g = flip List.filter (range $ nRows g) $ \i -> let x = getG g (Index i 0) in (x == x0) && (Int.all (nCols g) $ \j -> getG g (Index i j) == x) verticalLinesColor :: (Unbox a, HasBlank a, Eq a) => a -> Grid a -> [Int] verticalLinesColor x0 g = flip List.filter (range $ nCols g) $ \j -> let x = getG g (Index 0 j) in (x == x0) && (Int.all (nRows g) $ \i -> getG g (Index i j) == x) lineBoolVals :: (Unbox a) => Grid a -> ([a] -> Bool) -> Axis -> Map Int Bool lineBoolVals g f ax = List.iter (range (Line.numAxLines (dims g) ax)) Map.empty $ \acc ident -> let lineVals = Prelude.map (\idx -> getG g idx) $ Line.idxsOfId (dims g) ax ident in pure $ Map.insert ident (f lineVals) acc lineIntVals :: (Unbox a) => Grid a -> ([a] -> Int) -> Axis -> Map Int Int lineIntVals g f ax = List.iter (range (Line.numAxLines (dims g) ax)) Map.empty $ \acc ident -> let lineVals = Prelude.map (\idx -> getG g idx) $ Line.idxsOfId (dims g) ax ident in pure $ Map.insert ident (f lineVals) acc lineColorVals :: (Unbox a) => Grid a -> ([a] -> Color) -> Axis -> Map Int Color lineColorVals g f ax = List.iter (range (Line.numAxLines (dims g) ax)) Map.empty $ \acc ident -> let lineVals = Prelude.map (\idx -> getG g idx) $ Line.idxsOfId (dims g) ax ident in pure $ Map.insert ident (f lineVals) acc lineIdxsP :: (Unbox a, HasBlank a) => Grid a -> (Index -> a -> Bool) -> Axis -> Direction -> Int -> [Index] lineIdxsP g f ax dir ident = let predIdxs = flip List.filter (Line.idxsOfId (dims g) ax ident) $ \idx -> f idx (getG g idx) in if dir == Reverse then reverse predIdxs else predIdxs nonBlankLineIdxs :: (Unbox a, HasBlank a) => Grid a -> Axis -> Direction -> Int -> [Index] nonBlankLineIdxs g ax dir ident = lineIdxsP g (\idx val -> nonBlank val) ax dir ident blankLineIdxs :: (Unbox a, HasBlank a) => Grid a -> Axis -> Direction -> Int -> [Index] blankLineIdxs g ax dir ident = lineIdxsP g (\idx val -> isBlank val) ax dir ident valLineIdxs :: (Unbox a, HasBlank a, Eq a) => Grid a -> a -> Axis -> Direction -> Int -> [Index] valLineIdxs g x ax dir ident = lineIdxsP g (\idx val -> val == x) ax dir ident axisBlank :: (Unbox a, HasBlank a) => Grid a -> Axis -> Grid Bool axisBlank g ax = let vals :: Map Int Bool = lineBoolVals g (\lineVals -> flip Prelude.all lineVals $ \val -> isBlank val) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals axHasVal :: (Unbox a, HasBlank a) => Grid a -> a -> Axis -> Grid Bool axHasVal g x ax = let vals :: Map Int Bool = lineBoolVals g (\lineVals -> flip Prelude.any lineVals $ \val -> val == x) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals nInAxis :: (Unbox a, HasBlank a, Ord a, Eq a) => Grid a -> Axis -> Grid Int nInAxis g ax = let vals :: Map Int Int = lineIntVals g (\lineVals -> List.count nonBlank lineVals) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals nBlankInAxis :: (Unbox a, HasBlank a, Ord a, Eq a) => Grid a -> Axis -> Grid Int nBlankInAxis g ax = let vals :: Map Int Int = lineIntVals g (\lineVals -> List.count isBlank lineVals) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals idxInAxis :: Grid a -> Index -> Axis -> Grid Bool idxInAxis g idx ax = let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax identOfIdx :: Int = idxMapper idx in fromFunc (dims g) $ \idx2 -> if (idxMapper idx2) == identOfIdx then True else False idxInAxDir :: (Unbox a) => Grid a -> Index -> Axis -> Direction -> Grid Bool idxInAxDir g idx ax dir = let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax identOfIdx :: Int = idxMapper idx in fromFunc (dims g) $ \idx2 -> if (idxMapper idx2) == identOfIdx && Direction.precedes ax dir idx2 idx then True else False anyIdxInAxDir :: (Unbox a) => Grid a -> [Index] -> Axis -> Direction -> Grid Bool anyIdxInAxDir g idxs ax dir = List.reduce (\g1 g2 -> mapBinOp (Blank.orD True) g1 g2) (\idx -> idxInAxDir g idx ax dir) idxs axMax :: Grid Color -> Axis -> Grid Color axMax g ax = let vals :: Map Int Color = lineColorVals g (\lineVals -> flip List.argmaxKey (List.nub lineVals) $ \val -> if val == blank then 0 else (List.count (\val2 -> val2 == val) lineVals)) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals nDistinctInAxis :: (Unbox a, Ord a, Eq a) => Grid a -> Axis -> Grid Int nDistinctInAxis g ax = let vals :: Map Int Int = lineIntVals g (\lineVals -> List.countDistinct id lineVals) ax idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> Maybe.fromJust $ Map.lookup (idxMapper idx) vals nearestValInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid a nearestValInAxDir g ax dir = let axesNonBlanks :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> nonBlankLineIdxs g ax dir ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> case flip List.first (axesNonBlanks !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing of Nothing -> blank Just idx2 -> getG g idx2 furthestValInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid a furthestValInAxDir g ax dir = let axesNonBlanks :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> nonBlankLineIdxs g ax (Direction.reverse dir) ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> case flip List.first (axesNonBlanks !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing of Nothing -> blank Just idx2 -> getG g idx2 idxOfNearestInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid (Maybe Index) idxOfNearestInAxDir g ax dir = let axesNonBlanks :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> nonBlankLineIdxs g ax dir ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> flip List.first (axesNonBlanks !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing note the use of diagDist rather than orthoDist because we know we will be in the same axDir distToNearestNonBlankInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid (Maybe Int) distToNearestNonBlankInAxDir g ax dir = let axesNonBlanks :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> nonBlankLineIdxs g ax dir ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> case flip List.first (axesNonBlanks !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing of Nothing -> Nothing Just idx2 -> Just $ Axis.dist DiagDist idx idx2 note the use of diagDist rather than orthoDist because we know we will be in the same axDir distToNearestBlankInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid (Maybe Int) distToNearestBlankInAxDir g ax dir = let axesBlanks :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> blankLineIdxs g ax dir ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> case flip List.first (axesBlanks !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing of Nothing -> Nothing Just idx2 -> Just $ Axis.dist DiagDist idx idx2 distToNearestValInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> a -> Axis -> Direction -> Grid (Maybe Int) distToNearestValInAxDir g x ax dir = if not (containsVal x g) then Lib.Grid.const (dims g) Nothing else let axesVals :: [[Index]] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> valLineIdxs g x ax dir ident idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax in fromFunc (dims g) $ \idx -> case flip List.first (axesVals !! (idxMapper idx)) $ \idx2 -> if Direction.precedes ax dir idx idx2 then Just idx2 else Nothing of Nothing -> Nothing Just idx2 -> Just $ Axis.dist DiagDist idx idx2 extremeDistToPred :: (Unbox a, HasBlank a) => (Index -> Index -> Int) -> (Index -> a -> Bool) -> Grid a -> Grid Int extremeDistToPred distFunc predF g = flip Lib.Grid.map g $ \idx _ -> abs (List.maximum (List.map (distFunc idx) gridPredIdxs)) where gridPredIdxs = Set.toList $ predIdxs g predF FIXME : Could currently include 0s . Do we want this ? If not , we have to guard that there are at least 2 non blanks in the grid extremeDistToNonBlank :: (Unbox a, HasBlank a) => (Index -> Index -> Int) -> Grid a -> Grid Int extremeDistToNonBlank distFunc g = extremeDistToPred distFunc (\_ val -> nonBlank val) g extremeDistToBlank :: (Unbox a, HasBlank a) => (Index -> Index -> Int) -> Grid a -> Grid Int extremeDistToBlank distFunc g = extremeDistToPred distFunc (\_ val -> isBlank val) g extremeDistToVal :: (Unbox a, Eq a, HasBlank a) => (Index -> Index -> Int) -> Grid a -> a -> Grid Int extremeDistToVal distFunc g x = extremeDistToPred distFunc (\_ val -> val == x) g distToNonBlankLineInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid (Maybe Int) distToNonBlankLineInAxDir g ax dir = runIdentity $ do let linesWithNonBlank :: [Int] = flip List.filter (range (Line.numAxLines (dims g) ax)) $ \lineId -> flip Prelude.any (Line.idxsOfId (dims g) ax lineId) $ \idx -> nonBlank (getG g idx) let orderedNonBlankLines :: [Int] = if dir == Reverse then reverse linesWithNonBlank else linesWithNonBlank let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax let decider :: Int -> Int -> Bool = case dir of Normal -> \i1 i2 -> i1 > i2 Reverse -> \i1 i2 -> i1 < i2 let distPerLine :: [Maybe Int] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \lineId -> case flip List.first orderedNonBlankLines (\ident -> if decider ident lineId then Just ident else Nothing) of Nothing -> Nothing Just ident1 -> Just (abs (lineId - ident1)) pure $ fromFunc (dims g) $ \idx -> (distPerLine !! (idxMapper idx)) nonBlankLineExistsInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid Bool nonBlankLineExistsInAxDir g ax dir = runIdentity $ do let linesWithNonBlank :: [Int] = flip List.filter (range (Line.numAxLines (dims g) ax)) $ \lineId -> flip Prelude.any (Line.idxsOfId (dims g) ax lineId) $ \idx -> nonBlank (getG g idx) let orderedNonBlankLines :: [Int] = if dir == Reverse then reverse linesWithNonBlank else linesWithNonBlank let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax let decider :: Int -> Int -> Bool = case dir of Normal -> \i1 i2 -> i1 > i2 Reverse -> \i1 i2 -> i1 < i2 let decisionPerLine :: [Bool] = flip Prelude.map (range (Line.numAxLines (dims g) ax )) $ \lineId -> flip Prelude.any orderedNonBlankLines $ \ident -> decider ident lineId pure $ fromFunc (dims g) $ \idx -> (decisionPerLine !! (idxMapper idx)) lineWithValExistsInAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> a -> Axis -> Direction -> Grid Bool lineWithValExistsInAxDir g x ax dir = runIdentity $ do let linesWithVal :: [Int] = flip List.filter (range (Line.numAxLines (dims g) ax)) $ \lineId -> flip Prelude.any (Line.idxsOfId (dims g) ax lineId) $ \idx -> (getG g idx) == x let orderedLinesWithVal :: [Int] = if dir == Reverse then reverse linesWithVal else linesWithVal let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax let decider :: Int -> Int -> Bool = case dir of Normal -> \i1 i2 -> i1 > i2 Reverse -> \i1 i2 -> i1 < i2 let decisionPerLine :: [Bool] = flip Prelude.map (range (Line.numAxLines (dims g) ax )) $ \lineId -> flip Prelude.any orderedLinesWithVal $ \ident -> decider ident lineId pure $ fromFunc (dims g) $ \idx -> (decisionPerLine !! (idxMapper idx)) nonBlankExistsToAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> Axis -> Direction -> Grid Bool nonBlankExistsToAxDir g ax dir = do let axesMaxNonBlanks :: [Index] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> do let lineNonBlankIdxs = flip List.filter (Line.idxsOfId (dims g) ax ident) $ \idx -> nonBlank (getG g idx) if null lineNonBlankIdxs then (Index (-1) (-1)) else Direction.furthestInAxDir lineNonBlankIdxs ax dir let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax fromFunc (dims g) $ \idx -> do let maxInLine :: Index = axesMaxNonBlanks !! (idxMapper idx) if maxInLine == Index (-1) (-1) then False else Direction.precedes ax dir idx maxInLine valExistsToAxDir :: (Unbox a, HasBlank a, Eq a) => Grid a -> a -> Axis -> Direction -> Grid Bool valExistsToAxDir g x ax dir = do let axesMaxVals :: [Index] = flip Prelude.map (range (Line.numAxLines (dims g) ax)) $ \ident -> do let lineValIdxs = flip List.filter (Line.idxsOfId (dims g) ax ident) $ \idx -> (getG g idx) == x ( -1 , -1 ) indicates the non - existence of a val in axdir if null lineValIdxs then (Index (-1) (-1)) else Direction.furthestInAxDir lineValIdxs ax dir let idxMapper :: Index -> Int = Line.idxAxisId (dims g) ax fromFunc (dims g) $ \idx -> do let maxInLine :: Index = axesMaxVals !! (idxMapper idx) if maxInLine == Index (-1) (-1) then False else Direction.precedes ax dir idx maxInLine cropDeltas :: Grid a -> Axis -> [Int] cropDeltas grid ax = case ax of Horizontal -> List.range $ nCols grid Vertical -> List.range $ nRows grid _ -> List.range $ min (nRows grid) (nCols grid) cropAlongAxDirOpt :: Grid a -> Axis -> Direction -> Int -> Maybe Rect cropAlongAxDirOpt grid ax dir delta = case (ax, dir) of (Horizontal, Normal) -> do guard $ delta < nCols grid pure $ Rect (Index 0 delta) (Dims (nRows grid) ((nCols grid) - delta)) (Horizontal, Reverse) -> do guard $ delta < nCols grid pure $ Rect (Index 0 0) (Dims (nRows grid) ((nCols grid) - delta)) (Vertical, Normal) -> do guard $ delta < nRows grid pure $ Rect (Index delta 0) (Dims ((nRows grid) - delta) (nCols grid)) (Vertical, Reverse) -> do guard $ delta < nRows grid pure $ Rect (Index 0 0) (Dims ((nRows grid) - delta) (nCols grid)) (DownRight, Normal) -> do guard $ delta < min (nRows grid) (nCols grid) pure $ Rect (Index delta delta) (Dims ((nRows grid) - delta) ((nCols grid) - delta)) (DownRight, Reverse) -> do guard $ delta < min (nRows grid) (nCols grid) pure $ Rect (Index 0 0) (Dims ((nRows grid) - delta) ((nCols grid) - delta)) (DownLeft, Normal) -> do guard $ delta < min (nRows grid) (nCols grid) pure $ Rect (Index delta 0) (Dims ((nRows grid) - delta) ((nCols grid) - delta)) (DownLeft, Reverse) -> do guard $ delta < min (nRows grid) (nCols grid) pure $ Rect (Index 0 delta) (Dims ((nRows grid) - delta) ((nCols grid) - delta)) rectInBounds :: (Unbox a) => Grid a -> Rect -> Bool rectInBounds g (Rect ul (Dims nR nC)) = Dims.inBounds (dims g) (ul + (Index (nR - 1) (nC - 1))) && Dims.inBounds (dims g) ul nonBlankRect :: (Unbox a, HasBlank a) => Grid a -> Maybe Rect nonBlankRect g = do let (minRow, maxRow, minCol, maxCol) = Dims.iter (dims g) (nRows g, 0, nCols g, 0) $ \vals@(minRow, maxRow, minCol, maxCol) idx@(Index i j) -> pure $ if nonBlank (getG g idx) then (min minRow i, max maxRow i, min minCol j, max maxCol j) else vals guard $ minRow < nRows g && minCol < nCols g pure $ Rect { Rect.upperLeft = Index minRow minCol, Rect.dims = Dims (maxRow + 1 - minRow) (maxCol + 1 - minCol) } getRect :: (Unbox a) => Grid a -> Rect -> Grid a getRect g (Rect ul dims) = getSubgridUnsafe g dims ul embedRectIn :: (Unbox a, HasBlank a) => Grid a -> Rect -> Grid a -> Maybe (Grid a) embedRectIn bg rect@(Rect (Index ri rj) rDims@(Dims dx dy)) g = do let outerDims = dims bg guard $ rDims == dims g guard $ ri + dx <= Dims.nRows outerDims guard $ rj + dy <= Dims.nCols outerDims pure $ fromFunc outerDims $ \idx@(Index i j) -> if (i >= ri && i < ri + dx && j >= rj && j < rj + dy) then getG g (idx - Index ri rj) else getG bg idx embedRectInBlank :: (Unbox a, HasBlank a) => Dims -> Rect -> Grid a -> Maybe (Grid a) embedRectInBlank outerDims = embedRectIn (Lib.Grid.const outerDims blank) nonBlankShape :: (Unbox a, HasBlank a) => Grid a -> Maybe (Shape a) nonBlankShape g = case nonBlankRect g of Just r -> Just $ Shape.fromList (flip Prelude.map (Rect.getIdxs r) (\idx -> (idx, getG g idx))) Nothing -> Nothing fromShapes :: (Unbox a, HasBlank a) => Dims -> [Shape a] -> Grid a fromShapes dims shapes = fromFunc dims $ \idx -> case flip List.first shapes $ \s -> Shape.lookupIndex s idx of Nothing -> blank Just x -> x replacingShapes :: (Unbox a, HasBlank a) => Grid a -> [Shape a] -> [Shape a] -> Grid a replacingShapes g oldShapes newShapes = flip Lib.Grid.map g $ \idx x0 -> case flip List.first newShapes $ \s -> Shape.lookupIndex s idx of Just x -> x Nothing -> case flip List.first oldShapes $ \s -> Shape.lookupIndex s idx of Just _ -> blank Nothing -> x0 lookupShape :: (Unbox a, HasBlank a) => Grid a -> Shape b -> Shape a lookupShape g s = Shape.fromList $ Prelude.map (\idx -> (idx, getG g idx)) $ Shape.indices s shapeOrthoNeighbors :: (Unbox a, Eq a, Ord a) => Grid a -> Shape a -> [Index] shapeOrthoNeighbors g s = let allNeighbors = List.nub $ List.iter (Shape.indices s) [] $ \acc sIdx -> pure $ acc ++ (neighborsOrtho g sIdx) in List.filter (\neighbIdx -> not (Shape.containsIndex s neighbIdx)) allNeighbors shapeDiagNeighbors :: (Unbox a, Eq a, Ord a) => Grid a -> Shape a -> [Index] shapeDiagNeighbors g s = let allNeighbors = List.nub $ List.iter (Shape.indices s) [] $ \acc sIdx -> pure $ acc ++ (neighborsDiag g sIdx) in List.filter (\neighbIdx -> not (Shape.containsIndex s neighbIdx)) allNeighbors shapeAllNeighbors :: (Unbox a, Eq a, Ord a) => Grid a -> Shape a -> [Index] shapeAllNeighbors g s = let allNeighbors = List.nub $ List.iter (Shape.indices s) [] $ \acc sIdx -> pure $ acc ++ (neighbors g sIdx) in List.filter (\neighbIdx -> not (Shape.containsIndex s neighbIdx)) allNeighbors shapesNeighbors :: (Unbox a, Eq a, Ord a) => Grid a -> [Shape a] -> (Grid a -> Shape a -> [Index]) -> [Index] shapesNeighbors g shapes neighborFn = List.nub $ List.iter shapes [] $ \acc s -> pure $ acc ++ (neighborFn g s)
f5c49bbecb79e58b4bcda2cc700a3c09b7225fcbedc6308e653973f2753837a5
practicalli/clojure-through-code
03-using-data-structures.clj
;;;;;;;;;;;;;;;;;;;;;;;;;;;; Using Clojure data structures (ns clojure-through-code.03-using-data-structures) Defining things is easy in Clojure Defining things is as simple as giving a name to a value , of course in Clojure the evaluation of a function is also a value . (def person "Jane Doe") ;; Names are of course case sensitive, so Person is not the same as person (def Person "James Doh") Clojure uses dynamic typing , this means its trivial to mix and match different kinds of data . ;; Here we are defining a name for a vector, which contains numbers, a string and name of another def. (def my-data [1 2 3 "frog" person]) my-data ;; You can also dynamically re-define a name to points to a different value (def my-data [1 2 3 4 5 "frog" person]) ;; the original value that defined my-data remains unchanged (its immutable), so anything using that value remains unaffected. Essentially we are re-mapping my-data to a new value. ;; Lets define a name to point to a list of numbers (def my-list '(1 2 3)) ;; We are returned that list of numbers when we evaluate the name my-list ;; We can use the cons function to add a number to our list, ;; however because lists are immutable, rather than changing the original list, a new one is returned ;; So if we want to keep on refering to our "changed" list, we need to give it a name (def my-list-updated (cons 4 my-list)) ;; As you can see we have not changed the original list my-list ;; The new list does have the change though. my-list-updated As names in Clojure are dynamic , we can of course point the original name to the new list (def my-list (cons 5 my-list)) ;; so now when we evaluate the original name, we get the updated list my-list ;;;;;;;;;;;;;;;;;;;;;;;;; ;; Practising with lists ;; Create a simple collection of developer event names ;; first lets use a list of strings at it seems the easiest straight forward (def developer-events-strings '("Devoxx UK" "Devoxx France" "Devoxx" "Hack the Tower")) > Remember , in Clojure the first element of a list is treated as a function call , so we have used the quote ' character to tell Cloojure to also treat the first element as data . We could of course have used the list function to define our list ` ( def developer - events - strings2 ( list " Devoxx UK " " Devoxx France " " Devoxx " " Hack the Tower " ) ) ` developer-events-strings We can get just the first element in our collection of developer events (first developer-events-strings) using a Clojure Vector data structure seems a little more Clojurey , especially when the vector contains keywords . Think of a Vector as an Array , although in Clojure it is again immutable in the same way a list is . (def developer-events-vector [:devoxxuk :devoxxfr :devoxx :hackthetower] ) ;; Lets create a slightly more involved data structure, ;; holding more data around each developer events. ;; This data structure is just a map, with each key being ;; the unique name of the developer event. ;; The details of each event (the value to go with the ;; event name key) is itself a map as there are several ;; pieces of data associated with each event name. ;; So we have a map where each value is itself a map. (def dev-event-details {:devoxxuk {:URL "" :event-type "Conference" :number-of-attendees 700 :call-for-papers true} :hackthetower {:URL "" :event-type "hackday" :number-of-attendees 60 :call-for-papers false}}) ;; lets call the data structre and see what it evaluates too, it should not be a surprise dev-event-details ;; We can ask for the value of a specific key, and just that value is returned (dev-event-details :devoxxuk) ;; In our example, the value returned from the :devoxxuk key is also a map, ;; so we can ask for a specific part of that map value by again using its key (:URL (dev-event-details :devoxxuk)) ;; Lets define a simple data structure for stocks data ;; This is a vector of maps, as there will be one or more company stocks ;; to track. Each map represents the stock information for a company. (def portfolio [ { :ticker "CRM" :lastTrade 233.12 :open 230.66} { :ticker "AAPL" :lastTrade 203.25 :open 204.50} { :ticker "MSFT" :lastTrade 29.12 :open 29.08 } { :ticker "ORCL" :lastTrade 21.90 :open 21.83 }]) ;; We can get the value of the whole data structure by refering to it by name portfolio ;; As the data structure is a vector (ie. array like) then we can ask for a specific element by its position in the array using the nth function Lets get the map that is the first element ( again as a vector has array - like properties , the first element is referenced by zero ) (nth portfolio 0) The vector has 4 elements , so we can access the last element by referencing the vector using 3 (nth portfolio 3) ;; As portfolio is a collection (list, vector, map, set), also known as a sequence, then we can use a number of functions that provide common ways of getting data from a data structure (first portfolio) (rest portfolio) (last portfolio) ;; To get specific information about the share in our portfolio, we can also use the keywords to get specific information (get (second portfolio) :ticker) ;; => "AAPL" (:ticker (first portfolio)) ;; => "CRM" (map :ticker portfolio) = > ( " CRM " " AAPL " " MSFT " " ORCL " ) ;; return the portfolio in a vector rather than a list using mapv function (mapv :ticker portfolio) = > [ " CRM " " AAPL " " MSFT " " ORCL " ] ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Map reduce (def my-numbers [1 2 3 4 5]) (map even? my-numbers) ;; => (false true false true false) ;; Reduce to see if all the numbers are even, otherwise return false. ;; or is a macro so is quoted so its evaluated only when called by reduce (reduce 'or (map even? my-numbers)) ;; => false ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Map reduce sandwich ;; -is-map-reduce ;; As several functions (defn slice [item] (str "sliced " item)) ;; => #'clojure-through-code.03-using-data-structures/slice ;; => #'clojure-through-code.03-using-data-structures/slice (def prepared-ingredience (map slice ["bread" "cucumber" "pepper" "tomato" "lettuce" "onion"])) ;; => #'clojure-through-code.03-using-data-structures/sandwich (def make-sandwich (reduce str (interpose ", " prepared-ingredience))) (str "I have a tasty sandwich made with " make-sandwich) ;; => "I have a tasty sandwich made with sliced bread, sliced cucumber, sliced pepper, sliced tomato, sliced lettuce, sliced onion" Or as one function (str "I have a tasty sandwich made with " (reduce str (interpose ", " (map #(str "sliced " %) ["bread" "cucumber" "pepper" "tomato" "lettuce" "onion"])))) ;; Or using the threading macro (->> ["bread" "cucumber" "pepper" "tomato" "lettuce" "onion"] (map #(str "sliced " %) ,,,) (interpose ", " ,,,) (reduce str ,,,) (str "I have a tasty sandwich made with " ,,,)) ;; => "I have a tasty sandwich made with sliced bread, sliced cucumber, sliced pepper, sliced tomato, sliced lettuce, sliced onion" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Map and filter ;; A collection of accounts, each account being a map with id and balance values (def accounts [{:id "fred" :balance 10} {:id "betty" :balance 20} {:id "wilma" :balance 5}]) ;; Get the balance for each account and add them together (apply + (map :balance accounts)) ;; We could also use reduce insdead of apply (reduce + (map :balance accounts)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Evaluating things you have defined ;; person ;; developer-events ;; (dev-event-details) (dev-event-details :devoxxuk) (first portfolio) (next portfolio) First and next are termed as sequence functions in Clojure , unlike other lisps , you can use first and next on other data structures too (first person) (rest person) ;;; these functions return the strings as a set of characters, ;;; as characters are the elements of a string returning the first element as a string is easy , simply by rapping the str function around the ( first person ) function (str (first person)) ;;; So how do we return the rest of the string as a string ? (str (rest person)) (map str (rest person)) (str (map str (rest person))) (apply str (rest person)) ;; You can get the value of this map (def luke {:name "Luke Skywarker" :skill "Targeting Swamp Rats"}) (def darth {:name "Darth Vader" :skill "Crank phone calls"}) (def jarjar {:name "JarJar Binks" :skill "Upsetting a generation of fans"}) (get luke :skill) (first luke) ;; Getting the keys or values in a map using keywords ;; When you use a keyword, eg. :name, as the key in a map, then that keyword can be used as a function call on the map to return its associated value. ;; Maps can also act as functions too. (:name luke) (luke :name) ;; There are also functions that will give you all the keys of a map and all the values of that map (keys luke) (vals luke) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Set #{} ;; a unique set of elements (#{:a :b :c} :c) (#{:a :b :c} :z) You can pull out data from a Vector ([1 2 3] 1) ( [ 1 2 3 ] 1 2 ) ; ; wrong number of arguments , vectors behaving as a function expect one parameter ( ( 1 2 3 ) 1 ) ; ; you ca nt treat lists in the same way , there is another approach - assoc ;; and there are lots of functions that work on data structures (def evil-empire #{"Palpatine" "Darth Vader" "Boba Fett" "Darth Tyranus"}) (contains? evil-empire "Darth Vader") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Scope ;; All def names are publicly available via their namespace. ;; As def values are immutable, then keeping things private is of less concern than languages built around Object Oriented design. ;; Private definitions syntax can be used to limit the access to def names to the namespace they are declared in. ;; To limit the scope of a def, add the :private true metadata key value pair. (def ^{:private true} some-var :value) ;; or (def ^:private some-var :value) The second form is syntax sugar for the first one . ;; You can define a macro for def- (defmacro def- [item value] `(def ^{:private true} ~item ~value) ) ;; You can then use this macro as follows: (def- private-definition "This is only accessible in the namespace") ;;;;;;;;;;;;;;;;;;;;;;;;; Be Lazy and get more done Seqs are an interface for logical lists , which can be lazy . " Lazy " means that a seq can define an infinite series , like so : (range 4) (range) ; => (0 1 2 3 4 ...) (an infinite series) ;; So we dont blow up our memory, just get the values we want (take 4 (range)) ; (0 1 2 3) Clojure ( and in general ) tend to evaluate at the last possible moment ; Use cons to add an item to the beginning of a list or vector = > ( 4 1 2 3 ) = > ( 4 1 2 3 ) ; Use conj to add an item to the beginning of a list, ; or the end of a vector = > [ 1 2 3 4 ] = > ( 4 1 2 3 ) ;; Showing how changing data structures does not change the original data structure ;; Lets define a name for a data structure (def name1 [1 2 3 4]) ;; when we evaluate that name we get the original data we set name1 Now we use a function called to adds ( conjoin ) another number to our data structure (conj name1 5) ;; This returns a new value without changing the original data structre name1 ;; We cant change the original data structure, it is immutable. Once it is set it cant be changed. ;; However, if we give a name to the resultl of changing the original data structure, we can refer to that new data structure (def name2(conj name1 5)) Now is the new data structure , but name1 remains unchanged name2 name1 ;; So we cannot change the data structure, however we can achieve something that looks like we have changed it ;; We can re-assign the original name to the result of changing the original data structure (def name2(conj name1 5)) Now name1 and are the same result name2 name1 Analogy ( ) You have the number 2 . If you add 1 to 2 , what value is the number 2 ? The number 2 is still 2 no mater that you add 1 to it , however , you get the value 3 in return ; Use concat to add lists or vectors together (concat [1 2] '(3 4)) ; => (1 2 3 4) ; Use filter, map to interact with collections = > ( 2 3 4 ) = > ( 2 ) ; Use reduce to reduce them (reduce + [1 2 3 4]) = ( + ( + ( + 1 2 ) 3 ) 4 ) = > 10 ; Reduce can take an initial-value argument too (reduce conj [] '(3 2 1)) = ( ( ( [ ] 3 ) 2 ) 1 ) = > [ 3 2 1 ] ;; Playing with data structures ;; Destructuring (let [[a b c & d :as e] [1 2 3 4 5 6 7]] [a b c d e]) (let [[[x1 y1][x2 y2]] [[1 2] [3 4]]] [x1 y1 x2 y2]) ;; with strings (let [[a b & c :as str] "asdjhhfdas"] [a b c str]) ;; with maps (let [{a :a, b :b, c :c, :as m :or {a 2 b 3}} {:a 5 :c 6}] [a b c m]) ;; printing out data structures (def data-structure-vector-of-vectors [[1 2 3] [4 5 6] [7 8 9]]) (defn- map-over-vector-of-vectors [] (map println data-structure-vector-of-vectors)) (comp println map-over-vector-of-vectors) ;; It is often the case that you will want to bind same-named symbols to the map keys. The :keys directive allows you to avoid the redundancy: (def my-map {:fred "freddy" :ethel "ethanol" :lucy "goosey"}) (let [{fred :fred ethel :ethel lucy :lucy} my-map] [fred ethel lucy]) ;; can be written: (let [{:keys [fred ethel lucy]} my-map] [fred ethel lucy]) As of Clojure 1.6 , you can also use prefixed map keys in the map destructuring form : (let [m {:x/a 1, :y/b 2} {:keys [x/a y/b]} m] (+ a b)) ; As shown above, in the case of using prefixed keys, the bound symbol name will be the same as the right-hand side of the prefixed key. You can also use auto-resolved keyword forms in the :keys directive: (let [m {::x 42} {:keys [::x]} m] x) ;; Pretty Printing Clojure data stuctures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Pretty print hash-maps (require '[clojure.pprint]) (clojure.pprint/pprint {:account-id 232443344 :account-name "Jenny Jetpack" :balance 9999 :last-update "2021-12-12" :credit-score :aa}) {:account-id 232443344, :account-name "Jenny Jetpack", :balance 9999, :last-update "2021-12-12", :credit-score :aa} ;; Showing data structures as a table (clojure.pprint/print-table [{:location "Scotland" :total-cases 42826 :total-mortality 9202} {:location "Wales" :total-cases 50876 :total-mortality 1202} {:location "England" :total-cases 5440876 :total-mortality 200202}]) ;; | :location | :total-cases | :total-mortality | ;; |-----------+--------------+------------------| ;; | Scotland | 42826 | 9202 | | Wales | 50876 | 1202 | | England | 5440876 | 200202 |
null
https://raw.githubusercontent.com/practicalli/clojure-through-code/4409a728db84965c2b6abe13d4dc073cbf8f706f/src/clojure_through_code/03-using-data-structures.clj
clojure
Names are of course case sensitive, so Person is not the same as person Here we are defining a name for a vector, which contains numbers, a string and name of another def. You can also dynamically re-define a name to points to a different value the original value that defined my-data remains unchanged (its immutable), so anything using that value remains unaffected. Essentially we are re-mapping my-data to a new value. Lets define a name to point to a list of numbers We are returned that list of numbers when we evaluate the name We can use the cons function to add a number to our list, however because lists are immutable, rather than changing the original list, a new one is returned So if we want to keep on refering to our "changed" list, we need to give it a name As you can see we have not changed the original list The new list does have the change though. so now when we evaluate the original name, we get the updated list Practising with lists Create a simple collection of developer event names first lets use a list of strings at it seems the easiest straight forward Lets create a slightly more involved data structure, holding more data around each developer events. This data structure is just a map, with each key being the unique name of the developer event. The details of each event (the value to go with the event name key) is itself a map as there are several pieces of data associated with each event name. So we have a map where each value is itself a map. lets call the data structre and see what it evaluates too, it should not be a surprise We can ask for the value of a specific key, and just that value is returned In our example, the value returned from the :devoxxuk key is also a map, so we can ask for a specific part of that map value by again using its key Lets define a simple data structure for stocks data This is a vector of maps, as there will be one or more company stocks to track. Each map represents the stock information for a company. We can get the value of the whole data structure by refering to it by name As the data structure is a vector (ie. array like) then we can ask for a specific element by its position in the array using the nth function As portfolio is a collection (list, vector, map, set), also known as a sequence, then we can use a number of functions that provide common ways of getting data from a data structure To get specific information about the share in our portfolio, we can also use the keywords to get specific information => "AAPL" => "CRM" return the portfolio in a vector rather than a list using mapv function Map reduce => (false true false true false) Reduce to see if all the numbers are even, otherwise return false. or is a macro so is quoted so its evaluated only when called by reduce => false Map reduce sandwich -is-map-reduce As several functions => #'clojure-through-code.03-using-data-structures/slice => #'clojure-through-code.03-using-data-structures/slice => #'clojure-through-code.03-using-data-structures/sandwich => "I have a tasty sandwich made with sliced bread, sliced cucumber, sliced pepper, sliced tomato, sliced lettuce, sliced onion" Or using the threading macro => "I have a tasty sandwich made with sliced bread, sliced cucumber, sliced pepper, sliced tomato, sliced lettuce, sliced onion" Map and filter A collection of accounts, each account being a map with id and balance values Get the balance for each account and add them together We could also use reduce insdead of apply Evaluating things you have defined person developer-events (dev-event-details) these functions return the strings as a set of characters, as characters are the elements of a string So how do we return the rest of the string as a string ? You can get the value of this map Getting the keys or values in a map using keywords When you use a keyword, eg. :name, as the key in a map, then that keyword can be used as a function call on the map to return its associated value. Maps can also act as functions too. There are also functions that will give you all the keys of a map and all the values of that map Set #{} a unique set of elements ; wrong number of arguments , vectors behaving as a function expect one parameter ; you ca nt treat lists in the same way , there is another approach - assoc and there are lots of functions that work on data structures Scope All def names are publicly available via their namespace. As def values are immutable, then keeping things private is of less concern than languages built around Object Oriented design. Private definitions syntax can be used to limit the access to def names to the namespace they are declared in. To limit the scope of a def, add the :private true metadata key value pair. or You can define a macro for def- You can then use this macro as follows: => (0 1 2 3 4 ...) (an infinite series) So we dont blow up our memory, just get the values we want (0 1 2 3) Use cons to add an item to the beginning of a list or vector Use conj to add an item to the beginning of a list, or the end of a vector Showing how changing data structures does not change the original data structure Lets define a name for a data structure when we evaluate that name we get the original data we set This returns a new value without changing the original data structre We cant change the original data structure, it is immutable. Once it is set it cant be changed. However, if we give a name to the resultl of changing the original data structure, we can refer to that new data structure So we cannot change the data structure, however we can achieve something that looks like we have changed it We can re-assign the original name to the result of changing the original data structure Use concat to add lists or vectors together => (1 2 3 4) Use filter, map to interact with collections Use reduce to reduce them Reduce can take an initial-value argument too Playing with data structures Destructuring with strings with maps printing out data structures It is often the case that you will want to bind same-named symbols to the map keys. The :keys directive allows you to avoid the redundancy: can be written: As shown above, in the case of using prefixed keys, the bound symbol name will be the same as the right-hand side of the prefixed key. You can also use auto-resolved keyword forms in the :keys directive: Pretty Printing Clojure data stuctures Pretty print hash-maps Showing data structures as a table | :location | :total-cases | :total-mortality | |-----------+--------------+------------------| | Scotland | 42826 | 9202 |
Using Clojure data structures (ns clojure-through-code.03-using-data-structures) Defining things is easy in Clojure Defining things is as simple as giving a name to a value , of course in Clojure the evaluation of a function is also a value . (def person "Jane Doe") (def Person "James Doh") Clojure uses dynamic typing , this means its trivial to mix and match different kinds of data . (def my-data [1 2 3 "frog" person]) my-data (def my-data [1 2 3 4 5 "frog" person]) (def my-list '(1 2 3)) my-list (def my-list-updated (cons 4 my-list)) my-list my-list-updated As names in Clojure are dynamic , we can of course point the original name to the new list (def my-list (cons 5 my-list)) my-list (def developer-events-strings '("Devoxx UK" "Devoxx France" "Devoxx" "Hack the Tower")) > Remember , in Clojure the first element of a list is treated as a function call , so we have used the quote ' character to tell Cloojure to also treat the first element as data . We could of course have used the list function to define our list ` ( def developer - events - strings2 ( list " Devoxx UK " " Devoxx France " " Devoxx " " Hack the Tower " ) ) ` developer-events-strings We can get just the first element in our collection of developer events (first developer-events-strings) using a Clojure Vector data structure seems a little more Clojurey , especially when the vector contains keywords . Think of a Vector as an Array , although in Clojure it is again immutable in the same way a list is . (def developer-events-vector [:devoxxuk :devoxxfr :devoxx :hackthetower] ) (def dev-event-details {:devoxxuk {:URL "" :event-type "Conference" :number-of-attendees 700 :call-for-papers true} :hackthetower {:URL "" :event-type "hackday" :number-of-attendees 60 :call-for-papers false}}) dev-event-details (dev-event-details :devoxxuk) (:URL (dev-event-details :devoxxuk)) (def portfolio [ { :ticker "CRM" :lastTrade 233.12 :open 230.66} { :ticker "AAPL" :lastTrade 203.25 :open 204.50} { :ticker "MSFT" :lastTrade 29.12 :open 29.08 } { :ticker "ORCL" :lastTrade 21.90 :open 21.83 }]) portfolio Lets get the map that is the first element ( again as a vector has array - like properties , the first element is referenced by zero ) (nth portfolio 0) The vector has 4 elements , so we can access the last element by referencing the vector using 3 (nth portfolio 3) (first portfolio) (rest portfolio) (last portfolio) (get (second portfolio) :ticker) (:ticker (first portfolio)) (map :ticker portfolio) = > ( " CRM " " AAPL " " MSFT " " ORCL " ) (mapv :ticker portfolio) = > [ " CRM " " AAPL " " MSFT " " ORCL " ] (def my-numbers [1 2 3 4 5]) (map even? my-numbers) (reduce 'or (map even? my-numbers)) (defn slice [item] (str "sliced " item)) (def prepared-ingredience (map slice ["bread" "cucumber" "pepper" "tomato" "lettuce" "onion"])) (def make-sandwich (reduce str (interpose ", " prepared-ingredience))) (str "I have a tasty sandwich made with " make-sandwich) Or as one function (str "I have a tasty sandwich made with " (reduce str (interpose ", " (map #(str "sliced " %) ["bread" "cucumber" "pepper" "tomato" "lettuce" "onion"])))) (->> ["bread" "cucumber" "pepper" "tomato" "lettuce" "onion"] (map #(str "sliced " %) ,,,) (interpose ", " ,,,) (reduce str ,,,) (str "I have a tasty sandwich made with " ,,,)) (def accounts [{:id "fred" :balance 10} {:id "betty" :balance 20} {:id "wilma" :balance 5}]) (apply + (map :balance accounts)) (reduce + (map :balance accounts)) (dev-event-details :devoxxuk) (first portfolio) (next portfolio) First and next are termed as sequence functions in Clojure , unlike other lisps , you can use first and next on other data structures too (first person) (rest person) returning the first element as a string is easy , simply by rapping the str function around the ( first person ) function (str (first person)) (str (rest person)) (map str (rest person)) (str (map str (rest person))) (apply str (rest person)) (def luke {:name "Luke Skywarker" :skill "Targeting Swamp Rats"}) (def darth {:name "Darth Vader" :skill "Crank phone calls"}) (def jarjar {:name "JarJar Binks" :skill "Upsetting a generation of fans"}) (get luke :skill) (first luke) (:name luke) (luke :name) (keys luke) (vals luke) (#{:a :b :c} :c) (#{:a :b :c} :z) You can pull out data from a Vector ([1 2 3] 1) (def evil-empire #{"Palpatine" "Darth Vader" "Boba Fett" "Darth Tyranus"}) (contains? evil-empire "Darth Vader") (def ^{:private true} some-var :value) (def ^:private some-var :value) The second form is syntax sugar for the first one . (defmacro def- [item value] `(def ^{:private true} ~item ~value) ) (def- private-definition "This is only accessible in the namespace") Be Lazy and get more done Seqs are an interface for logical lists , which can be lazy . " Lazy " means that a seq can define an infinite series , like so : (range 4) Clojure ( and in general ) tend to evaluate at the last possible moment = > ( 4 1 2 3 ) = > ( 4 1 2 3 ) = > [ 1 2 3 4 ] = > ( 4 1 2 3 ) (def name1 [1 2 3 4]) name1 Now we use a function called to adds ( conjoin ) another number to our data structure (conj name1 5) name1 (def name2(conj name1 5)) Now is the new data structure , but name1 remains unchanged name2 name1 (def name2(conj name1 5)) Now name1 and are the same result name2 name1 Analogy ( ) You have the number 2 . If you add 1 to 2 , what value is the number 2 ? The number 2 is still 2 no mater that you add 1 to it , however , you get the value 3 in return = > ( 2 3 4 ) = > ( 2 ) (reduce + [1 2 3 4]) = ( + ( + ( + 1 2 ) 3 ) 4 ) = > 10 (reduce conj [] '(3 2 1)) = ( ( ( [ ] 3 ) 2 ) 1 ) = > [ 3 2 1 ] (let [[a b c & d :as e] [1 2 3 4 5 6 7]] [a b c d e]) (let [[[x1 y1][x2 y2]] [[1 2] [3 4]]] [x1 y1 x2 y2]) (let [[a b & c :as str] "asdjhhfdas"] [a b c str]) (let [{a :a, b :b, c :c, :as m :or {a 2 b 3}} {:a 5 :c 6}] [a b c m]) (def data-structure-vector-of-vectors [[1 2 3] [4 5 6] [7 8 9]]) (defn- map-over-vector-of-vectors [] (map println data-structure-vector-of-vectors)) (comp println map-over-vector-of-vectors) (def my-map {:fred "freddy" :ethel "ethanol" :lucy "goosey"}) (let [{fred :fred ethel :ethel lucy :lucy} my-map] [fred ethel lucy]) (let [{:keys [fred ethel lucy]} my-map] [fred ethel lucy]) As of Clojure 1.6 , you can also use prefixed map keys in the map destructuring form : (let [m {:x/a 1, :y/b 2} {:keys [x/a y/b]} m] (+ a b)) (let [m {::x 42} {:keys [::x]} m] x) (require '[clojure.pprint]) (clojure.pprint/pprint {:account-id 232443344 :account-name "Jenny Jetpack" :balance 9999 :last-update "2021-12-12" :credit-score :aa}) {:account-id 232443344, :account-name "Jenny Jetpack", :balance 9999, :last-update "2021-12-12", :credit-score :aa} (clojure.pprint/print-table [{:location "Scotland" :total-cases 42826 :total-mortality 9202} {:location "Wales" :total-cases 50876 :total-mortality 1202} {:location "England" :total-cases 5440876 :total-mortality 200202}]) | Wales | 50876 | 1202 | | England | 5440876 | 200202 |
659e0369c083d1c5c8e6bbabd0e434a3d7d0316f6a997ad0e481c27f1428b7c9
spawnfest/eep49ers
ssl_pem_cache.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 20016 - 2018 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% %%---------------------------------------------------------------------- %% Purpose: Manages ssl sessions and trusted certifacates %%---------------------------------------------------------------------- -module(ssl_pem_cache). -behaviour(gen_server). Internal application API -export([start_link/1, start_link_dist/1, name/1, insert/2, clear/0]). % Spawn export -export([init_pem_cache_validator/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("ssl_handshake.hrl"). -include("ssl_internal.hrl"). -include_lib("kernel/include/file.hrl"). -record(state, { pem_cache, last_pem_check :: integer(), clear :: integer() }). -define(CLEAR_PEM_CACHE, 120000). -define(DEFAULT_MAX_SESSION_CACHE, 1000). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- -spec name(normal | dist) -> atom(). %% %% Description: Returns the registered name of the ssl cache process %% in the operation modes 'normal' and 'dist'. %%-------------------------------------------------------------------- name(normal) -> ?MODULE; name(dist) -> list_to_atom(atom_to_list(?MODULE) ++ "_dist"). %%-------------------------------------------------------------------- -spec start_link(list()) -> {ok, pid()} | ignore | {error, term()}. %% %% Description: Starts the ssl pem cache handler %%-------------------------------------------------------------------- start_link(_) -> CacheName = name(normal), gen_server:start_link({local, CacheName}, ?MODULE, [CacheName], []). %%-------------------------------------------------------------------- -spec start_link_dist(list()) -> {ok, pid()} | ignore | {error, term()}. %% %% Description: Starts a special instance of the ssl manager to be used by the erlang distribution . Note disables soft upgrade ! %%-------------------------------------------------------------------- start_link_dist(_) -> DistCacheName = name(dist), gen_server:start_link({local, DistCacheName}, ?MODULE, [DistCacheName], []). %%-------------------------------------------------------------------- -spec insert(binary(), term()) -> ok | {error, reason()}. %% %% Description: Cache a pem file and return its content. %%-------------------------------------------------------------------- insert(File, Content) -> case bypass_cache() of true -> ok; false -> cast({cache_pem, File, Content}), ok end. %%-------------------------------------------------------------------- -spec clear() -> ok. %% %% Description: Clear the PEM cache %%-------------------------------------------------------------------- clear() -> %% Not supported for distribution at the moement, should it be? put(ssl_pem_cache, name(normal)), call(unconditionally_clear_pem_cache). -spec invalidate_pem(File::binary()) -> ok. invalidate_pem(File) -> cast({invalidate_pem, File}). %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- -spec init(list()) -> {ok, #state{}}. %% Possible return values not used now. %% | {ok, #state{}, timeout()} | ignore | {stop, term()}. %% %% Description: Initiates the server %%-------------------------------------------------------------------- init([Name]) -> put(ssl_pem_cache, Name), process_flag(trap_exit, true), PemCache = ssl_pkix_db:create_pem_cache(Name), Interval = pem_check_interval(), erlang:send_after(Interval, self(), clear_pem_cache), erlang:system_time(second), {ok, #state{pem_cache = PemCache, last_pem_check = erlang:convert_time_unit(os:system_time(), native, second), clear = Interval }}. %%-------------------------------------------------------------------- -spec handle_call(msg(), from(), #state{}) -> {reply, reply(), #state{}}. %% Possible return values not used now. %% {reply, reply(), #state{}, timeout()} | { noreply , # state { } } | { noreply , # state { } , timeout ( ) } | %% {stop, reason(), reply(), #state{}} | %% {stop, reason(), #state{}}. %% %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call({unconditionally_clear_pem_cache, _},_, #state{pem_cache = PemCache} = State) -> ssl_pkix_db:clear(PemCache), Result = ssl_manager:refresh_trusted_db(ssl_manager_type()), {reply, Result, State}. %%-------------------------------------------------------------------- -spec handle_cast(msg(), #state{}) -> {noreply, #state{}}. %% Possible return values not used now. | { noreply , # state { } , timeout ( ) } | %% {stop, reason(), #state{}}. %% %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast({cache_pem, File, Content}, #state{pem_cache = Db} = State) -> ssl_pkix_db:insert(File, Content, Db), {noreply, State}; handle_cast({invalidate_pem, File}, #state{pem_cache = Db} = State) -> ssl_pkix_db:remove(File, Db), ssl_manager:refresh_trusted_db(ssl_manager_type(), File), {noreply, State}. %%-------------------------------------------------------------------- -spec handle_info(msg(), #state{}) -> {noreply, #state{}}. %% Possible return values not used now. %% |{noreply, #state{}, timeout()} | %% {stop, reason(), #state{}}. %% %% Description: Handling all non call/cast messages %%------------------------------------------------------------------- handle_info(clear_pem_cache, #state{pem_cache = PemCache, clear = Interval, last_pem_check = CheckPoint} = State) -> NewCheckPoint = erlang:convert_time_unit(os:system_time(), native, second), start_pem_cache_validator(PemCache, CheckPoint), erlang:send_after(Interval, self(), clear_pem_cache), {noreply, State#state{last_pem_check = NewCheckPoint}}; handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- -spec terminate(reason(), #state{}) -> ok. %% %% Description: This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, #state{}) -> ok. %%-------------------------------------------------------------------- -spec code_change(term(), #state{}, list()) -> {ok, #state{}}. %% %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- call(Msg) -> gen_server:call(get(ssl_pem_cache), {Msg, self()}, infinity). cast(Msg) -> gen_server:cast(get(ssl_pem_cache), Msg). start_pem_cache_validator(PemCache, CheckPoint) -> spawn_link(?MODULE, init_pem_cache_validator, [[get(ssl_pem_cache), PemCache, CheckPoint]]). init_pem_cache_validator([CacheName, PemCache, CheckPoint]) -> put(ssl_pem_cache, CacheName), ssl_pkix_db:foldl(fun pem_cache_validate/2, CheckPoint, PemCache). pem_cache_validate({File, _}, CheckPoint) -> case file:read_file_info(File, [{time, posix}]) of {ok, #file_info{mtime = Time}} when Time < CheckPoint -> ok; _ -> invalidate_pem(File) end, CheckPoint. pem_check_interval() -> case application:get_env(ssl, ssl_pem_cache_clean) of {ok, Interval} when is_integer(Interval) -> Interval; _ -> ?CLEAR_PEM_CACHE end. bypass_cache() -> case application:get_env(ssl, bypass_pem_cache) of {ok, Bool} when is_boolean(Bool) -> Bool; _ -> false end. ssl_manager_type() -> case get(ssl_pem_cache) of ?MODULE -> normal; _ -> dist end.
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/ssl/src/ssl_pem_cache.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% ---------------------------------------------------------------------- Purpose: Manages ssl sessions and trusted certifacates ---------------------------------------------------------------------- Spawn export gen_server callbacks ==================================================================== API ==================================================================== -------------------------------------------------------------------- Description: Returns the registered name of the ssl cache process in the operation modes 'normal' and 'dist'. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Starts the ssl pem cache handler -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Starts a special instance of the ssl manager to -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Cache a pem file and return its content. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Clear the PEM cache -------------------------------------------------------------------- Not supported for distribution at the moement, should it be? ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Possible return values not used now. | {ok, #state{}, timeout()} | ignore | {stop, term()}. Description: Initiates the server -------------------------------------------------------------------- -------------------------------------------------------------------- Possible return values not used now. {reply, reply(), #state{}, timeout()} | {stop, reason(), reply(), #state{}} | {stop, reason(), #state{}}. Description: Handling call messages -------------------------------------------------------------------- -------------------------------------------------------------------- Possible return values not used now. {stop, reason(), #state{}}. Description: Handling cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- Possible return values not used now. |{noreply, #state{}, timeout()} | {stop, reason(), #state{}}. Description: Handling all non call/cast messages ------------------------------------------------------------------- -------------------------------------------------------------------- Description: This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Convert process state when code is changed -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright Ericsson AB 20016 - 2018 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(ssl_pem_cache). -behaviour(gen_server). Internal application API -export([start_link/1, start_link_dist/1, name/1, insert/2, clear/0]). -export([init_pem_cache_validator/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("ssl_handshake.hrl"). -include("ssl_internal.hrl"). -include_lib("kernel/include/file.hrl"). -record(state, { pem_cache, last_pem_check :: integer(), clear :: integer() }). -define(CLEAR_PEM_CACHE, 120000). -define(DEFAULT_MAX_SESSION_CACHE, 1000). -spec name(normal | dist) -> atom(). name(normal) -> ?MODULE; name(dist) -> list_to_atom(atom_to_list(?MODULE) ++ "_dist"). -spec start_link(list()) -> {ok, pid()} | ignore | {error, term()}. start_link(_) -> CacheName = name(normal), gen_server:start_link({local, CacheName}, ?MODULE, [CacheName], []). -spec start_link_dist(list()) -> {ok, pid()} | ignore | {error, term()}. be used by the erlang distribution . Note disables soft upgrade ! start_link_dist(_) -> DistCacheName = name(dist), gen_server:start_link({local, DistCacheName}, ?MODULE, [DistCacheName], []). -spec insert(binary(), term()) -> ok | {error, reason()}. insert(File, Content) -> case bypass_cache() of true -> ok; false -> cast({cache_pem, File, Content}), ok end. -spec clear() -> ok. clear() -> put(ssl_pem_cache, name(normal)), call(unconditionally_clear_pem_cache). -spec invalidate_pem(File::binary()) -> ok. invalidate_pem(File) -> cast({invalidate_pem, File}). -spec init(list()) -> {ok, #state{}}. init([Name]) -> put(ssl_pem_cache, Name), process_flag(trap_exit, true), PemCache = ssl_pkix_db:create_pem_cache(Name), Interval = pem_check_interval(), erlang:send_after(Interval, self(), clear_pem_cache), erlang:system_time(second), {ok, #state{pem_cache = PemCache, last_pem_check = erlang:convert_time_unit(os:system_time(), native, second), clear = Interval }}. -spec handle_call(msg(), from(), #state{}) -> {reply, reply(), #state{}}. { noreply , # state { } } | { noreply , # state { } , timeout ( ) } | handle_call({unconditionally_clear_pem_cache, _},_, #state{pem_cache = PemCache} = State) -> ssl_pkix_db:clear(PemCache), Result = ssl_manager:refresh_trusted_db(ssl_manager_type()), {reply, Result, State}. -spec handle_cast(msg(), #state{}) -> {noreply, #state{}}. | { noreply , # state { } , timeout ( ) } | handle_cast({cache_pem, File, Content}, #state{pem_cache = Db} = State) -> ssl_pkix_db:insert(File, Content, Db), {noreply, State}; handle_cast({invalidate_pem, File}, #state{pem_cache = Db} = State) -> ssl_pkix_db:remove(File, Db), ssl_manager:refresh_trusted_db(ssl_manager_type(), File), {noreply, State}. -spec handle_info(msg(), #state{}) -> {noreply, #state{}}. handle_info(clear_pem_cache, #state{pem_cache = PemCache, clear = Interval, last_pem_check = CheckPoint} = State) -> NewCheckPoint = erlang:convert_time_unit(os:system_time(), native, second), start_pem_cache_validator(PemCache, CheckPoint), erlang:send_after(Interval, self(), clear_pem_cache), {noreply, State#state{last_pem_check = NewCheckPoint}}; handle_info(_Info, State) -> {noreply, State}. -spec terminate(reason(), #state{}) -> ok. terminate(_Reason, #state{}) -> ok. -spec code_change(term(), #state{}, list()) -> {ok, #state{}}. code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions call(Msg) -> gen_server:call(get(ssl_pem_cache), {Msg, self()}, infinity). cast(Msg) -> gen_server:cast(get(ssl_pem_cache), Msg). start_pem_cache_validator(PemCache, CheckPoint) -> spawn_link(?MODULE, init_pem_cache_validator, [[get(ssl_pem_cache), PemCache, CheckPoint]]). init_pem_cache_validator([CacheName, PemCache, CheckPoint]) -> put(ssl_pem_cache, CacheName), ssl_pkix_db:foldl(fun pem_cache_validate/2, CheckPoint, PemCache). pem_cache_validate({File, _}, CheckPoint) -> case file:read_file_info(File, [{time, posix}]) of {ok, #file_info{mtime = Time}} when Time < CheckPoint -> ok; _ -> invalidate_pem(File) end, CheckPoint. pem_check_interval() -> case application:get_env(ssl, ssl_pem_cache_clean) of {ok, Interval} when is_integer(Interval) -> Interval; _ -> ?CLEAR_PEM_CACHE end. bypass_cache() -> case application:get_env(ssl, bypass_pem_cache) of {ok, Bool} when is_boolean(Bool) -> Bool; _ -> false end. ssl_manager_type() -> case get(ssl_pem_cache) of ?MODULE -> normal; _ -> dist end.
47b5a22606c8e19e83669eaa8c32b78e3d8cb9e9401c354495347fb5f3a49ad4
borkdude/speculative
specs.cljc
(ns speculative.specs "Primitive specs" (:refer-clojure :exclude [seqable? reduceable? regexp?]) (:require [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [clojure.string :as str] #?(:cljs [goog.string]))) #?(:cljs (def ^:private before-1_10_439? (and *clojurescript-version* (pos? (goog.string/compareVersions "1.10.439" *clojurescript-version*))))) #?(:cljs (if before-1_10_439? (defn seqable? [v] (or (nil? v) (clojure.core/seqable? v))) (def seqable? clojure.core/seqable?)) :clj (def seqable? clojure.core/seqable?)) (s/def ::seqable (s/with-gen seqable? (fn [] (s/gen clojure.core/seqable?)))) (defn reducible? [x] #?(:clj (instance? clojure.lang.IReduceInit x) :cljs (clojure.core/reduceable? x))) #?(:clj (defn- iterable? [x] (instance? java.lang.Iterable x))) (s/def ::associative associative?) ;; workaround for -1966 (s/def ::any (s/with-gen (s/conformer #(if (s/invalid? %) ::invalid %)) #(s/gen any?))) (s/def ::boolean boolean?) (s/def ::counted (s/with-gen counted? #(s/gen (s/spec seqable?)))) (s/def ::ifn ifn?) (s/def ::predicate (s/with-gen ::ifn (fn [] (gen/bind (s/gen ::boolean) (fn [b] (gen/return (fn [x] b))))))) (s/def ::int int?) (s/def ::nat-int nat-int?) (s/def ::pos-int pos-int?) (s/def ::iterable iterable?) (s/def ::map map?) #?(:clj (s/def ::java-map (s/with-gen #(instance? java.util.Map %) (fn [] (gen/fmap #(java.util.HashMap. %) (s/gen ::map)))))) (s/def ::map+ #?(:cljs ::map :clj (s/or :map ::map :java-map ::java-map))) (s/def ::map-entry (s/with-gen map-entry? (fn [] (gen/fmap first (s/gen (s/and ::map seq)))))) (s/def ::pair (s/tuple ::any ::any)) (s/def ::set set?) (s/def ::nil nil?) (s/def ::number number?) (s/def ::reducible reducible?) (s/def ::seq seq?) (s/def ::non-empty-seq (s/and ::seq not-empty)) (s/def ::vector vector?) (s/def ::sequential sequential?) (s/def ::some some?) (s/def ::string string?) (s/def ::keyword keyword?) #?(:clj (s/def ::char-sequence (s/with-gen #(instance? java.lang.CharSequence %) (fn [] (gen/one-of (map #(gen/fmap % (s/gen ::string)) [#(StringBuffer. %) #(StringBuilder. %) #(java.nio.CharBuffer/wrap %) #(String. %)])))))) (s/def ::string+ #?(:cljs ::string :clj ::char-sequence)) (defn seqable-of "every is not designed to deal with seqable?, this is a way around it" [spec] (s/with-gen (s/and seqable? (s/or :empty empty? :seq (s/and (s/conformer seq) (s/every spec)))) ;; avoid generation of strings and vectors (those are interpreted as pairs when using conj with maps #(s/gen (s/nilable (s/every spec :kind seq?))))) (s/def ::seqable-of-map-entry (seqable-of ::map-entry)) (s/def ::seqable-of-nilable-string (seqable-of (s/nilable ::string))) (s/def ::reducible-coll (s/with-gen (s/or :seqable ::seqable :reducible (s/nilable ::reducible) :iterable (s/nilable ::iterable)) #(s/gen ::seqable))) (s/def ::coll coll?) (s/def ::conjable (s/nilable ::coll)) (s/def ::java-coll (s/with-gen #(instance? java.util.Collection %) (fn [] (gen/fmap #(java.util.ArrayList. %) (s/gen vector?))))) (s/def ::transducer (s/with-gen ::ifn (fn [] (gen/return (map identity))))) (s/def ::seqable-or-transducer (s/or :seqable ::seqable :transducer ::transducer)) ;;;; Atoms (s/def ::atom (s/with-gen (fn [a] #?(:clj (instance? clojure.lang.IAtom a) :cljs (satisfies? IAtom a))) #(gen/fmap (fn [any] (atom any)) (s/gen ::any)))) (s/def :speculative.atom.options/validator (s/with-gen ::predicate (fn [] (gen/return (fn [_] true))))) (s/def :speculative.atom.options/meta ::map) (s/def ::atom.options (s/keys* :opt-un [:speculative.atom.options/validator :speculative.atom.options/meta])) ;;;; End Atoms Regex stuff #?(:clj (defn regex? [r] (instance? java.util.regex.Pattern r)) :cljs (def regex? cljs.core/regexp?)) (s/def ::regex.gen.sub-pattern (s/cat :pattern (s/alt :chars (s/+ #{\a \b}) :group (s/cat :open-paren #{\(} :inner-pattern ::regex.gen.sub-pattern :closing-paren #{\)})) :maybe (s/? #{\?}))) (s/def ::regex.gen.pattern (s/coll-of ::regex.gen.sub-pattern :gen-max 10)) (defn regex-gen [] (gen/fmap (fn [patterns] (let [s (reduce #(str %1 (str/join %2)) "" patterns)] (re-pattern s))) (s/gen ::regex.gen.pattern))) #?(:clj (defn lazy-string-from-regex "Defers loading test.check" [re] (require '[com.gfredericks.test.chuck.generators]) ((resolve 'com.gfredericks.test.chuck.generators/string-from-regex) re))) (defn regex-with-string-gen [] "Returns generator that generates a regex and a string that will match 90% of the time on CLJ and will maybe match 10% of the time on CLJ. On CLJS it will maybe match 100% of the time, since the string from regex generator isn't used there." (gen/bind (regex-gen) (fn [re] (gen/tuple (gen/return re) (gen/frequency [#?(:clj [9 (lazy-string-from-regex re)]) [#?(:clj 1 :cljs 10) (gen/fmap str/join (s/gen (s/* #{\a \b})))]]))))) #?(:clj (do (defn regex-with-matching-string-gen [] (gen/bind (regex-gen) (fn [re] (gen/tuple (gen/return re) (lazy-string-from-regex re))))) (defn matching-matcher-gen [] (gen/fmap (fn [[r s]] (re-matcher r s)) (regex-with-matching-string-gen))) (defn matcher-gen [] (gen/fmap (fn [[r strs]] (re-matcher r (str/join strs))) (regex-with-string-gen))) (s/def ::matcher (s/with-gen #(instance? java.util.regex.Matcher %) (fn [] (matcher-gen)))) ;; test matcher-gen: (comment (re-find (gen/generate matcher-gen))))) (s/def ::regex+string-args (s/with-gen (s/cat :re ::regex :s ::string+) regex-with-string-gen)) (s/def ::regex (s/with-gen regex? (fn [] (regex-gen)))) (s/def ::regex-match (s/nilable (s/or :string ::string :seqable ::seqable-of-nilable-string))) (s/def ::regex-matches (seqable-of ::regex-match)) ;;;; End regex stuff (s/def ::sequential-of-non-sequential (s/every (complement sequential?) :kind sequential?)) (s/def ::non-empty-seqable (s/and ::seqable not-empty)) (s/def ::array (s/with-gen #?(:clj #(-> % .getClass .isArray) :cljs array?) #(gen/one-of [(gen/fmap int-array (gen/vector (gen/int))) (gen/fmap double-array (gen/vector (gen/double))) #?(:clj (gen/fmap char-array (gen/string))) (gen/fmap object-array (gen/vector (gen/any)))]))) (s/def ::indexed indexed?) (s/def ::nthable (s/with-gen (s/nilable (s/or :index ::indexed :str #?(:clj ::char-sequence :cljs ::string) :array ::array #?@(:clj [:random-access #(instance? java.util.RandomAccess %)]) #?@(:clj [:matcher ::matcher]) :map-entry ::map-entry :sequential ::sequential)) #(gen/not-empty (gen/one-of [(s/gen ::indexed) #?(:clj (s/gen ::char-sequence) :cljs (gen/string)) (s/gen ::array) (s/gen ::map-entry) (s/gen ::sequential)])))) (s/def ::stack (s/with-gen #?(:cljs #(satisfies? IStack %) :clj #(instance? clojure.lang.IPersistentStack %)) (fn [] (s/gen (s/or :vector vector? :list list?))))) (s/def ::list list?) (defn named? [x] #?(:clj (instance? clojure.lang.Named x) :cljs (satisfies? INamed x))) (s/def ::symbol symbol?) (s/def ::named (s/with-gen named? (fn [] (s/gen (s/or :symbol ::symbol :keyword ::keyword))))) ;;;; Scratch (comment (require '[clojure.spec.test.alpha :as stest]) (stest/instrument) (stest/unstrument))
null
https://raw.githubusercontent.com/borkdude/speculative/4e773794a4065a84bdadd997516e52c76ab51b1f/src/speculative/specs.cljc
clojure
workaround for -1966 avoid generation of strings and vectors (those are interpreted as pairs when using conj with maps Atoms End Atoms test matcher-gen: End regex stuff Scratch
(ns speculative.specs "Primitive specs" (:refer-clojure :exclude [seqable? reduceable? regexp?]) (:require [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [clojure.string :as str] #?(:cljs [goog.string]))) #?(:cljs (def ^:private before-1_10_439? (and *clojurescript-version* (pos? (goog.string/compareVersions "1.10.439" *clojurescript-version*))))) #?(:cljs (if before-1_10_439? (defn seqable? [v] (or (nil? v) (clojure.core/seqable? v))) (def seqable? clojure.core/seqable?)) :clj (def seqable? clojure.core/seqable?)) (s/def ::seqable (s/with-gen seqable? (fn [] (s/gen clojure.core/seqable?)))) (defn reducible? [x] #?(:clj (instance? clojure.lang.IReduceInit x) :cljs (clojure.core/reduceable? x))) #?(:clj (defn- iterable? [x] (instance? java.lang.Iterable x))) (s/def ::associative associative?) (s/def ::any (s/with-gen (s/conformer #(if (s/invalid? %) ::invalid %)) #(s/gen any?))) (s/def ::boolean boolean?) (s/def ::counted (s/with-gen counted? #(s/gen (s/spec seqable?)))) (s/def ::ifn ifn?) (s/def ::predicate (s/with-gen ::ifn (fn [] (gen/bind (s/gen ::boolean) (fn [b] (gen/return (fn [x] b))))))) (s/def ::int int?) (s/def ::nat-int nat-int?) (s/def ::pos-int pos-int?) (s/def ::iterable iterable?) (s/def ::map map?) #?(:clj (s/def ::java-map (s/with-gen #(instance? java.util.Map %) (fn [] (gen/fmap #(java.util.HashMap. %) (s/gen ::map)))))) (s/def ::map+ #?(:cljs ::map :clj (s/or :map ::map :java-map ::java-map))) (s/def ::map-entry (s/with-gen map-entry? (fn [] (gen/fmap first (s/gen (s/and ::map seq)))))) (s/def ::pair (s/tuple ::any ::any)) (s/def ::set set?) (s/def ::nil nil?) (s/def ::number number?) (s/def ::reducible reducible?) (s/def ::seq seq?) (s/def ::non-empty-seq (s/and ::seq not-empty)) (s/def ::vector vector?) (s/def ::sequential sequential?) (s/def ::some some?) (s/def ::string string?) (s/def ::keyword keyword?) #?(:clj (s/def ::char-sequence (s/with-gen #(instance? java.lang.CharSequence %) (fn [] (gen/one-of (map #(gen/fmap % (s/gen ::string)) [#(StringBuffer. %) #(StringBuilder. %) #(java.nio.CharBuffer/wrap %) #(String. %)])))))) (s/def ::string+ #?(:cljs ::string :clj ::char-sequence)) (defn seqable-of "every is not designed to deal with seqable?, this is a way around it" [spec] (s/with-gen (s/and seqable? (s/or :empty empty? :seq (s/and (s/conformer seq) (s/every spec)))) #(s/gen (s/nilable (s/every spec :kind seq?))))) (s/def ::seqable-of-map-entry (seqable-of ::map-entry)) (s/def ::seqable-of-nilable-string (seqable-of (s/nilable ::string))) (s/def ::reducible-coll (s/with-gen (s/or :seqable ::seqable :reducible (s/nilable ::reducible) :iterable (s/nilable ::iterable)) #(s/gen ::seqable))) (s/def ::coll coll?) (s/def ::conjable (s/nilable ::coll)) (s/def ::java-coll (s/with-gen #(instance? java.util.Collection %) (fn [] (gen/fmap #(java.util.ArrayList. %) (s/gen vector?))))) (s/def ::transducer (s/with-gen ::ifn (fn [] (gen/return (map identity))))) (s/def ::seqable-or-transducer (s/or :seqable ::seqable :transducer ::transducer)) (s/def ::atom (s/with-gen (fn [a] #?(:clj (instance? clojure.lang.IAtom a) :cljs (satisfies? IAtom a))) #(gen/fmap (fn [any] (atom any)) (s/gen ::any)))) (s/def :speculative.atom.options/validator (s/with-gen ::predicate (fn [] (gen/return (fn [_] true))))) (s/def :speculative.atom.options/meta ::map) (s/def ::atom.options (s/keys* :opt-un [:speculative.atom.options/validator :speculative.atom.options/meta])) Regex stuff #?(:clj (defn regex? [r] (instance? java.util.regex.Pattern r)) :cljs (def regex? cljs.core/regexp?)) (s/def ::regex.gen.sub-pattern (s/cat :pattern (s/alt :chars (s/+ #{\a \b}) :group (s/cat :open-paren #{\(} :inner-pattern ::regex.gen.sub-pattern :closing-paren #{\)})) :maybe (s/? #{\?}))) (s/def ::regex.gen.pattern (s/coll-of ::regex.gen.sub-pattern :gen-max 10)) (defn regex-gen [] (gen/fmap (fn [patterns] (let [s (reduce #(str %1 (str/join %2)) "" patterns)] (re-pattern s))) (s/gen ::regex.gen.pattern))) #?(:clj (defn lazy-string-from-regex "Defers loading test.check" [re] (require '[com.gfredericks.test.chuck.generators]) ((resolve 'com.gfredericks.test.chuck.generators/string-from-regex) re))) (defn regex-with-string-gen [] "Returns generator that generates a regex and a string that will match 90% of the time on CLJ and will maybe match 10% of the time on CLJ. On CLJS it will maybe match 100% of the time, since the string from regex generator isn't used there." (gen/bind (regex-gen) (fn [re] (gen/tuple (gen/return re) (gen/frequency [#?(:clj [9 (lazy-string-from-regex re)]) [#?(:clj 1 :cljs 10) (gen/fmap str/join (s/gen (s/* #{\a \b})))]]))))) #?(:clj (do (defn regex-with-matching-string-gen [] (gen/bind (regex-gen) (fn [re] (gen/tuple (gen/return re) (lazy-string-from-regex re))))) (defn matching-matcher-gen [] (gen/fmap (fn [[r s]] (re-matcher r s)) (regex-with-matching-string-gen))) (defn matcher-gen [] (gen/fmap (fn [[r strs]] (re-matcher r (str/join strs))) (regex-with-string-gen))) (s/def ::matcher (s/with-gen #(instance? java.util.regex.Matcher %) (fn [] (matcher-gen)))) (comment (re-find (gen/generate matcher-gen))))) (s/def ::regex+string-args (s/with-gen (s/cat :re ::regex :s ::string+) regex-with-string-gen)) (s/def ::regex (s/with-gen regex? (fn [] (regex-gen)))) (s/def ::regex-match (s/nilable (s/or :string ::string :seqable ::seqable-of-nilable-string))) (s/def ::regex-matches (seqable-of ::regex-match)) (s/def ::sequential-of-non-sequential (s/every (complement sequential?) :kind sequential?)) (s/def ::non-empty-seqable (s/and ::seqable not-empty)) (s/def ::array (s/with-gen #?(:clj #(-> % .getClass .isArray) :cljs array?) #(gen/one-of [(gen/fmap int-array (gen/vector (gen/int))) (gen/fmap double-array (gen/vector (gen/double))) #?(:clj (gen/fmap char-array (gen/string))) (gen/fmap object-array (gen/vector (gen/any)))]))) (s/def ::indexed indexed?) (s/def ::nthable (s/with-gen (s/nilable (s/or :index ::indexed :str #?(:clj ::char-sequence :cljs ::string) :array ::array #?@(:clj [:random-access #(instance? java.util.RandomAccess %)]) #?@(:clj [:matcher ::matcher]) :map-entry ::map-entry :sequential ::sequential)) #(gen/not-empty (gen/one-of [(s/gen ::indexed) #?(:clj (s/gen ::char-sequence) :cljs (gen/string)) (s/gen ::array) (s/gen ::map-entry) (s/gen ::sequential)])))) (s/def ::stack (s/with-gen #?(:cljs #(satisfies? IStack %) :clj #(instance? clojure.lang.IPersistentStack %)) (fn [] (s/gen (s/or :vector vector? :list list?))))) (s/def ::list list?) (defn named? [x] #?(:clj (instance? clojure.lang.Named x) :cljs (satisfies? INamed x))) (s/def ::symbol symbol?) (s/def ::named (s/with-gen named? (fn [] (s/gen (s/or :symbol ::symbol :keyword ::keyword))))) (comment (require '[clojure.spec.test.alpha :as stest]) (stest/instrument) (stest/unstrument))
101f4b93c69af80db1b76cdf21a9dfa3f1a0acdd503957c3682a1808962c15d2
byorgey/bin
cm.hs
# LANGUAGE ScopedTypeVariables # # LANGUAGE ViewPatterns # -- Depends on lens-datetime package import Control.Applicative import Control.Exception (IOException, catch) import Control.Lens ((^.)) import Control.Monad import Data.Time import Data.Time.Lens import System.Directory import System.FilePath import System.IO import System.Process mailboxesrc, maildir :: String mailboxesrc = ".mailboxesrc" maildir = "Maildir" data Box = Box { boxName :: String, boxLoc :: FilePath, new :: Int } readBox :: String -> Box readBox (words -> [name, loc]) = Box name loc 0 main :: IO () main = do t <- getCurrentTime tz <- getCurrentTimeZone let hrs = t ^. utcInTZ tz . hours when (hrs >= 12) $ do hSetBuffering stdout NoBuffering home <- getHomeDirectory boxes <- map readBox . lines <$> readFile (home </> mailboxesrc) mainloop home boxes nonEmpty :: Box -> Bool nonEmpty = (>0) . new mainloop :: FilePath -> [Box] -> IO () mainloop home boxes = do boxes' <- filter nonEmpty <$> mapM (checkBox (home </> maildir)) boxes putStr $ showCounts boxes' putStr "> " choice <- readLnMaybe case choice of Nothing -> mainloop home boxes' Just 0 -> return () Just i -> do if (i <= length boxes') then openBox (boxes' !! (i - 1)) else mapM_ openBox (reverse boxes') mainloop home boxes' openBox :: Box -> IO () openBox box = do system $ "m " ++ boxName box return () readLnMaybe :: (Read a) => IO (Maybe a) readLnMaybe = readMaybe <$> getLine readMaybe :: (Read a) => String -> Maybe a readMaybe s = case reads s of [(x,[])] -> Just x _ -> Nothing checkBox :: FilePath -> Box -> IO Box checkBox dir box = do n <- countNew dir box return $ box { new = n } countNew :: FilePath -> Box -> IO Int countNew dir box = countEm `catch` (\(_ :: IOException) -> return 0) where countEm = (subtract 2) . length <$> getDirectoryContents (dir </> boxLoc box </> "new") showCounts :: [Box] -> String showCounts = unlines . zipWith number [1::Int ..] . map showCount where number n s = show n ++ ") " ++ s showCount (Box name _ n) = name ++ ": " ++ show n
null
https://raw.githubusercontent.com/byorgey/bin/7370e6cc77be375c9e5e00718d15773169534c10/cm.hs
haskell
Depends on lens-datetime package
# LANGUAGE ScopedTypeVariables # # LANGUAGE ViewPatterns # import Control.Applicative import Control.Exception (IOException, catch) import Control.Lens ((^.)) import Control.Monad import Data.Time import Data.Time.Lens import System.Directory import System.FilePath import System.IO import System.Process mailboxesrc, maildir :: String mailboxesrc = ".mailboxesrc" maildir = "Maildir" data Box = Box { boxName :: String, boxLoc :: FilePath, new :: Int } readBox :: String -> Box readBox (words -> [name, loc]) = Box name loc 0 main :: IO () main = do t <- getCurrentTime tz <- getCurrentTimeZone let hrs = t ^. utcInTZ tz . hours when (hrs >= 12) $ do hSetBuffering stdout NoBuffering home <- getHomeDirectory boxes <- map readBox . lines <$> readFile (home </> mailboxesrc) mainloop home boxes nonEmpty :: Box -> Bool nonEmpty = (>0) . new mainloop :: FilePath -> [Box] -> IO () mainloop home boxes = do boxes' <- filter nonEmpty <$> mapM (checkBox (home </> maildir)) boxes putStr $ showCounts boxes' putStr "> " choice <- readLnMaybe case choice of Nothing -> mainloop home boxes' Just 0 -> return () Just i -> do if (i <= length boxes') then openBox (boxes' !! (i - 1)) else mapM_ openBox (reverse boxes') mainloop home boxes' openBox :: Box -> IO () openBox box = do system $ "m " ++ boxName box return () readLnMaybe :: (Read a) => IO (Maybe a) readLnMaybe = readMaybe <$> getLine readMaybe :: (Read a) => String -> Maybe a readMaybe s = case reads s of [(x,[])] -> Just x _ -> Nothing checkBox :: FilePath -> Box -> IO Box checkBox dir box = do n <- countNew dir box return $ box { new = n } countNew :: FilePath -> Box -> IO Int countNew dir box = countEm `catch` (\(_ :: IOException) -> return 0) where countEm = (subtract 2) . length <$> getDirectoryContents (dir </> boxLoc box </> "new") showCounts :: [Box] -> String showCounts = unlines . zipWith number [1::Int ..] . map showCount where number n s = show n ++ ") " ++ s showCount (Box name _ n) = name ++ ": " ++ show n