code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Handler.PostLogin where import Import getPostLoginR :: Handler Html getPostLoginR = do app <- getYesod redirectUltDest $ loginDest app
chreekat/snowdrift
Handler/PostLogin.hs
agpl-3.0
152
0
8
29
39
20
19
6
1
module Propellor.Property.HostingProvider.CloudAtCost where import Propellor import qualified Propellor.Property.Hostname as Hostname import qualified Propellor.Property.File as File import qualified Propellor.Property.User as User -- Clean up a system as installed by cloudatcost.com decruft :: Property NoInfo decruft = propertyList "cloudatcost cleanup" [ Hostname.sane , "worked around grub/lvm boot bug #743126" ==> "/etc/default/grub" `File.containsLine` "GRUB_DISABLE_LINUX_UUID=true" `onChange` cmdProperty "update-grub" [] `onChange` cmdProperty "update-initramfs" ["-u"] , combineProperties "nuked cloudatcost cruft" [ File.notPresent "/etc/rc.local" , File.notPresent "/etc/init.d/S97-setup.sh" , File.notPresent "/zang-debian.sh" , User.nuked "user" User.YesReallyDeleteHome ] ]
avengerpenguin/propellor
src/Propellor/Property/HostingProvider/CloudAtCost.hs
bsd-2-clause
814
14
10
102
162
95
67
17
1
{- | The public face of Template Haskell For other documentation, refer to: <http://www.haskell.org/haskellwiki/Template_Haskell> -} module Language.Haskell.TH( -- * The monad and its operations Q, runQ, -- ** Administration: errors, locations and IO reportError, -- :: String -> Q () reportWarning, -- :: String -> Q () report, -- :: Bool -> String -> Q () recover, -- :: Q a -> Q a -> Q a location, -- :: Q Loc Loc(..), runIO, -- :: IO a -> Q a -- ** Querying the compiler -- *** Reify reify, -- :: Name -> Q Info reifyModule, thisModule, Info(..), ModuleInfo(..), InstanceDec, ParentName, Arity, Unlifted, -- *** Language extension lookup Extension(..), extsEnabled, isExtEnabled, -- *** Name lookup lookupTypeName, -- :: String -> Q (Maybe Name) lookupValueName, -- :: String -> Q (Maybe Name) -- *** Fixity lookup reifyFixity, -- *** Instance lookup reifyInstances, isInstance, -- *** Roles lookup reifyRoles, -- *** Annotation lookup reifyAnnotations, AnnLookup(..), -- *** Constructor strictness lookup reifyConStrictness, -- * Typed expressions TExp, unType, -- * Names Name, NameSpace, -- Abstract -- ** Constructing names mkName, -- :: String -> Name newName, -- :: String -> Q Name -- ** Deconstructing names nameBase, -- :: Name -> String nameModule, -- :: Name -> Maybe String namePackage, -- :: Name -> Maybe String nameSpace, -- :: Name -> Maybe NameSpace -- ** Built-in names tupleTypeName, tupleDataName, -- Int -> Name unboxedTupleTypeName, unboxedTupleDataName, -- :: Int -> Name -- * The algebraic data types -- | The lowercase versions (/syntax operators/) of these constructors are -- preferred to these constructors, since they compose better with -- quotations (@[| |]@) and splices (@$( ... )@) -- ** Declarations Dec(..), Con(..), Clause(..), SourceUnpackedness(..), SourceStrictness(..), DecidedStrictness(..), Bang(..), Strict, Foreign(..), Callconv(..), Safety(..), Pragma(..), Inline(..), RuleMatch(..), Phases(..), RuleBndr(..), AnnTarget(..), FunDep(..), FamFlavour(..), TySynEqn(..), TypeFamilyHead(..), Fixity(..), FixityDirection(..), defaultFixity, maxPrecedence, PatSynDir(..), PatSynArgs(..), -- ** Expressions Exp(..), Match(..), Body(..), Guard(..), Stmt(..), Range(..), Lit(..), -- ** Patterns Pat(..), FieldExp, FieldPat, -- ** Types Type(..), TyVarBndr(..), TyLit(..), Kind, Cxt, Pred, Syntax.Role(..), FamilyResultSig(..), Syntax.InjectivityAnn(..), PatSynType, -- * Library functions -- ** Abbreviations InfoQ, ExpQ, DecQ, DecsQ, ConQ, TypeQ, TyLitQ, CxtQ, PredQ, MatchQ, ClauseQ, BodyQ, GuardQ, StmtQ, RangeQ, SourceStrictnessQ, SourceUnpackednessQ, BangTypeQ, VarBangTypeQ, StrictTypeQ, VarStrictTypeQ, PatQ, FieldPatQ, RuleBndrQ, TySynEqnQ, PatSynDirQ, PatSynArgsQ, -- ** Constructors lifted to 'Q' -- *** Literals intPrimL, wordPrimL, floatPrimL, doublePrimL, integerL, rationalL, charL, stringL, stringPrimL, charPrimL, -- *** Patterns litP, varP, tupP, conP, uInfixP, parensP, infixP, tildeP, bangP, asP, wildP, recP, listP, sigP, viewP, fieldPat, -- *** Pattern Guards normalB, guardedB, normalG, normalGE, patG, patGE, match, clause, -- *** Expressions dyn, varE, conE, litE, appE, uInfixE, parensE, staticE, infixE, infixApp, sectionL, sectionR, lamE, lam1E, lamCaseE, tupE, condE, multiIfE, letE, caseE, appsE, listE, sigE, recConE, recUpdE, stringE, fieldExp, -- **** Ranges fromE, fromThenE, fromToE, fromThenToE, -- ***** Ranges with more indirection arithSeqE, fromR, fromThenR, fromToR, fromThenToR, -- **** Statements doE, compE, bindS, letS, noBindS, parS, -- *** Types forallT, varT, conT, appT, arrowT, infixT, uInfixT, parensT, equalityT, listT, tupleT, sigT, litT, promotedT, promotedTupleT, promotedNilT, promotedConsT, -- **** Type literals numTyLit, strTyLit, -- **** Strictness noSourceUnpackedness, sourceNoUnpack, sourceUnpack, noSourceStrictness, sourceLazy, sourceStrict, isStrict, notStrict, unpacked, bang, bangType, varBangType, strictType, varStrictType, -- **** Class Contexts cxt, classP, equalP, -- **** Constructors normalC, recC, infixC, forallC, gadtC, recGadtC, -- *** Kinds varK, conK, tupleK, arrowK, listK, appK, starK, constraintK, -- *** Roles nominalR, representationalR, phantomR, inferR, -- *** Top Level Declarations -- **** Data valD, funD, tySynD, dataD, newtypeD, -- **** Class classD, instanceD, instanceWithOverlapD, Overlap(..), sigD, standaloneDerivD, defaultSigD, -- **** Role annotations roleAnnotD, -- **** Type Family / Data Family dataFamilyD, openTypeFamilyD, closedTypeFamilyD, dataInstD, familyNoKindD, familyKindD, closedTypeFamilyNoKindD, closedTypeFamilyKindD, newtypeInstD, tySynInstD, typeFam, dataFam, tySynEqn, injectivityAnn, noSig, kindSig, tyVarSig, -- **** Foreign Function Interface (FFI) cCall, stdCall, cApi, prim, javaScript, unsafe, safe, forImpD, -- **** Pragmas ruleVar, typedRuleVar, pragInlD, pragSpecD, pragSpecInlD, pragSpecInstD, pragRuleD, pragAnnD, pragLineD, -- **** Pattern Synonyms patSynD, patSynSigD, unidir, implBidir, explBidir, prefixPatSyn, infixPatSyn, recordPatSyn, -- * Pretty-printer Ppr(..), pprint, pprExp, pprLit, pprPat, pprParendType ) where import Language.Haskell.TH.Syntax as Syntax import Language.Haskell.TH.Lib import Language.Haskell.TH.Ppr
vikraman/ghc
libraries/template-haskell/Language/Haskell/TH.hs
bsd-3-clause
6,267
0
5
1,727
1,212
847
365
101
0
module Test14 where f = let x = 45 in (x, 45)
kmate/HaRe
old/testing/refacRedunDec/Test14AST.hs
bsd-3-clause
47
0
8
13
26
15
11
2
1
{-# OPTIONS -fglasgow-exts #-} -- This code defines a default method with a highly dubious type, -- because 'v' is not mentioned, and there are no fundeps -- -- However, arguably the instance declaration should be accepted, -- beause it's equivalent to -- instance Baz Int Int where { foo x = x } -- which *does* typecheck -- GHC does not actually macro-expand the instance decl. Instead, it -- defines a default method function, thus -- -- $dmfoo :: Baz v x => x -> x -- $dmfoo y = y -- -- Notice that this is an ambiguous type: you can't call $dmfoo -- without triggering an error. And when you write an instance decl, -- it calls the default method: -- -- instance Baz Int Int where foo = $dmfoo -- -- I'd never thought of that. You might think that we should just -- *infer* the type of the default method (here forall a. a->a), but -- in the presence of higher rank types etc we can't necessarily do -- that. module Foo1 where class Baz v x where foo :: x -> x foo y = y instance Baz Int Int
hvr/jhc
regress/tests/1_typecheck/2_pass/ghc/uncat/tc199.hs
mit
1,013
0
7
212
65
45
20
-1
-1
module Foo where {-@ type Range Lo Hi = {v:Int | Lo <= v && v < Hi} @-} {-@ bow :: Range 0 100 @-} bow :: Int bow = 12
mightymoose/liquidhaskell
tests/pos/tyExpr.hs
bsd-3-clause
121
0
4
34
16
11
5
3
1
{-# LANGUAGE DeriveFunctor, RankNTypes #-} module Lamdu.Sugar.AddNames.CPS ( CPS(..) ) where import Control.Applicative (Applicative(..)) data CPS m a = CPS { runCPS :: forall r. m r -> m (a, r) } deriving (Functor) instance Functor m => Applicative (CPS m) where pure x = CPS $ fmap ((,) x) CPS cpsf <*> CPS cpsx = CPS (fmap foo . cpsf . cpsx) where foo (f, (x, r)) = (f x, r)
sinelaw/lamdu
Lamdu/Sugar/AddNames/CPS.hs
gpl-3.0
405
0
12
99
187
103
84
11
0
module OverD where -- Tests that we verify consistency of type families between -- transitive imports. import OverB import OverC
ezyang/ghc
testsuite/tests/indexed-types/should_fail/OverD.hs
bsd-3-clause
129
0
3
20
12
9
3
3
0
{-# LANGUAGE TemplateHaskell, FlexibleInstances, ScopedTypeVariables, GADTs, RankNTypes, FlexibleContexts, TypeSynonymInstances, MultiParamTypeClasses, DeriveDataTypeable, PatternGuards, OverlappingInstances, UndecidableInstances, CPP #-} module T1735_Help.Xml (Element(..), Xml, fromXml) where import T1735_Help.Basics import T1735_Help.Instances () import T1735_Help.State data Element = Elem String [Element] | CData String | Attr String String fromXml :: Xml a => [Element] -> Maybe a fromXml xs = case readXml xs of Just (_, v) -> return v Nothing -> error "XXX" class (Data XmlD a) => Xml a where toXml :: a -> [Element] toXml = defaultToXml readXml :: [Element] -> Maybe ([Element], a) readXml = defaultReadXml readXml' :: [Element] -> Maybe ([Element], a) readXml' = defaultReadXml' instance (Data XmlD t, Show t) => Xml t data XmlD a = XmlD { toXmlD :: a -> [Element], readMXmlD :: ReadM Maybe a } xmlProxy :: Proxy XmlD xmlProxy = error "xmlProxy" instance Xml t => Sat (XmlD t) where dict = XmlD { toXmlD = toXml, readMXmlD = readMXml } defaultToXml :: Xml t => t -> [Element] defaultToXml x = [Elem (constring $ toConstr xmlProxy x) (transparentToXml x)] transparentToXml :: Xml t => t -> [Element] transparentToXml x = concat $ gmapQ xmlProxy (toXmlD dict) x -- Don't do any defaulting here, as these functions can be implemented -- differently by the user. We do the defaulting elsewhere instead. -- The t' type is thus not used. defaultReadXml :: Xml t => [Element] -> Maybe ([Element], t) defaultReadXml es = readXml' es defaultReadXml' :: Xml t => [Element] -> Maybe ([Element], t) defaultReadXml' = readXmlWith readVersionedElement readXmlWith :: Xml t => (Element -> Maybe t) -> [Element] -> Maybe ([Element], t) readXmlWith f es = case es of e : es' -> case f e of Just v -> Just (es', v) Nothing -> Nothing [] -> Nothing readVersionedElement :: forall t . Xml t => Element -> Maybe t readVersionedElement e = readElement e readElement :: forall t . Xml t => Element -> Maybe t readElement (Elem n es) = res where resType :: t resType = typeNotValue resType resDataType = dataTypeOf xmlProxy resType con = readConstr resDataType n res = case con of Just c -> f c Nothing -> Nothing f c = let m :: Maybe ([Element], t) m = constrFromElements c es in case m of Just ([], x) -> Just x _ -> Nothing readElement _ = Nothing constrFromElements :: forall t . Xml t => Constr -> [Element] -> Maybe ([Element], t) constrFromElements c es = do let st = ReadState { xmls = es } m :: ReadM Maybe t m = fromConstrM xmlProxy (readMXmlD dict) c -- XXX Should we flip the result order? (x, st') <- runStateT m st return (xmls st', x) type ReadM m = StateT ReadState m data ReadState = ReadState { xmls :: [Element] } getXmls :: Monad m => ReadM m [Element] getXmls = do st <- get return $ xmls st putXmls :: Monad m => [Element] -> ReadM m () putXmls xs = do st <- get put $ st { xmls = xs } readMXml :: Xml a => ReadM Maybe a readMXml = do xs <- getXmls case readXml xs of Nothing -> fail "Cannot read value" Just (xs', v) -> do putXmls xs' return v typeNotValue :: Xml a => a -> a typeNotValue t = error ("Type used as value: " ++ typeName) where typeName = dataTypeName (dataTypeOf xmlProxy t) -- The Xml [a] context is a bit scary, but if we don't have it then -- GHC complains about overlapping instances instance (Xml a {-, Xml [a] -}) => Xml [a] where toXml = concatMap toXml readXml = f [] [] where f acc_xs acc_vs [] = Just (reverse acc_xs, reverse acc_vs) f acc_xs acc_vs (x:xs) = case readXml [x] of Just ([], v) -> f acc_xs (v:acc_vs) xs _ -> f (x:acc_xs) acc_vs xs instance Xml String where toXml x = [CData x] readXml = readXmlWith f where f (CData x) = Just x f _ = Nothing
ezyang/ghc
testsuite/tests/typecheck/should_run/T1735_Help/Xml.hs
bsd-3-clause
4,655
0
14
1,632
1,441
748
693
106
3
{-# LANGUAGE TemplateHaskell #-} module AFM where class Functor f where fmap :: (a -> b) -> f a -> f b fmap id x == x fmap f . fmap g == fmap (f . g) class Functor f => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b -- LiftA fmap f x == liftA f x liftA id x == x liftA3 (.) f g x == f <*> (g <*> x) liftA f (pure x) == pure (f x) data State s a = State (s -> (a, s)) runState :: State s a -> s -> (a, s) runState (State f) = f data Writer msg b = Writer (b, msg) runWriter :: Write msg b -> (b, msg) runWriter (Writer a) = a class Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b return :: a -> ma fail :: String -> m a -- return a >>= k = k a -- m >>= return -- m >>= (\x -> k x >>= h) = (m >>= k) >>= h
mortum5/programming
haskell/usefull/AMP.hs
mit
800
0
11
251
425
217
208
-1
-1
module Main () where import Data.List (elemIndex) type Header = String type Row a = [a] data Table a = Table { headers :: [Header] , rows :: [Row a] } create :: Table a -> Row a -> Table a create (Table headers rows) newRow = Table headers $ [newRow] ++ rows type Predicate a = (Row a -> Bool) readRow :: Table a -> Predicate a -> [Row a] readRow (Table _ rows) predicate = filter predicate rows readColumn :: Header -> Table a -> Predicate a -> [a] readColumn headerName table@(Table headers rows) predicate = maybeGetColumn $ readRow table predicate maybeGetColumn headerName headers = fmap (flip (!!)) $ elemIndex headerName headers
bmuk/PipeDBHs
Main.hs
mit
687
0
10
165
271
144
127
14
1
{-# LANGUAGE OverloadedStrings #-} -------------------------------------------------------------------------------- -- | -- Module : Network.MQTT.Broker.RetainedMessages -- Copyright : (c) Lars Petersen 2016 -- License : MIT -- -- Maintainer : [email protected] -- Stability : experimental -------------------------------------------------------------------------------- module Network.MQTT.Broker.RetainedMessages where import Control.Applicative hiding (empty) import Control.Concurrent.MVar import qualified Data.ByteString.Lazy as BSL import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.Map.Strict as M import Data.Maybe import qualified Data.Set as S import Prelude hiding (null) import qualified Network.MQTT.Message as Message import qualified Network.MQTT.Message.Topic as Topic newtype RetainedStore = RetainedStore { unstore :: MVar RetainedTree } newtype RetainedTree = RetainedTree { untree :: M.Map Topic.Level RetainedNode } data RetainedNode = RetainedNode !RetainedTree !(Maybe Message.Message) new :: IO RetainedStore new = RetainedStore <$> newMVar empty store :: Message.Message -> RetainedStore -> IO () store msg (RetainedStore mvar) | retain = modifyMVar_ mvar $ \tree-> -- The seq ($!) is important for not leaking memory! pure $! if BSL.null body then delete msg tree else insert msg tree | otherwise = pure () where Message.Payload body = Message.msgPayload msg Message.Retain retain = Message.msgRetain msg retrieve :: Topic.Filter -> RetainedStore -> IO (S.Set Message.Message) retrieve filtr (RetainedStore mvar) = lookupFilter filtr <$> readMVar mvar empty :: RetainedTree empty = RetainedTree mempty null :: RetainedTree -> Bool null = M.null . untree insert :: Message.Message -> RetainedTree -> RetainedTree insert msg = union (singleton msg) delete :: Message.Message -> RetainedTree -> RetainedTree delete msg = flip difference (singleton msg) singleton :: Message.Message -> RetainedTree singleton msg = let l :| ls = Topic.topicLevels (Message.msgTopic msg) in RetainedTree (M.singleton l $ node ls) where node [] = RetainedNode empty $! Just $! msg node (x:xs) = RetainedNode (RetainedTree $ M.singleton x $ node xs) Nothing -- | The expression `union t1 t2` takes the left-biased union of `t1` and `t2`. union :: RetainedTree -> RetainedTree -> RetainedTree union (RetainedTree m1) (RetainedTree m2) = RetainedTree $ M.unionWith merge m1 m2 where merge (RetainedNode t1 mm1) (RetainedNode t2 mm2) = RetainedNode (t1 `union` t2) $! case mm1 <|> mm2 of Nothing -> Nothing Just mm -> Just $! mm difference :: RetainedTree -> RetainedTree -> RetainedTree difference (RetainedTree m1) (RetainedTree m2) = RetainedTree $ M.differenceWith diff m1 m2 where diff (RetainedNode t1 mm1) (RetainedNode t2 mm2) | null t3 && isNothing mm3 = Nothing | otherwise = Just (RetainedNode t3 mm3) where t3 = difference t1 t2 mm3 = case mm2 of Just _ -> Nothing Nothing -> mm1 lookupFilter :: Topic.Filter -> RetainedTree -> S.Set Message.Message lookupFilter filtr t = let l :| ls = Topic.filterLevels filtr in collect l ls t where collect l ls tree@(RetainedTree m) = case l of "#" -> allTree tree "+" -> M.foldl (\s node-> s `S.union` pathNode ls node) S.empty m _ -> fromMaybe S.empty $ pathNode ls <$> M.lookup l m allTree (RetainedTree branches) = M.foldl (\s node-> s `S.union` allNode node) S.empty branches allNode (RetainedNode subtree mmsg) = case mmsg of Nothing -> allTree subtree Just msg -> S.insert msg (allTree subtree) pathNode [] (RetainedNode _ mmsg) = fromMaybe S.empty $ S.singleton <$> mmsg pathNode (x:xs) (RetainedNode subtree mmsg) = case x of "#"-> fromMaybe id (S.insert <$> mmsg) (collect x xs subtree) _ -> collect x xs subtree
lpeterse/haskell-mqtt
src/Network/MQTT/Broker/RetainedMessages.hs
mit
4,172
0
14
1,013
1,238
637
601
83
6
module Main where import Parser import Control.Monad.Trans import System.Console.Haskeline process line = do let res = parseTopLevel line case res of Left err -> print err Right ex -> mapM_ print ex main = runInputT defaultSettings loop where loop = do minput <- getInputLine "ready> " case minput of Nothing -> outputStrLn "Goodbye." Just input -> (liftIO $ process input) >> loop
waterlink/hgo
ParserRepl.hs
mit
432
0
15
112
138
67
71
15
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Control.Monad.Zipkin ( Identifier, parseIdentifier , TraceInfo(..), fromHeaders, toHeaders, newTraceInfo , TraceT, getTraceInfo, forkTraceInfo, runTraceT ) where import Control.Monad.State.Strict import System.Random.Mersenne.Pure64 import Data.Zipkin.Types import qualified Data.Zipkin.Context as Ctx newtype TraceT m a = TraceT { run :: StateT Ctx.TraceContext m a } deriving (Functor, Applicative, Monad, MonadTrans) newTraceInfo :: IO TraceInfo newTraceInfo = evalState Ctx.newTraceInfo <$> newPureMT getTraceInfo :: Monad m => TraceT m TraceInfo getTraceInfo = TraceT Ctx.getTraceInfo forkTraceInfo :: Monad m => TraceT m TraceInfo forkTraceInfo = TraceT Ctx.forkTraceInfo runTraceT :: Monad m => TraceT m a -> TraceInfo -> m a runTraceT m = evalStateT (run m) . Ctx.mkContext
srijs/haskell-zipkin
src/Control/Monad/Zipkin.hs
mit
851
0
8
124
243
137
106
19
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE RankNTypes #-} module Web.Stripe.Test.Subscription where import Data.Either import Data.Maybe import Test.Hspec import Web.Stripe.Test.Prelude import Web.Stripe.Test.Util import Web.Stripe.Subscription import Web.Stripe.Customer import Web.Stripe.Plan import Web.Stripe.Coupon subscriptionTests :: StripeSpec subscriptionTests stripe = do describe "Subscription tests" $ do it "Succesfully creates a Subscription" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") sub <- createSubscription cid planid void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves a Subscription" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") Subscription { subscriptionId = sid } <- createSubscription cid planid sub <- getSubscription cid sid void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves a Subscription expanded" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") Subscription { subscriptionId = sid } <- createSubscription cid planid sub <- getSubscription cid sid -&- ExpandParams ["customer"] void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves a Customer's Subscriptions expanded" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") void $ createSubscription cid planid sub <- getSubscriptionsByCustomerId cid -&- ExpandParams ["data.customer"] void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves a Customer's Subscriptions" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") void $ createSubscription cid planid sub <- getSubscriptionsByCustomerId cid void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves all Subscriptions expanded" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") void $ createSubscription cid planid sub <- getSubscriptions -&- ExpandParams ["data.customer"] void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves all Subscriptions" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") void $ createSubscription cid planid sub <- getSubscriptions void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully updates a Customer's Subscriptions" $ do planid <- makePlanId secondPlanid <- makePlanId couponid <- makeCouponId result <- stripe $ do Coupon { } <- createCoupon (Just couponid) Once -&- (AmountOff 1) -&- USD Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") Subscription { subscriptionId = sid } <- createSubscription cid planid sub <- updateSubscription cid sid -&- couponid -&- MetaData [("hi","there")] void $ deleteCustomer cid return sub result `shouldSatisfy` isRight let Right Subscription {..} = result subscriptionMetaData `shouldBe` (MetaData [("hi", "there")]) subscriptionDiscount `shouldSatisfy` isJust it "Succesfully cancels a Customer's Subscription" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") Subscription { subscriptionId = sid } <- createSubscription cid planid sub <- cancelSubscription cid sid -&- AtPeriodEnd False void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight let Right Subscription {..} = result subscriptionStatus `shouldBe` Canceled
dmjio/stripe
stripe-tests/tests/Web/Stripe/Test/Subscription.hs
mit
6,399
0
22
2,450
1,481
693
788
165
1
{-# LANGUAGE OverloadedStrings #-} -- we infect all the other modules with instances from -- this module, so they don't appear orphaned. {-# OPTIONS_GHC -fno-warn-orphans #-} module Network.Datadog.Internal ( prependMaybe , prependBool , datadogHttp , decodeDatadog , baseRequest , defaultMonitorOptions , DatadogCredentials(..) , module Network.Datadog.Lens , module Network.Datadog.Types ) where import Control.Arrow (first) import Control.Exception import Control.Lens hiding ((.=), cons) import Data.Aeson hiding (Series, Success, Error) import Data.Aeson.Types (modifyFailure, typeMismatch) import qualified Data.ByteString.Lazy as LBS (ByteString, empty) import qualified Data.DList as D import qualified Data.HashMap.Strict as HM import Data.Maybe import Data.Text (Text, pack, append, splitAt, findIndex, cons) import Data.Text.Lazy (unpack) import Data.Text.Encoding (encodeUtf8) import Data.Text.Lazy.Encoding (decodeUtf8) import Data.Time.Clock import Data.Time.Clock.POSIX import Data.Vector ((!?)) import Network.HTTP.Client hiding (host) import Network.HTTP.Types import Network.Datadog.Types import Network.Datadog.Lens import Prelude hiding (splitAt) prependMaybe :: (a -> b) -> Maybe a -> [b] -> [b] prependMaybe f = maybe id ((:) . f) prependBool :: Bool -> b -> [b] -> [b] prependBool p a = if p then (a :) else id datadogHttp :: Environment-> String -> [(String, String)] -> StdMethod -> Maybe LBS.ByteString -> IO LBS.ByteString datadogHttp (Environment keys baseUrl manager) endpoint q httpMethod content = do initReq <- parseUrlThrow $ baseUrl ++ endpoint let body = RequestBodyLBS $ fromMaybe LBS.empty content headers = [("Content-type", "application/json") | isJust content] apiQuery = [("api_key", apiKey keys) ,("application_key", appKey keys)] fullQuery = map (\(a,b) -> (encodeUtf8 (pack a), Just (encodeUtf8 (pack b)))) $ apiQuery ++ q request = setQueryString fullQuery $ initReq { method = renderStdMethod httpMethod , requestBody = body , requestHeaders = headers } responseBody <$> httpLbs request manager decodeDatadog :: FromJSON a => String -> LBS.ByteString -> IO a decodeDatadog funcname body = either (throwIO . AssertionFailed . failstring) return $ eitherDecode body where failstring e = "Datadog Library decoding failure in \"" ++ funcname ++ "\": " ++ e ++ ": " ++ unpack (decodeUtf8 body) baseRequest :: Request baseRequest = fromJust $ parseUrlThrow "https://api.datadoghq.com" class DatadogCredentials s where signRequest :: s -> Request -> Request instance DatadogCredentials Write where signRequest (Write k) = setQueryString [("api_key", Just k)] instance DatadogCredentials ReadWrite where signRequest (ReadWrite w r) = setQueryString [("api_key", Just w), ("application_key", Just r)] instance ToJSON DowntimeSpec where toJSON ds = object $ prependMaybe (\a -> "start" .= (ceiling (utcTimeToPOSIXSeconds a) :: Integer)) (ds ^. start) $ prependMaybe (\a -> "end" .= (floor (utcTimeToPOSIXSeconds a) :: Integer)) (ds ^. end) ["scope" .= (ds ^. scope)] instance FromJSON DowntimeSpec where parseJSON (Object v) = modifyFailure ("DowntimeSpec: " ++) $ DowntimeSpec <$> (maybe (return Nothing) (withScientific "Integer" (\t -> return (Just (posixSecondsToUTCTime (fromIntegral (floor t :: Integer)))))) =<< (v .:? "start")) <*> (maybe (return Nothing) (withScientific "Integer" (\t -> return (Just (posixSecondsToUTCTime (fromIntegral (floor t :: Integer)))))) =<< (v .:? "end")) <*> v .:? "message" .!= Nothing <*> (withArray "Text" (\t -> maybe (fail "\"scope\" Array is too short") parseJSON (t !? 0)) =<< v .: "scope") parseJSON a = modifyFailure ("DowntimeSpec: " ++) $ typeMismatch "Object" a instance ToJSON Tag where toJSON (KeyValueTag k v) = Data.Aeson.String $ k `append` (':' `cons` v) toJSON (LabelTag t) = Data.Aeson.String t instance FromJSON Tag where parseJSON (String s) = return $ maybe (LabelTag s) (\i -> uncurry KeyValueTag (splitAt i s)) $ findIndex (==':') s parseJSON a = modifyFailure ("Tag: " ++) $ typeMismatch "String" a instance ToJSON CheckStatus where toJSON CheckOk = Number 0 toJSON CheckWarning = Number 1 toJSON CheckCritical = Number 2 toJSON CheckUnknown = Number 3 instance FromJSON CheckStatus where parseJSON (Number 0) = return CheckOk parseJSON (Number 1) = return CheckWarning parseJSON (Number 2) = return CheckCritical parseJSON (Number 3) = return CheckUnknown parseJSON (Number n) = fail $ "CheckStatus: Number \"" ++ show n ++ "\" is not a valid CheckStatus" parseJSON a = modifyFailure ("MonitorType: " ++) $ typeMismatch "Number" a instance ToJSON CheckResult where toJSON cr = object $ prependMaybe (\a -> "timestamp" .= (floor (utcTimeToPOSIXSeconds a) :: Integer)) (cr ^. timestamp) $ prependMaybe (\a -> "message" .= a) (cr ^. message) ["check" .= (cr ^. check) ,"host_name" .= (cr ^. hostName) ,"status" .= (cr ^. status) ,"tags" .= (cr ^. tags) ] instance FromJSON CheckResult where parseJSON (Object v) = modifyFailure ("CheckResult: " ++) $ CheckResult <$> v .: "check" <*> v .: "host_name" <*> v .: "status" <*> v .:? "timestamp" .!= Nothing <*> v .:? "message" .!= Nothing <*> v .: "tags" .!= [] parseJSON a = modifyFailure ("CheckResult: " ++) $ typeMismatch "Object" a instance ToJSON Downtime where toJSON downtime = Object $ HM.insert "id" (toJSON $ downtime ^. id') basemap where (Object basemap) = toJSON (downtime ^. spec) instance FromJSON Downtime where parseJSON (Object v) = modifyFailure ("Downtime: " ++) $ Downtime <$> v .: "id" <*> parseJSON (Object v) parseJSON a = modifyFailure ("Downtime: " ++) $ typeMismatch "Object" a instance ToJSON EventPriority where toJSON NormalPriority = Data.Aeson.String "normal" toJSON LowPriority = Data.Aeson.String "low" instance FromJSON EventPriority where parseJSON (Data.Aeson.String "normal") = return NormalPriority parseJSON (Data.Aeson.String "low") = return LowPriority parseJSON (Data.Aeson.String s) = fail $ "EventPriority: String " ++ show s ++ " is not a valid EventPriority" parseJSON a = modifyFailure ("EventPriority: " ++) $ typeMismatch "String" a instance ToJSON AlertType where toJSON Error = Data.Aeson.String "error" toJSON Warning = Data.Aeson.String "warning" toJSON Info = Data.Aeson.String "info" toJSON Success = Data.Aeson.String "success" instance FromJSON AlertType where parseJSON (Data.Aeson.String "error") = return Error parseJSON (Data.Aeson.String "warning") = return Warning parseJSON (Data.Aeson.String "info") = return Info parseJSON (Data.Aeson.String "success") = return Success parseJSON (Data.Aeson.String s) = fail $ "AlertType: String " ++ show s ++ " is not a valid AlertType" parseJSON a = modifyFailure ("AlertType: " ++) $ typeMismatch "String" a instance ToJSON SourceType where toJSON Nagios = Data.Aeson.String "nagios" toJSON Hudson = Data.Aeson.String "hudson" toJSON Jenkins = Data.Aeson.String "jenkins" toJSON User = Data.Aeson.String "user" toJSON MyApps = Data.Aeson.String "my apps" toJSON Feed = Data.Aeson.String "feed" toJSON Chef = Data.Aeson.String "chef" toJSON Puppet = Data.Aeson.String "puppet" toJSON Git = Data.Aeson.String "git" toJSON BitBucket = Data.Aeson.String "bitbucket" toJSON Fabric = Data.Aeson.String "fabric" toJSON Capistrano = Data.Aeson.String "capistrano" instance FromJSON SourceType where parseJSON (Data.Aeson.String "nagios") = return Nagios parseJSON (Data.Aeson.String "hudson") = return Hudson parseJSON (Data.Aeson.String "jenkins") = return Jenkins parseJSON (Data.Aeson.String "user") = return User parseJSON (Data.Aeson.String "my apps") = return MyApps parseJSON (Data.Aeson.String "feed") = return Feed parseJSON (Data.Aeson.String "chef") = return Chef parseJSON (Data.Aeson.String "puppet") = return Puppet parseJSON (Data.Aeson.String "git") = return Git parseJSON (Data.Aeson.String "bitbucket") = return BitBucket parseJSON (Data.Aeson.String "fabric") = return Fabric parseJSON (Data.Aeson.String "capistrano") = return Capistrano parseJSON (Data.Aeson.String s) = fail $ "SourceType: String " ++ show s ++ " is not a valid SourceType" parseJSON a = modifyFailure ("SourceType: " ++) $ typeMismatch "String" a instance ToJSON EventSpec where toJSON ed = object $ prependMaybe (\a -> "host" .= a) (ed ^. host) $ prependMaybe (\a -> "source_type_name" .= pack (show a)) (ed ^. sourceType) ["title" .= (ed ^. title) ,"text" .= (ed ^. text) ,"date_happened" .= (floor (utcTimeToPOSIXSeconds (ed ^. dateHappened)) :: Integer) ,"priority" .= pack (show (ed ^. priority)) ,"alert_type" .= pack (show (ed ^. alertType)) ,"tags" .= (ed ^. tags) ] instance FromJSON EventSpec where parseJSON (Object v) = modifyFailure ("EventSpec: " ++) $ EventSpec <$> v .: "title" <*> v .: "text" <*> (withScientific "Integer" (\t -> return (posixSecondsToUTCTime (fromIntegral (floor t :: Integer)))) =<< v .: "date_happened") <*> v .: "priority" <*> v .:? "host" .!= Nothing <*> v .:? "tags" .!= [] <*> v .:? "alert_type" .!= Info <*> v .:? "source_type" .!= Nothing parseJSON a = modifyFailure ("EventSpec: " ++) $ typeMismatch "Object" a instance ToJSON Event where toJSON event = Object $ HM.insert "id" (toJSON (event ^. id')) basemap where (Object basemap) = toJSON (event ^. details) instance FromJSON Event where parseJSON (Object v) = modifyFailure ("Event: " ++) $ Event <$> v .: "id" <*> parseJSON (Object v) parseJSON a = modifyFailure ("Event: " ++) $ typeMismatch "Object" a instance FromJSON WrappedEvent where parseJSON (Object v) = modifyFailure ("WrappedEvent: " ++) $ WrappedEvent <$> v .: "event" parseJSON a = modifyFailure ("WrappedEvent: " ++) $ typeMismatch "Object" a instance FromJSON WrappedEvents where parseJSON (Object v) = modifyFailure ("WrappedEvents: " ++) $ WrappedEvents <$> v .: "events" parseJSON a = modifyFailure ("WrappedEvents: " ++) $ typeMismatch "Object" a instance ToJSON Series where toJSON s = object [ "series" .= D.toList (fromSeries s) ] instance ToJSON Timestamp where toJSON = toJSON . (round :: NominalDiffTime -> Int) . fromTimestamp instance ToJSON MetricPoints where toJSON (Gauge ps) = toJSON $ fmap (first Timestamp) ps toJSON (Counter ps) = toJSON $ fmap (first Timestamp) ps instance ToJSON Metric where toJSON m = object ks where f = maybe id (\x y -> ("host" .= x) : y) $ metricHost m ks = f [ "metric" .= metricName m , "points" .= metricPoints m , "tags" .= metricTags m , "type" .= case metricPoints m of Gauge _ -> "gauge" :: Text Counter _ -> "counter" :: Text ] instance ToJSON MonitorType where toJSON MetricAlert = Data.Aeson.String "metric alert" toJSON ServiceCheck = Data.Aeson.String "service check" toJSON EventAlert = Data.Aeson.String "event alert" instance FromJSON MonitorType where parseJSON (Data.Aeson.String "metric alert") = return MetricAlert -- TODO figure out what "query alert" actually is parseJSON (Data.Aeson.String "query alert") = return MetricAlert parseJSON (Data.Aeson.String "service check") = return ServiceCheck parseJSON (Data.Aeson.String "event alert") = return EventAlert parseJSON (Data.Aeson.String s) = fail $ "MonitorType: String " ++ show s ++ " is not a valid MonitorType" parseJSON a = modifyFailure ("MonitorType: " ++) $ typeMismatch "String" a instance ToJSON MonitorOptions where toJSON opts = Object $ HM.fromList [ ("silenced", toJSON (opts ^. silenced)) , ("notify_no_data", Bool (opts ^. notifyNoData)) , ("no_data_timeframe", maybe Null (Number . fromIntegral) (opts ^. noDataTimeframe)) , ("timeout_h", maybe Null (Number . fromIntegral) (opts ^. timeoutH)) , ("renotify_interval", maybe Null (Number . fromIntegral) (opts ^. renotifyInterval)) , ("escalation_message", Data.Aeson.String (opts ^. escalationMessage)) , ("notify_audit", Bool (opts ^. notifyAudit)) ] instance FromJSON MonitorOptions where parseJSON (Object v) = modifyFailure ("MonitorOptions: " ++) $ MonitorOptions <$> v .:? "silenced" .!= HM.empty <*> v .:? "notify_no_data" .!= False <*> v .:? "no_data_timeframe" .!= Nothing <*> v .:? "timeout_h" .!= Nothing <*> v .:? "renotify_interval" .!= Nothing <*> v .:? "escalation_message" .!= "" <*> v .:? "notify_audit" .!= False parseJSON a = modifyFailure ("MonitorOptions: " ++) $ typeMismatch "Object" a instance ToJSON MonitorSpec where toJSON ms = Object $ HM.insert "options" (toJSON (ms ^. options)) hmap where (Object hmap) = object $ prependMaybe ("name" .=) (ms ^. name) $ prependMaybe ("message" .=) (ms ^. message) [ "type" .= pack (show (ms ^. type')) , "query" .= (ms ^. query) ] -- | Creates the most basic specification required by a monitor, containing the -- type of monitor and the query string used to detect the monitor's state. -- -- Generates a set of "default" Monitor options, which specify as little -- optional configuration as possible. This includes: -- -- * No silencing of any part of the monitor -- * No notification when data related to the monitor is missing -- * No alert timeout after the monitor is triggeredn -- * No renotification when the monitor is triggered -- * No notification when the monitor is modified -- -- In production situations, it is /not safe/ to rely on this documented -- default behaviour for critical setitngs; use the helper functions to -- introspect the MonitorOptions instance provided by this function. This also -- protects against future modifications to this API. defaultMonitorOptions :: MonitorOptions defaultMonitorOptions = MonitorOptions { monitorOptionsSilenced = HM.empty , monitorOptionsNotifyNoData = False , monitorOptionsNoDataTimeframe = Nothing , monitorOptionsTimeoutH = Nothing , monitorOptionsRenotifyInterval = Nothing , monitorOptionsEscalationMessage = "" , monitorOptionsNotifyAudit = False } instance FromJSON MonitorSpec where parseJSON (Object v) = modifyFailure ("MonitorSpec: " ++) $ MonitorSpec <$> v .: "type" <*> v .: "query" <*> v .:? "name" .!= Nothing <*> v .:? "message" .!= Nothing <*> v .:? "options" .!= defaultMonitorOptions parseJSON a = modifyFailure ("MonitorSpec: " ++) $ typeMismatch "Object" a instance ToJSON Monitor where toJSON monitor = Object $ HM.insert "id" (toJSON (monitor ^. id')) basemap where (Object basemap) = toJSON (monitor ^. spec) instance FromJSON Monitor where parseJSON (Object v) = modifyFailure ("Monitor: " ++ ) $ Monitor <$> v .: "id" <*> parseJSON (Object v) parseJSON a = modifyFailure ("Monitor: " ++) $ typeMismatch "Object" a
iand675/datadog
src/Network/Datadog/Internal.hs
mit
16,829
0
33
4,633
4,741
2,490
2,251
284
2
-- | Module for providing various functionals used in calculations involving -- quantum mathematics. This includes the fidelity and trace norm. module Hoqus.Fidelity where import Numeric.LinearAlgebra.Data import Numeric.LinearAlgebra import Hoqus.MtxFun -- | Function 'fidelity' calculates the fidelity between two quantum states (or -- any two square matrices) --fidelity :: Matrix C -> Matrix C -> C --fidelity a b = (sum $ map sqrt $ toList $ eigenvalues $ a <> b ) ** 2 -- | Function 'superFidelity' calculates an upper bound for the fidelity using -- only trace of the products of input matrices. superFidelity :: Matrix C -> Matrix C -> C superFidelity a b = (trace (a <> b)) + (sqrt (1 - trace (a <> a))) * (sqrt (1 - trace (b <> b))) -- | Function 'subFidelity' calculates a lower bound for the fidelity using only -- race of the products of input matrices. subFidelity :: Matrix C -> Matrix C -> C subFidelity a b = (trace p) + (sqrt 2) * (sqrt ((trace p)*(trace p) - trace (p <> p))) where p = a <> b
jmiszczak/hoqus
Hoqus/Fidelity.hs
mit
1,022
0
13
194
227
123
104
9
1
module Pretty where -- see: http://stackoverflow.com/questions/5929377/format-list-output-in-haskell import Data.List ( transpose, intercalate ) -- a type for fill functions type Filler = Int -> String -> String -- a type for describing table columns data ColDesc t = ColDesc { colTitleFill :: Filler , colTitle :: String , colValueFill :: Filler , colValue :: t -> String } -- functions that fill a string (s) to a given width (n) by adding pad -- character (c) to align left, right, or center fillLeft, fillRight, fillCenter :: a -> Int -> [a] -> [a] fillLeft c n s = s ++ replicate (n - length s) c fillRight c n s = replicate (n - length s) c ++ s fillCenter c n s = replicate l c ++ s ++ replicate r c where x = n - length s l = x `div` 2 r = x - l -- functions that fill with spaces left, right, center :: Int -> String -> String left = fillLeft ' ' right = fillRight ' ' center = fillCenter ' ' -- converts a list of items into a table according to a list -- of column descriptors ppTable :: [ColDesc t] -> [t] -> String ppTable cs ts = let header = map colTitle cs rows = [[colValue c t | c <- cs] | t <- ts] widths = [maximum $ map length col | col <- transpose $ header : rows] separator = intercalate "-+-" [replicate width '-' | width <- widths] fillCols fill cols = intercalate " | " [fill c width col | (c, width, col) <- zip3 cs widths cols] in unlines $ fillCols colTitleFill header : separator : map (fillCols colValueFill) rows renderTable :: [ColDesc t] -> [t] -> IO () renderTable cs = putStrLn . ppTable cs
nyorem/skemmtun
src/Pretty.hs
mit
1,773
0
13
548
529
284
245
29
1
module TestSafePrelude where import Test.HUnit import SafePrelude testSafeHeadForEmptyList :: Test testSafeHeadForEmptyList = TestCase $ assertEqual "Should return Nothing for empty list" Nothing (safeHead ([]::[Int])) testSafeHeadForNonEmptyList :: Test testSafeHeadForNonEmptyList = TestCase $ assertEqual "Should return (Just head) for non empty list" (Just 1) (safeHead ([1]::[Int])) main :: IO Counts main = runTestTT $ TestList [testSafeHeadForEmptyList, testSafeHeadForNonEmptyList]
Muzietto/transformerz
haskell/hunit/TestSafePrelude.hs
mit
572
0
10
137
121
68
53
13
1
-- ref: https://en.wikibooks.org/wiki/Haskell/Arrow_tutorial {-# LANGUAGE Arrows #-} module Main where import Control.Arrow import Control.Monad import qualified Control.Category as Cat import Data.List import Data.Maybe import System.Random -- Arrows which can save state newtype Circuit a b = Circuit { unCircuit :: a -> (Circuit a b, b) } instance Cat.Category Circuit where id = Circuit $ \a -> (Cat.id, a) (.) = dot where (Circuit cir2) `dot` (Circuit cir1) = Circuit $ \a -> let (cir1', b) = cir1 a (cir2', c) = cir2 b in (cir2' `dot` cir1', c) instance Arrow Circuit where arr f = Circuit $ \a -> (arr f, f a) first (Circuit cir) = Circuit $ \(b, d) -> let (cir', c) = cir b in (first cir', (c, d)) runCircuit :: Circuit a b -> [a] -> [b] runCircuit _ [] = [] runCircuit cir (x:xs) = let (cir',x') = unCircuit cir x in x' : runCircuit cir' xs -- or runCircuit cir = snd . mapAccumL unCircuit cir -- | Accumulator that outputs a value determined by the supplied function. accum :: acc -> (a -> acc -> (b, acc)) -> Circuit a b accum acc f = Circuit $ \input -> let (output, acc') = input `f` acc in (accum acc' f, output) -- | Accumulator that outputs the accumulator value. accum' :: b -> (a -> b -> b) -> Circuit a b accum' acc f = accum acc (\a b -> let b' = a `f` b in (b', b')) total :: Num a => Circuit a a total = accum' 0 (+) mean1 :: Fractional a => Circuit a a mean1 = (total &&& (const 1 ^>> total)) >>> arr (uncurry (/)) mean2 :: Fractional a => Circuit a a mean2 = proc value -> do t <- total -< value n <- total -< 1 returnA -< t / n mean3 :: Fractional a => Circuit a a mean3 = proc value -> do (t, n) <- (| (&&&) (total -< value) (total -< 1) |) returnA -< t / n mean4 :: Fractional a => Circuit a a mean4 = proc value -> do (t, n) <- (total -< value) &&& (total -< 1) returnA -< t / n mean5 :: Fractional a => Circuit a a mean5 = proc value -> do rec (lastTot, lastN) <- delay (0,0) -< (tot, n) let (tot, n) = (lastTot + value, lastN + 1) let mean = tot / n returnA -< mean -- proc {- proc is the keyword that introduces arrow notation, and it binds the arrow input to a pattern (value in this example). Arrow statements in a do block take one of these forms: variable binding pattern <- arrow -< pure expression giving arrow input arrow -< pure expression giving arrow input -} instance ArrowLoop Circuit where loop (Circuit cir) = Circuit $ \b -> let (cir', (c,d)) = cir (b,d) in (loop cir', c)
Airtnp/Freshman_Simple_Haskell_Lib
Intro/WIW/Circuit_and_Arrow.hs
mit
2,639
6
14
709
1,038
553
485
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Applicative import Control.Arrow import qualified Data.Attoparsec.Text.Lazy as A import Data.List import Data.Maybe import Data.Monoid import qualified Data.String as S import qualified Data.Text.Lazy as T main :: IO () main = print ("Hi!" :: String) data Term = Var Char | Lam Char Term | App Term Term deriving Show instance S.IsString Term where fromString = parse . T.pack pretty :: Term -> String pretty (Var x) = [x] pretty (Lam x s) = "(\\" ++ [x] ++ ". " ++ pretty s ++ ")" pretty (App s t) = "(" ++ pretty s ++ " " ++ pretty t ++ ")" term :: A.Parser Term term = (parens app <|> parens lam <|> var) where var = Var <$> A.letter lam = Lam <$> (A.char '\\' *> A.letter) <* A.string ". " <*> term app = App <$> term <* A.char ' ' <*> term parens p = id <$> (A.char '(' *> p) <* A.char ')' parse :: T.Text -> Term parse t = case A.parse (term <* A.endOfInput) t of A.Fail _ _ _ -> error "parsing failed" A.Done _ r -> r subst :: (Char, Term) -> Term -> Term subst (x, r) s@(Var y) = if x == y then r else s subst p@(x, _) s@(Lam y t) = if x == y then s else Lam y (subst p t) subst p (App s t) = App (subst p s) (subst p t) leftmostReduction :: Term -> Maybe Term leftmostReduction (Var _) = Nothing leftmostReduction (Lam x s) = fmap (Lam x) $ leftmostReduction s leftmostReduction (App (Lam x s) t) = Just $ subst (x, t) s leftmostReduction (App s t) = case leftmostReduction s of Nothing -> fmap (App s) (leftmostReduction t) Just s' -> Just $ App s' t reduce :: Term -> Term reduce t = if j < 100 then n else error $ "Stopped after 100 reductions: " ++ pretty n where iterations = zip ([1..] :: [Integer]) $ iterate (>>= leftmostReduction) (Just t) (j, Just n) = last $ takeWhile (\(i,m) -> i <= 100 && isJust m) iterations data Signature = SVar String | SFun String [Signature] deriving Eq instance Show Signature where show (SVar c) = c show (SFun n vs) = "(" ++ n ++ " " ++ (intercalate " " $ map show vs) ++ ")" unify :: [(Signature, Signature)] -> Either String (Signature -> Signature) unify = fmap apply . foldrEither (\(s1, s2) sub -> unify' sub s1 s2) (Right emptySub) where unify' :: (String -> Signature) -> Signature -> Signature -> Either String (String -> Signature) unify' sub s1@(SVar v) s2 = if s1' == s1 then extend sub v s2' else unify' sub s1' s2' where s1' = apply sub s1 s2' = apply sub s2 unify' sub s@(SFun _ _) v@(SVar _) = unify' sub v s unify' sub t1@(SFun n1 ss1) t2@(SFun n2 ss2) = if n1 /= n2 then Left $ "Failed to unify " ++ show t1 ++ " with " ++ show t2 else foldrEither (\(s1, s2) s -> unify' s s1 s2) (Right sub) (zip ss1 ss2) foldrEither :: (a -> b -> Either e b) -> Either e b -> [a] -> Either e b foldrEither f = foldr mf where mf _ (Left e) = Left e mf a (Right b) = f a b vars :: Signature -> [String] vars (SVar c) = [c] vars (SFun _ ss) = concatMap vars ss emptySub :: String -> Signature emptySub = SVar extend :: (String -> Signature) -> String -> Signature -> Either String (String -> Signature) extend sub c s = if s == SVar c then Right sub else if c `elem` vars s then Left "cycle" else Right $ (delta c s) `scomp` sub delta c s c' = if c == c' then s else SVar c' scomp sub1 sub2 c = apply sub1 (sub2 c) apply :: (String -> Signature) -> Signature -> Signature apply sub (SVar v) = sub v apply sub (SFun n ss) = SFun n $ map (apply sub) ss data Type = TVar String | TArrow Type Type instance Show Type where show (TVar c) = c show (TArrow t1 t2) = "(" ++ show t1 ++ " -> " ++ show t2 ++ ")" toType :: Signature -> Type toType (SVar s) = TVar s toType (SFun _ (a:b:[])) = TArrow (toType a) (toType b) toType _ = error "unexpected signature" typeEquations :: String -> Term -> [(Signature, Signature)] typeEquations n (Var x) = [(SVar n, SVar $ "T" ++ [x])] typeEquations n (App a b) = typeEquations (n ++ "_l") a ++ typeEquations (n ++ "_r") b ++ [(SVar $ n ++ "_l", SFun "->" [SVar $ n ++ "_r", SVar n])] typeEquations n (Lam x b) = map (replaceBoundVar *** replaceBoundVar) (typeEquations (n ++ "_b") b) ++ [(SVar n, SFun "->" [SVar $ n ++ "_x", SVar $ n ++ "_b"])] where replaceBoundVar = replaceVar ("T" ++ [x]) (n ++ "_x") replaceVar a a' (SVar v) = if v == a then SVar a' else SVar v replaceVar a a' (SFun name ss) = SFun name $ map (replaceVar a a') ss typeOf :: Term -> Either String Type typeOf t = fmap (\u -> toType $ u (SVar "M")) (unify $ typeEquations "M" t) eval :: T.Text -> Either String (Type, Term) eval s = case typeOf t of Left e -> Left e Right ty -> Right (ty, reduce t) where t = parse s -- Testing _I, _K, _S, _Y :: T.Text _I = "(\\a. a)" _K = "(\\a. (\\b. a))" _S = "(\\a. (\\b. (\\c. ((a c) (b c)))))" _Y = "(\\f. ((\\w. (f (w w))) (\\w. (f (w w)))))" (<.>) :: T.Text -> T.Text -> T.Text a <.> b = "(" <> a <> " " <> b <> ")" infixl 6 <.> red :: Int -> Term -> IO () red n t = putStr $ unlines $ fmap show $ (fmap . fmap) pretty $ take n $ iterate (>>= leftmostReduction) (Just t) -- (a, b, c, f) = (SVar "a", SVar "b", SVar "c", \a b -> SFun "f" [a, b])
andregrigon/Lambda
executable/Main.hs
mit
5,389
0
13
1,428
2,503
1,299
1,204
122
11
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} module PostgREST.DbStructure ( getDbStructure , accessibleTables ) where import qualified Hasql.Decoders as HD import qualified Hasql.Encoders as HE import qualified Hasql.Query as H import Control.Applicative import Data.List (elemIndex) import Data.Maybe (fromJust) import Data.Text (split, strip, breakOn, dropAround) import qualified Data.Text as T import qualified Hasql.Session as H import PostgREST.Types import Text.InterpolatedString.Perl6 (q) import GHC.Exts (groupWith) import Protolude import Unsafe (unsafeHead) getDbStructure :: Schema -> H.Session DbStructure getDbStructure schema = do tabs <- H.query () allTables cols <- H.query () $ allColumns tabs syns <- H.query () $ allSynonyms cols rels <- H.query () $ allRelations tabs cols keys <- H.query () $ allPrimaryKeys tabs procs <- H.query schema accessibleProcs let rels' = (addManyToManyRelations . raiseRelations schema syns . addParentRelations . addSynonymousRelations syns) rels cols' = addForeignKeys rels' cols keys' = synonymousPrimaryKeys syns keys return DbStructure { dbTables = tabs , dbColumns = cols' , dbRelations = rels' , dbPrimaryKeys = keys' , dbProcs = procs } decodeTables :: HD.Result [Table] decodeTables = HD.rowsList tblRow where tblRow = Table <$> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.bool decodeColumns :: [Table] -> HD.Result [Column] decodeColumns tables = mapMaybe (columnFromRow tables) <$> HD.rowsList colRow where colRow = (,,,,,,,,,,) <$> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.int4 <*> HD.value HD.bool <*> HD.value HD.text <*> HD.value HD.bool <*> HD.nullableValue HD.int4 <*> HD.nullableValue HD.int4 <*> HD.nullableValue HD.text <*> HD.nullableValue HD.text decodeRelations :: [Table] -> [Column] -> HD.Result [Relation] decodeRelations tables cols = mapMaybe (relationFromRow tables cols) <$> HD.rowsList relRow where relRow = (,,,,,) <$> HD.value HD.text <*> HD.value HD.text <*> HD.value (HD.array (HD.arrayDimension replicateM (HD.arrayValue HD.text))) <*> HD.value HD.text <*> HD.value HD.text <*> HD.value (HD.array (HD.arrayDimension replicateM (HD.arrayValue HD.text))) decodePks :: [Table] -> HD.Result [PrimaryKey] decodePks tables = mapMaybe (pkFromRow tables) <$> HD.rowsList pkRow where pkRow = (,,) <$> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text decodeSynonyms :: [Column] -> HD.Result [(Column,Column)] decodeSynonyms cols = mapMaybe (synonymFromRow cols) <$> HD.rowsList synRow where synRow = (,,,,,) <$> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text accessibleProcs :: H.Query Schema [(Text, ProcDescription)] accessibleProcs = H.statement sql (HE.value HE.text) (map addName <$> HD.rowsList (ProcDescription <$> HD.value HD.text <*> (parseArgs <$> HD.value HD.text) <*> HD.value HD.text)) True where addName :: ProcDescription -> (Text, ProcDescription) addName pd = (pdName pd, pd) parseArgs :: Text -> [PgArg] parseArgs = mapMaybe (parseArg . strip) . split (==',') parseArg :: Text -> Maybe PgArg parseArg a = let (body, def) = breakOn " DEFAULT " a (name, typ) = breakOn " " body in if T.null typ then Nothing else Just $ PgArg (dropAround (== '"') name) (strip typ) (T.null def) sql = [q| SELECT p.proname as "proc_name", pg_get_function_arguments(p.oid) as "args", pg_get_function_result(p.oid) as "return_type" FROM pg_namespace n JOIN pg_proc p ON pronamespace = n.oid WHERE n.nspname = $1|] accessibleTables :: H.Query Schema [Table] accessibleTables = H.statement sql (HE.value HE.text) decodeTables True where sql = [q| select n.nspname as table_schema, relname as table_name, c.relkind = 'r' or (c.relkind IN ('v', 'f')) and (pg_relation_is_updatable(c.oid::regclass, false) & 8) = 8 or (exists ( select 1 from pg_trigger where pg_trigger.tgrelid = c.oid and (pg_trigger.tgtype::integer & 69) = 69) ) as insertable from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.relkind in ('v', 'r', 'm') and n.nspname = $1 and ( pg_has_role(c.relowner, 'USAGE'::text) or has_table_privilege(c.oid, 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES'::text) ) order by relname |] synonymousColumns :: [(Column,Column)] -> [Column] -> [[Column]] synonymousColumns allSyns cols = synCols' where syns = case headMay cols of Just firstCol -> sort $ filter ((== colTable firstCol) . colTable . fst) allSyns Nothing -> [] synCols  = transpose $ map (\c -> map snd $ filter ((== c) . fst) syns) cols synCols' = (filter sameTable . filter matchLength) synCols matchLength cs = length cols == length cs sameTable (c:cs) = all (\cc -> colTable c == colTable cc) (c:cs) sameTable [] = False addForeignKeys :: [Relation] -> [Column] -> [Column] addForeignKeys rels = map addFk where addFk col = col { colFK = fk col } fk col = join $ relToFk col <$> find (lookupFn col) rels lookupFn :: Column -> Relation -> Bool lookupFn c Relation{relColumns=cs, relType=rty} = c `elem` cs && rty==Child relToFk col Relation{relColumns=cols, relFColumns=colsF} = do pos <- elemIndex col cols colF <- atMay colsF pos return $ ForeignKey colF addSynonymousRelations :: [(Column,Column)] -> [Relation] -> [Relation] addSynonymousRelations _ [] = [] addSynonymousRelations syns (rel:rels) = rel : synRelsP ++ synRelsF ++ addSynonymousRelations syns rels where synRelsP = synRels (relColumns rel) (\t cs -> rel{relTable=t,relColumns=cs}) synRelsF = synRels (relFColumns rel) (\t cs -> rel{relFTable=t,relFColumns=cs}) synRels cols mapFn = map (\cs -> mapFn (colTable $ unsafeHead cs) cs) $ synonymousColumns syns cols addParentRelations :: [Relation] -> [Relation] addParentRelations [] = [] addParentRelations (rel@(Relation t c ft fc _ _ _ _):rels) = Relation ft fc t c Parent Nothing Nothing Nothing : rel : addParentRelations rels addManyToManyRelations :: [Relation] -> [Relation] addManyToManyRelations rels = rels ++ addMirrorRelation (mapMaybe link2Relation links) where links = join $ map (combinations 2) $ filter (not . null) $ groupWith groupFn $ filter ( (==Child). relType) rels groupFn :: Relation -> Text groupFn Relation{relTable=Table{tableSchema=s, tableName=t}} = s<>"_"<>t combinations k ns = filter ((k==).length) (subsequences ns) addMirrorRelation [] = [] addMirrorRelation (rel@(Relation t c ft fc _ lt lc1 lc2):rels') = Relation ft fc t c Many lt lc2 lc1 : rel : addMirrorRelation rels' link2Relation [ Relation{relTable=lt, relColumns=lc1, relFTable=t, relFColumns=c}, Relation{ relColumns=lc2, relFTable=ft, relFColumns=fc} ] | lc1 /= lc2 && length lc1 == 1 && length lc2 == 1 = Just $ Relation t c ft fc Many (Just lt) (Just lc1) (Just lc2) | otherwise = Nothing link2Relation _ = Nothing raiseRelations :: Schema -> [(Column,Column)] -> [Relation] -> [Relation] raiseRelations schema syns = map raiseRel where raiseRel rel | tableSchema table == schema = rel | isJust newCols = rel{relFTable=fromJust newTable,relFColumns=fromJust newCols} | otherwise = rel where cols = relFColumns rel table = relFTable rel newCols = listToMaybe $ filter ((== schema) . tableSchema . colTable . unsafeHead) (synonymousColumns syns cols) newTable = (colTable . unsafeHead) <$> newCols synonymousPrimaryKeys :: [(Column,Column)] -> [PrimaryKey] -> [PrimaryKey] synonymousPrimaryKeys _ [] = [] synonymousPrimaryKeys syns (key:keys) = key : newKeys ++ synonymousPrimaryKeys syns keys where keySyns = filter ((\c -> colTable c == pkTable key && colName c == pkName key) . fst) syns newKeys = map ((\c -> PrimaryKey{pkTable=colTable c,pkName=colName c}) . snd) keySyns allTables :: H.Query () [Table] allTables = H.statement sql HE.unit decodeTables True where sql = [q| SELECT n.nspname AS table_schema, c.relname AS table_name, c.relkind = 'r' OR (c.relkind IN ('v','f')) AND (pg_relation_is_updatable(c.oid::regclass, FALSE) & 8) = 8 OR (EXISTS ( SELECT 1 FROM pg_trigger WHERE pg_trigger.tgrelid = c.oid AND (pg_trigger.tgtype::integer & 69) = 69) ) AS insertable FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('v','r','m') AND n.nspname NOT IN ('pg_catalog', 'information_schema') GROUP BY table_schema, table_name, insertable ORDER BY table_schema, table_name |] allColumns :: [Table] -> H.Query () [Column] allColumns tabs = H.statement sql HE.unit (decodeColumns tabs) True where sql = [q| SELECT DISTINCT info.table_schema AS schema, info.table_name AS table_name, info.column_name AS name, info.ordinal_position AS position, info.is_nullable::boolean AS nullable, info.data_type AS col_type, info.is_updatable::boolean AS updatable, info.character_maximum_length AS max_len, info.numeric_precision AS precision, info.column_default AS default_value, array_to_string(enum_info.vals, ',') AS enum FROM ( /* -- CTE based on information_schema.columns to remove the owner filter */ WITH columns AS ( SELECT current_database()::information_schema.sql_identifier AS table_catalog, nc.nspname::information_schema.sql_identifier AS table_schema, c.relname::information_schema.sql_identifier AS table_name, a.attname::information_schema.sql_identifier AS column_name, a.attnum::information_schema.cardinal_number AS ordinal_position, pg_get_expr(ad.adbin, ad.adrelid)::information_schema.character_data AS column_default, CASE WHEN a.attnotnull OR t.typtype = 'd'::"char" AND t.typnotnull THEN 'NO'::text ELSE 'YES'::text END::information_schema.yes_or_no AS is_nullable, CASE WHEN t.typtype = 'd'::"char" THEN CASE WHEN bt.typelem <> 0::oid AND bt.typlen = (-1) THEN 'ARRAY'::text WHEN nbt.nspname = 'pg_catalog'::name THEN format_type(t.typbasetype, NULL::integer) ELSE format_type(a.atttypid, a.atttypmod) END ELSE CASE WHEN t.typelem <> 0::oid AND t.typlen = (-1) THEN 'ARRAY'::text WHEN nt.nspname = 'pg_catalog'::name THEN format_type(a.atttypid, NULL::integer) ELSE format_type(a.atttypid, a.atttypmod) END END::information_schema.character_data AS data_type, information_schema._pg_char_max_length(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS character_maximum_length, information_schema._pg_char_octet_length(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS character_octet_length, information_schema._pg_numeric_precision(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_precision, information_schema._pg_numeric_precision_radix(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_precision_radix, information_schema._pg_numeric_scale(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_scale, information_schema._pg_datetime_precision(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS datetime_precision, information_schema._pg_interval_type(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.character_data AS interval_type, NULL::integer::information_schema.cardinal_number AS interval_precision, NULL::character varying::information_schema.sql_identifier AS character_set_catalog, NULL::character varying::information_schema.sql_identifier AS character_set_schema, NULL::character varying::information_schema.sql_identifier AS character_set_name, CASE WHEN nco.nspname IS NOT NULL THEN current_database() ELSE NULL::name END::information_schema.sql_identifier AS collation_catalog, nco.nspname::information_schema.sql_identifier AS collation_schema, co.collname::information_schema.sql_identifier AS collation_name, CASE WHEN t.typtype = 'd'::"char" THEN current_database() ELSE NULL::name END::information_schema.sql_identifier AS domain_catalog, CASE WHEN t.typtype = 'd'::"char" THEN nt.nspname ELSE NULL::name END::information_schema.sql_identifier AS domain_schema, CASE WHEN t.typtype = 'd'::"char" THEN t.typname ELSE NULL::name END::information_schema.sql_identifier AS domain_name, current_database()::information_schema.sql_identifier AS udt_catalog, COALESCE(nbt.nspname, nt.nspname)::information_schema.sql_identifier AS udt_schema, COALESCE(bt.typname, t.typname)::information_schema.sql_identifier AS udt_name, NULL::character varying::information_schema.sql_identifier AS scope_catalog, NULL::character varying::information_schema.sql_identifier AS scope_schema, NULL::character varying::information_schema.sql_identifier AS scope_name, NULL::integer::information_schema.cardinal_number AS maximum_cardinality, a.attnum::information_schema.sql_identifier AS dtd_identifier, 'NO'::character varying::information_schema.yes_or_no AS is_self_referencing, 'NO'::character varying::information_schema.yes_or_no AS is_identity, NULL::character varying::information_schema.character_data AS identity_generation, NULL::character varying::information_schema.character_data AS identity_start, NULL::character varying::information_schema.character_data AS identity_increment, NULL::character varying::information_schema.character_data AS identity_maximum, NULL::character varying::information_schema.character_data AS identity_minimum, NULL::character varying::information_schema.yes_or_no AS identity_cycle, 'NEVER'::character varying::information_schema.character_data AS is_generated, NULL::character varying::information_schema.character_data AS generation_expression, CASE WHEN c.relkind = 'r'::"char" OR (c.relkind = ANY (ARRAY['v'::"char", 'f'::"char"])) AND pg_column_is_updatable(c.oid::regclass, a.attnum, false) THEN 'YES'::text ELSE 'NO'::text END::information_schema.yes_or_no AS is_updatable FROM pg_attribute a LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum JOIN (pg_class c JOIN pg_namespace nc ON c.relnamespace = nc.oid) ON a.attrelid = c.oid JOIN (pg_type t JOIN pg_namespace nt ON t.typnamespace = nt.oid) ON a.atttypid = t.oid LEFT JOIN (pg_type bt JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid) ON t.typtype = 'd'::"char" AND t.typbasetype = bt.oid LEFT JOIN (pg_collation co JOIN pg_namespace nco ON co.collnamespace = nco.oid) ON a.attcollation = co.oid AND (nco.nspname <> 'pg_catalog'::name OR co.collname <> 'default'::name) WHERE NOT pg_is_other_temp_schema(nc.oid) AND a.attnum > 0 AND NOT a.attisdropped AND (c.relkind = ANY (ARRAY['r'::"char", 'v'::"char", 'f'::"char"])) /*--AND (pg_has_role(c.relowner, 'USAGE'::text) OR has_column_privilege(c.oid, a.attnum, 'SELECT, INSERT, UPDATE, REFERENCES'::text))*/ ) SELECT table_schema, table_name, column_name, ordinal_position, is_nullable, data_type, is_updatable, character_maximum_length, numeric_precision, column_default, udt_name /*-- FROM information_schema.columns*/ FROM columns WHERE table_schema NOT IN ('pg_catalog', 'information_schema') ) AS info LEFT OUTER JOIN ( SELECT n.nspname AS s, t.typname AS n, array_agg(e.enumlabel ORDER BY e.enumsortorder) AS vals FROM pg_type t JOIN pg_enum e ON t.oid = e.enumtypid JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace GROUP BY s,n ) AS enum_info ON (info.udt_name = enum_info.n) ORDER BY schema, position |] columnFromRow :: [Table] -> (Text, Text, Text, Int32, Bool, Text, Bool, Maybe Int32, Maybe Int32, Maybe Text, Maybe Text) -> Maybe Column columnFromRow tabs (s, t, n, pos, nul, typ, u, l, p, d, e) = buildColumn <$> table where buildColumn tbl = Column tbl n pos nul typ u l p d (parseEnum e) Nothing table = find (\tbl -> tableSchema tbl == s && tableName tbl == t) tabs parseEnum :: Maybe Text -> [Text] parseEnum str = fromMaybe [] $ split (==',') <$> str allRelations :: [Table] -> [Column] -> H.Query () [Relation] allRelations tabs cols = H.statement sql HE.unit (decodeRelations tabs cols) True where sql = [q| SELECT ns1.nspname AS table_schema, tab.relname AS table_name, column_info.cols AS columns, ns2.nspname AS foreign_table_schema, other.relname AS foreign_table_name, column_info.refs AS foreign_columns FROM pg_constraint, LATERAL (SELECT array_agg(cols.attname) AS cols, array_agg(cols.attnum) AS nums, array_agg(refs.attname) AS refs FROM ( SELECT unnest(conkey) AS col, unnest(confkey) AS ref) k, LATERAL (SELECT * FROM pg_attribute WHERE attrelid = conrelid AND attnum = col) AS cols, LATERAL (SELECT * FROM pg_attribute WHERE attrelid = confrelid AND attnum = ref) AS refs) AS column_info, LATERAL (SELECT * FROM pg_namespace WHERE pg_namespace.oid = connamespace) AS ns1, LATERAL (SELECT * FROM pg_class WHERE pg_class.oid = conrelid) AS tab, LATERAL (SELECT * FROM pg_class WHERE pg_class.oid = confrelid) AS other, LATERAL (SELECT * FROM pg_namespace WHERE pg_namespace.oid = other.relnamespace) AS ns2 WHERE confrelid != 0 ORDER BY (conrelid, column_info.nums) |] relationFromRow :: [Table] -> [Column] -> (Text, Text, [Text], Text, Text, [Text]) -> Maybe Relation relationFromRow allTabs allCols (rs, rt, rcs, frs, frt, frcs) = Relation <$> table <*> cols <*> tableF <*> colsF <*> pure Child <*> pure Nothing <*> pure Nothing <*> pure Nothing where findTable s t = find (\tbl -> tableSchema tbl == s && tableName tbl == t) allTabs findCol s t c = find (\col -> tableSchema (colTable col) == s && tableName (colTable col) == t && colName col == c) allCols table = findTable rs rt tableF = findTable frs frt cols = mapM (findCol rs rt) rcs colsF = mapM (findCol frs frt) frcs allPrimaryKeys :: [Table] -> H.Query () [PrimaryKey] allPrimaryKeys tabs = H.statement sql HE.unit (decodePks tabs) True where sql = [q| /* -- CTE to replace information_schema.table_constraints to remove owner limit */ WITH tc AS ( SELECT current_database()::information_schema.sql_identifier AS constraint_catalog, nc.nspname::information_schema.sql_identifier AS constraint_schema, c.conname::information_schema.sql_identifier AS constraint_name, current_database()::information_schema.sql_identifier AS table_catalog, nr.nspname::information_schema.sql_identifier AS table_schema, r.relname::information_schema.sql_identifier AS table_name, CASE c.contype WHEN 'c'::"char" THEN 'CHECK'::text WHEN 'f'::"char" THEN 'FOREIGN KEY'::text WHEN 'p'::"char" THEN 'PRIMARY KEY'::text WHEN 'u'::"char" THEN 'UNIQUE'::text ELSE NULL::text END::information_schema.character_data AS constraint_type, CASE WHEN c.condeferrable THEN 'YES'::text ELSE 'NO'::text END::information_schema.yes_or_no AS is_deferrable, CASE WHEN c.condeferred THEN 'YES'::text ELSE 'NO'::text END::information_schema.yes_or_no AS initially_deferred FROM pg_namespace nc, pg_namespace nr, pg_constraint c, pg_class r WHERE nc.oid = c.connamespace AND nr.oid = r.relnamespace AND c.conrelid = r.oid AND (c.contype <> ALL (ARRAY['t'::"char", 'x'::"char"])) AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid) /*--AND (pg_has_role(r.relowner, 'USAGE'::text) OR has_table_privilege(r.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) OR has_any_column_privilege(r.oid, 'INSERT, UPDATE, REFERENCES'::text))*/ UNION ALL SELECT current_database()::information_schema.sql_identifier AS constraint_catalog, nr.nspname::information_schema.sql_identifier AS constraint_schema, (((((nr.oid::text || '_'::text) || r.oid::text) || '_'::text) || a.attnum::text) || '_not_null'::text)::information_schema.sql_identifier AS constraint_name, current_database()::information_schema.sql_identifier AS table_catalog, nr.nspname::information_schema.sql_identifier AS table_schema, r.relname::information_schema.sql_identifier AS table_name, 'CHECK'::character varying::information_schema.character_data AS constraint_type, 'NO'::character varying::information_schema.yes_or_no AS is_deferrable, 'NO'::character varying::information_schema.yes_or_no AS initially_deferred FROM pg_namespace nr, pg_class r, pg_attribute a WHERE nr.oid = r.relnamespace AND r.oid = a.attrelid AND a.attnotnull AND a.attnum > 0 AND NOT a.attisdropped AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid) /*--AND (pg_has_role(r.relowner, 'USAGE'::text) OR has_table_privilege(r.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) OR has_any_column_privilege(r.oid, 'INSERT, UPDATE, REFERENCES'::text))*/ ), /* -- CTE to replace information_schema.key_column_usage to remove owner limit */ kc AS ( SELECT current_database()::information_schema.sql_identifier AS constraint_catalog, ss.nc_nspname::information_schema.sql_identifier AS constraint_schema, ss.conname::information_schema.sql_identifier AS constraint_name, current_database()::information_schema.sql_identifier AS table_catalog, ss.nr_nspname::information_schema.sql_identifier AS table_schema, ss.relname::information_schema.sql_identifier AS table_name, a.attname::information_schema.sql_identifier AS column_name, (ss.x).n::information_schema.cardinal_number AS ordinal_position, CASE WHEN ss.contype = 'f'::"char" THEN information_schema._pg_index_position(ss.conindid, ss.confkey[(ss.x).n]) ELSE NULL::integer END::information_schema.cardinal_number AS position_in_unique_constraint FROM pg_attribute a, ( SELECT r.oid AS roid, r.relname, r.relowner, nc.nspname AS nc_nspname, nr.nspname AS nr_nspname, c.oid AS coid, c.conname, c.contype, c.conindid, c.confkey, c.confrelid, information_schema._pg_expandarray(c.conkey) AS x FROM pg_namespace nr, pg_class r, pg_namespace nc, pg_constraint c WHERE nr.oid = r.relnamespace AND r.oid = c.conrelid AND nc.oid = c.connamespace AND (c.contype = ANY (ARRAY['p'::"char", 'u'::"char", 'f'::"char"])) AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid)) ss WHERE ss.roid = a.attrelid AND a.attnum = (ss.x).x AND NOT a.attisdropped /*--AND (pg_has_role(ss.relowner, 'USAGE'::text) OR has_column_privilege(ss.roid, a.attnum, 'SELECT, INSERT, UPDATE, REFERENCES'::text))*/ ) SELECT kc.table_schema, kc.table_name, kc.column_name FROM /* --information_schema.table_constraints tc, --information_schema.key_column_usage kc */ tc, kc WHERE tc.constraint_type = 'PRIMARY KEY' AND kc.table_name = tc.table_name AND kc.table_schema = tc.table_schema AND kc.constraint_name = tc.constraint_name AND kc.table_schema NOT IN ('pg_catalog', 'information_schema') |] pkFromRow :: [Table] -> (Schema, Text, Text) -> Maybe PrimaryKey pkFromRow tabs (s, t, n) = PrimaryKey <$> table <*> pure n where table = find (\tbl -> tableSchema tbl == s && tableName tbl == t) tabs allSynonyms :: [Column] -> H.Query () [(Column,Column)] allSynonyms cols = H.statement sql HE.unit (decodeSynonyms cols) True where -- query explanation at https://gist.github.com/ruslantalpa/2eab8c930a65e8043d8f sql = [q| with view_columns as ( select c.oid as view_oid, a.attname::information_schema.sql_identifier as column_name from pg_attribute a join pg_class c on a.attrelid = c.oid join pg_namespace nc on c.relnamespace = nc.oid where not pg_is_other_temp_schema(nc.oid) and a.attnum > 0 and not a.attisdropped and (c.relkind = 'v'::"char") and nc.nspname not in ('information_schema', 'pg_catalog') ), view_column_usage as ( select distinct v.oid as view_oid, nv.nspname::information_schema.sql_identifier as view_schema, v.relname::information_schema.sql_identifier as view_name, nt.nspname::information_schema.sql_identifier as table_schema, t.relname::information_schema.sql_identifier as table_name, a.attname::information_schema.sql_identifier as column_name, pg_get_viewdef(v.oid)::information_schema.character_data as view_definition from pg_namespace nv join pg_class v on nv.oid = v.relnamespace join pg_depend dv on v.oid = dv.refobjid join pg_depend dt on dv.objid = dt.objid join pg_class t on dt.refobjid = t.oid join pg_namespace nt on t.relnamespace = nt.oid join pg_attribute a on t.oid = a.attrelid and dt.refobjsubid = a.attnum where nv.nspname not in ('information_schema', 'pg_catalog') and v.relkind = 'v'::"char" and dv.refclassid = 'pg_class'::regclass::oid and dv.classid = 'pg_rewrite'::regclass::oid and dv.deptype = 'i'::"char" and dv.refobjid <> dt.refobjid and dt.classid = 'pg_rewrite'::regclass::oid and dt.refclassid = 'pg_class'::regclass::oid and (t.relkind = any (array['r'::"char", 'v'::"char", 'f'::"char"])) ), candidates as ( select vcu.*, ( select case when match is not null then coalesce(match[8], match[7], match[4]) end from regexp_matches( CONCAT('SELECT ', SPLIT_PART(vcu.view_definition, 'SELECT', 2)), CONCAT('SELECT.*?((',vcu.table_name,')|(\w+))\.(', vcu.column_name, ')(\s+AS\s+("([^"]+)"|([^, \n\t]+)))?.*?FROM.*?',vcu.table_schema,'\.(\2|',vcu.table_name,'\s+(as\s)?\3)'), 'nsi' ) match ) as view_column_name from view_column_usage as vcu ) select c.table_schema, c.table_name, c.column_name as table_column_name, c.view_schema, c.view_name, c.view_column_name from view_columns as vc, candidates as c where vc.view_oid = c.view_oid and vc.column_name = c.view_column_name order by c.view_schema, c.view_name, c.table_name, c.view_column_name |] synonymFromRow :: [Column] -> (Text,Text,Text,Text,Text,Text) -> Maybe (Column,Column) synonymFromRow allCols (s1,t1,c1,s2,t2,c2) = (,) <$> col1 <*> col2 where col1 = findCol s1 t1 c1 col2 = findCol s2 t2 c2 findCol s t c = find (\col -> (tableSchema . colTable) col == s && (tableName . colTable) col == t && colName col == c) allCols
NotBrianZach/postgrest
src/PostgREST/DbStructure.hs
mit
31,146
0
19
8,472
3,968
2,090
1,878
208
3
module GHCJS.DOM.SVGViewElement ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGViewElement.hs
mit
44
0
3
7
10
7
3
1
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-spend.html module Stratosphere.ResourceProperties.BudgetsBudgetSpend where import Stratosphere.ResourceImports -- | Full data type definition for BudgetsBudgetSpend. See -- 'budgetsBudgetSpend' for a more convenient constructor. data BudgetsBudgetSpend = BudgetsBudgetSpend { _budgetsBudgetSpendAmount :: Val Double , _budgetsBudgetSpendUnit :: Val Text } deriving (Show, Eq) instance ToJSON BudgetsBudgetSpend where toJSON BudgetsBudgetSpend{..} = object $ catMaybes [ (Just . ("Amount",) . toJSON) _budgetsBudgetSpendAmount , (Just . ("Unit",) . toJSON) _budgetsBudgetSpendUnit ] -- | Constructor for 'BudgetsBudgetSpend' containing required fields as -- arguments. budgetsBudgetSpend :: Val Double -- ^ 'bbsAmount' -> Val Text -- ^ 'bbsUnit' -> BudgetsBudgetSpend budgetsBudgetSpend amountarg unitarg = BudgetsBudgetSpend { _budgetsBudgetSpendAmount = amountarg , _budgetsBudgetSpendUnit = unitarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-spend.html#cfn-budgets-budget-spend-amount bbsAmount :: Lens' BudgetsBudgetSpend (Val Double) bbsAmount = lens _budgetsBudgetSpendAmount (\s a -> s { _budgetsBudgetSpendAmount = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-spend.html#cfn-budgets-budget-spend-unit bbsUnit :: Lens' BudgetsBudgetSpend (Val Text) bbsUnit = lens _budgetsBudgetSpendUnit (\s a -> s { _budgetsBudgetSpendUnit = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/BudgetsBudgetSpend.hs
mit
1,728
0
13
220
265
151
114
29
1
module Pos.Infra.Binary () where import Pos.Infra.Binary.DHTModel ()
input-output-hk/pos-haskell-prototype
infra/src/Pos/Infra/Binary.hs
mit
80
0
4
18
20
14
6
2
0
module Text.Spoonerize ( spoonerize ) where import System.Random import Data.Array.IO import Control.Monad import Data.List (sort) import Data.Char (isLower, toLower, toUpper) type Sequence = Int type Word = String type IsSpoonerizable = Bool data WordInfo = WordInfo Sequence Word IsSpoonerizable deriving (Show) instance Ord WordInfo where (WordInfo seq1 _ _) `compare` (WordInfo seq2 _ _) = seq1 `compare` seq2 instance Eq WordInfo where (WordInfo seq1 word1 bool1) == (WordInfo seq2 word2 bool2) = seq1 == seq2 && word1 == word2 && bool1 == bool2 type AnnotatedSentence = [WordInfo] alphabet = ['A'..'Z'] ++ ['a'..'z'] vowels = "AEIOUaeiou" -- | Randomly shuffle a list -- /O(N)/ -- From http://www.haskell.org/haskellwiki/Random_shuffle#Imperative_algorithm shuffle :: [a] -> IO [a] shuffle xs = do ar <- newArray n xs forM [1..n] $ \i -> do j <- randomRIO (i,n) vi <- readArray ar i vj <- readArray ar j writeArray ar j vi return vj where n = length xs newArray :: Int -> [a] -> IO (IOArray Int a) newArray n = newListArray (1, n) annotatedSentence :: String -> AnnotatedSentence annotatedSentence sent = map (\(x, y, z) -> (WordInfo x y z)) wordTuples where sentence = words sent wordTuples = zip3 [1..] sentence $ cycle [True] caseFunction :: Char -> (Char -> Char) caseFunction char = if isLower char then toLower else toUpper isTooShort :: Word -> Bool isTooShort word = length word <= 1 hasLeadingVowel :: Word -> Bool hasLeadingVowel word = not (null word) && head word `elem` vowels isSpoonerizableWord :: Word -> Bool isSpoonerizableWord word = not (isTooShort word) && not (hasLeadingVowel word) && not (isAllConsonants word) markSpoonerizableWords :: AnnotatedSentence -> AnnotatedSentence markSpoonerizableWords = map (\(WordInfo x y z) -> (WordInfo x y (z && isSpoonerizableWord y))) spoonerizableWords :: AnnotatedSentence -> AnnotatedSentence spoonerizableWords = filter (\(WordInfo _ _ isSpoonerizable) -> isSpoonerizable) wordBeginning :: String -> String wordBeginning = takeWhile isConsonant wordEnding :: String -> String wordEnding = dropWhile isConsonant isConsonant :: Char -> Bool isConsonant l = l `notElem` vowels isAllConsonants :: Word -> Bool isAllConsonants = all isConsonant applyCase :: Char -> Char -> Char applyCase sourceCharacter destCharacter = (caseFunction sourceCharacter) destCharacter swapWordCase :: (Word, Word) -> (Word, Word) swapWordCase (wordA, wordB) = ([newLtrA] ++ tail wordA, [newLtrB] ++ tail wordB) where firstLtrA = head wordA firstLtrB = head wordB newLtrA = applyCase firstLtrB firstLtrA newLtrB = applyCase firstLtrA firstLtrB swapWordBeginnings :: (Word, Word) -> (Word, Word) swapWordBeginnings (wordA, wordB) = (wordBeginning bCaseFlipped ++ wordEnding wordA, wordBeginning aCaseFlipped ++ wordEnding wordB) where (aCaseFlipped, bCaseFlipped) = swapWordCase (wordA, wordB) spoonerizeWords :: (WordInfo, WordInfo) -> (WordInfo, WordInfo) spoonerizeWords (WordInfo seqA wordA boolA, WordInfo seqB wordB boolB) = (WordInfo seqA newWordA boolA, WordInfo seqB newWordB boolB) where (newWordA, newWordB) = swapWordBeginnings(wordA, wordB) wordSequenceNumbers :: [WordInfo] -> [Int] wordSequenceNumbers = map (\(WordInfo sequenceNumber _ _) -> sequenceNumber) substituteWords :: ([WordInfo], WordInfo, WordInfo) -> String substituteWords (oldsentence, toSpoonerizeA, toSpoonerizeB) = unwords $ map (\(WordInfo _ word _) -> word) orderedWords where sequencesToReplace = wordSequenceNumbers [spoonerizedA, spoonerizedB] minusSpoonerized = filter (\(WordInfo seq _ _) -> (seq `notElem` sequencesToReplace)) oldsentence (spoonerizedA, spoonerizedB) = spoonerizeWords(toSpoonerizeA, toSpoonerizeB) newSentence = minusSpoonerized ++ [spoonerizedA, spoonerizedB] orderedWords = sort newSentence spoonerize :: String -> IO String spoonerize str = let markedWords = markSpoonerizableWords $ annotatedSentence str in do shuffled <- shuffle $ spoonerizableWords markedWords let [toSpoonerizeA, toSpoonerizeB] = take 2 shuffled in return $ substituteWords(markedWords, toSpoonerizeA, toSpoonerizeB)
jsl/spoonerize
Text/Spoonerize.hs
mit
4,556
0
13
1,062
1,401
748
653
100
2
{-# LANGUAGE FlexibleContexts #-} module Plots.Theme where import Diagrams.Prelude import Diagrams.TwoD.Text import Plots import Plots.Axis.Line import Plots.Style import Control.Monad.Trans.State.Lazy publishableTheme :: Control.Monad.Trans.State.Lazy.StateT (Axis b V2 Double) Identity () publishableTheme = do -- Grid lines. hideGridLines -- Axes. xAxis . axisLineType .= MiddleAxisLine yAxis . axisLineType .= LeftAxisLine yAxis . axisLineStyle .= mempty # lwO 1 xAxis . axisLineStyle .= mempty # lwO 1 -- Ticks. hide (xAxis . minorTicks) hide (yAxis . minorTicks) xAxis . majorTicksAlignment .= outsideTicks yAxis . majorTicksAlignment .= outsideTicks xAxis . majorTicksStyle .= mempty # lwO 1 yAxis . majorTicksStyle .= mempty # lwO 1 -- Line style. lineStyle . _lineWidth .= 1 lineStyle . _lineCap .= LineCapSquare lineStyle . _lineJoin .= LineJoinBevel -- Bar style. --areaStyle .= (mempty # fc black # lc black) publishableFont :: Control.Monad.Trans.State.Lazy.StateT (Axis b V2 Double) Identity () publishableFont = do -- Fonts. axisLabelStyle &= do _fontSize .= (output 6.45) -- 8pt font _font .= Just "Arial" tickLabelStyle &= do _fontSize .= (output 5.63) -- 7pt font _font .= Just "Arial"
GregorySchwartz/dotfiles
.config/diagrams/plot-theme/src/Plots/Theme.hs
gpl-2.0
1,336
0
12
303
357
182
175
-1
-1
{- | Module : $Header$ Description : Generic Prover GUI. Copyright : (c) Klaus Luettich, Rainer Grabbe, Uni Bremen 2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : needs POSIX Generic GUI for automatic theorem provers. Based upon former SPASS Prover GUI. -} module GUI.HTkGenericATP (genericATPgui) where import Logic.Prover import qualified Common.AS_Annotation as AS_Anno import qualified Data.Map as Map import Common.Utils (getEnvSave, readMaybe) import Common.Result import Data.List import Data.Maybe import qualified Control.Exception as Exception import qualified Control.Concurrent as Conc import HTk.Toolkit.SpinButton import HTk.Toolkit.Separator import HTk.Devices.XSelection import HTk.Widgets.Space import GUI.Utils import GUI.HTkUtils hiding (createTextSaveDisplay, createTextDisplay) import Interfaces.GenericATPState import Proofs.BatchProcessing {- | Utility function to set the time limit of a Config. For values <= 0 a default value is used. -} setTimeLimit :: Int -> GenericConfig proofTree -> GenericConfig proofTree setTimeLimit n c = c { timeLimit = if n > 0 then Just n else Nothing } {- | Utility function to set the extra options of a Config. -} setExtraOpts :: [String] -> GenericConfig proofTree -> GenericConfig proofTree setExtraOpts opts c = c { extraOpts = opts } -- ** Constants -- ** Defining the view {- | Colors used by the GUI to indicate the status of a goal. -} data ProofStatusColour -- | Proved = Green -- | Proved, but theory is inconsistent | Brown -- | Disproved | Red -- | Open | Black -- | Running | Blue deriving (Bounded, Enum, Show) {- | Generates a ('ProofStatusColour', 'String') tuple representing a Proved proof status. -} statusProved :: (ProofStatusColour, String) statusProved = (Green, "Proved") {- | Generates a ('ProofStatusColour', 'String') tuple representing a Proved (but inconsistent) proof status. -} statusProvedButInconsistent :: (ProofStatusColour, String) statusProvedButInconsistent = (Brown, "Proved/Inconsistent") {- | Generates a ('ProofStatusColour', 'String') tuple representing a Disproved proof status. -} statusDisproved :: (ProofStatusColour, String) statusDisproved = (Red, "Disproved") {- | Generates a ('ProofStatusColour', 'String') tuple representing an Open proof status. -} statusOpen :: (ProofStatusColour, String) statusOpen = (Black, "Open") {- | Generates a ('ProofStatusColour', 'String') tuple representing an Open proof status in case the time limit has been exceeded. -} statusOpenTExceeded :: (ProofStatusColour, String) statusOpenTExceeded = (Black, "Open (Time is up!)") {- | Generates a ('ProofStatusColour', 'String') tuple representing a Running proof status. -} statusRunning :: (ProofStatusColour, String) statusRunning = (Blue, "Running") {- | Converts a 'ProofStatus' into a ('ProofStatusColour', 'String') tuple to be displayed by the GUI. -} toGuiStatus :: GenericConfig proofTree -- ^ current prover configuration -> ProofStatus a -- ^ status to convert -> (ProofStatusColour, String) toGuiStatus cf st = case goalStatus st of Proved c -> if c then statusProved else statusProvedButInconsistent Disproved -> statusDisproved _ -> if timeLimitExceeded cf then statusOpenTExceeded else statusOpen -- | stores widgets of an options frame and the frame itself data OpFrame = OpFrame { ofFrame :: Frame , ofTimeSpinner :: SpinButton , ofTimeEntry :: Entry Int , ofOptionsEntry :: Entry String } {- | Generates a list of 'GUI.HTkUtils.LBGoalView' representations of all goals from a 'GenericATPState.GenericState'. -} goalsView :: GenericState sign sentence proofTree pst -- ^ current global prover state -> [LBGoalView] -- ^ resulting ['LBGoalView'] list goalsView s = map ((\ g -> let cfg = Map.lookup g (configsMap s) statind = maybe LBIndicatorOpen (indicatorFromProofStatus . proofStatus) cfg in LBGoalView {statIndicator = statind, goalDescription = g}) . AS_Anno.senAttr) $ goalsList s -- * GUI Implementation -- ** Utility Functions {- | Retrieves the value of the time limit 'Entry'. Ignores invalid input. -} getValueSafe :: Int -- ^ default time limt -> Entry Int -- ^ time limit 'Entry' -> IO Int -- ^ user-requested time limit or default for errors getValueSafe defaultTimeLimit timeEntry = Exception.catch (getValue timeEntry :: IO Int) $ \ e -> do putStrLn $ "Warning: Error " ++ show (e :: Exception.SomeException) ++ " was ignored" return defaultTimeLimit {- | reads passed ENV-variable and if it exists and has an Int-value this value is returned otherwise the value of 'batchTimeLimit' is returned. -} getBatchTimeLimit :: String -- ^ ENV-variable containing batch time limit -> IO Int getBatchTimeLimit env = getEnvSave batchTimeLimit env readMaybe {- | Text displayed by the batch mode window. -} batchInfoText :: Int -- ^ batch time limt -> Int -- ^ total number of goals -> Int -- ^ number of that have been processed -> String batchInfoText tl gTotal gDone = let totalSecs = (gTotal - gDone) * tl (remMins, secs) = divMod totalSecs 60 (hours, mins) = divMod remMins 60 in "Batch mode running.\n" ++ show gDone ++ "/" ++ show gTotal ++ " goals processed.\n" ++ "At most " ++ show hours ++ "h " ++ show mins ++ "m " ++ show secs ++ "s remaining." -- ** Callbacks {- | Updates the display of the status of the current goal. -} updateDisplay :: GenericState sign sentence proofTree pst -- ^ current global prover state -> Bool -- ^ set to 'True' if you want the 'ListBox' to be updated -> ListBox String -- ^ 'ListBox' displaying the status of all goals (see 'goalsView') -> Label {- ^ 'Label' displaying the status of the currently selected goal (see 'toGuiStatus') -} -> Entry Int -- ^ 'Entry' containing the time limit of the current goal -> Entry String -- ^ 'Entry' containing the extra options -> ListBox String -- ^ 'ListBox' displaying all axioms used to prove a goal (if any) -> IO () updateDisplay st updateLb goalsLb statusLabel timeEntry optionsEntry axiomsLb = {- the code in comments only works with an updated uni version that will be installed when switching to ghc-6.6.1 -} do when updateLb (do (offScreen, _) <- view Vertical goalsLb populateGoalsListBox goalsLb (goalsView st) moveto Vertical goalsLb offScreen ) maybe (return ()) (\ go -> let mprfst = Map.lookup go (configsMap st) cf = Map.findWithDefault (error "GUI.GenericATP.updateDisplay") go (configsMap st) t' = fromMaybe guiDefaultTimeLimit (timeLimit cf) opts' = unwords (extraOpts cf) (color, label) = maybe statusOpen (toGuiStatus cf . proofStatus) mprfst usedAxs = maybe [] (usedAxioms . proofStatus) mprfst in do statusLabel # text label statusLabel # foreground (show color) timeEntry # value t' optionsEntry # value opts' axiomsLb # value (usedAxs :: [String]) return ()) (currentGoal st) newOptionsFrame :: Container par => par -- ^ the parent container -> (Entry Int -> Spin -> IO a) -- ^ Function called by pressing one spin button -> Bool -- ^ extra options input line -> IO OpFrame newOptionsFrame con updateFn isExtraOps = do right <- newFrame con [] -- contents of newOptionsFrame l1 <- newLabel right [text "Options:"] pack l1 [Anchor NorthWest] opFrame <- newFrame right [] pack opFrame [Expand On, Fill X, Anchor North] spacer <- newLabel opFrame [text " "] pack spacer [Side AtLeft] opFrame2 <- newVBox opFrame [] pack opFrame2 [Expand On, Fill X, Anchor NorthWest] timeLimitFrame <- newFrame opFrame2 [] pack timeLimitFrame [Expand On, Fill X, Anchor West] l2 <- newLabel timeLimitFrame [text "TimeLimit"] pack l2 [Side AtLeft] -- extra HBox for time limit display timeLimitLine <- newHBox timeLimitFrame [] pack timeLimitLine [Expand On, Side AtRight, Anchor East] timeEntry <- newEntry timeLimitLine [width 18, value guiDefaultTimeLimit] pack (timeEntry :: Entry Int) [] timeSpinner <- newSpinButton timeLimitLine (updateFn timeEntry) [] pack timeSpinner [] l3 <- newLabel opFrame2 [text "Extra Options:"] when isExtraOps $ pack l3 [Anchor West] optionsEntry <- newEntry opFrame2 [width 37] when isExtraOps $ pack (optionsEntry :: Entry String) [Fill X, PadX (cm 0.1)] return OpFrame { ofFrame = right , ofTimeSpinner = timeSpinner , ofTimeEntry = timeEntry , ofOptionsEntry = optionsEntry } -- ** Main GUI {- | Invokes the prover GUI. Users may start the batch prover run on all goals, or use a detailed GUI for proving each goal manually. -} genericATPgui :: (Ord proofTree, Ord sentence) => ATPFunctions sign sentence mor proofTree pst -- ^ prover specific functions -> Bool -- ^ prover supports extra options -> String -- ^ prover name -> String -- ^ theory name -> Theory sign sentence proofTree -- ^ theory with signature and sentences -> [FreeDefMorphism sentence mor] -- ^ freeness constraints -> proofTree -- ^ initial empty proofTree -> IO [ProofStatus proofTree] -- ^ proof status for each goal genericATPgui atpFun isExtraOptions prName thName th freedefs pt = do -- create initial backing data structure let initState = initialGenericState prName (initialProverState atpFun) (atpTransSenName atpFun) th freedefs pt stateMVar <- Conc.newMVar initState batchTLimit <- getBatchTimeLimit $ batchTimeEnv atpFun -- main window main <- createToplevel [text $ thName ++ " - " ++ prName ++ " Prover"] pack main [Expand On, Fill Both] -- VBox for the whole window b <- newVBox main [] pack b [Expand On, Fill Both] -- HBox for the upper part (goals on the left, options/results on the right) b2 <- newHBox b [] pack b2 [Expand On, Fill Both] -- left frame (goals) left <- newFrame b2 [] pack left [Expand On, Fill Both] b3 <- newVBox left [] pack b3 [Expand On, Fill Both] l0 <- newLabel b3 [text "Goals:"] pack l0 [Anchor NorthWest] lbFrame <- newFrame b3 [] pack lbFrame [Expand On, Fill Both] lb <- newListBox lbFrame [bg "white", exportSelection False, selectMode Single, height 15] :: IO (ListBox String) pack lb [Expand On, Side AtLeft, Fill Both] sb <- newScrollBar lbFrame [] pack sb [Expand On, Side AtRight, Fill Y, Anchor West] lb # scrollbar Vertical sb -- right frame (options/results) OpFrame { ofFrame = right , ofTimeSpinner = timeSpinner , ofTimeEntry = timeEntry , ofOptionsEntry = optionsEntry} <- newOptionsFrame b2 (\ timeEntry sp -> synchronize main (do st <- Conc.readMVar stateMVar maybe noGoalSelected (\ goal -> do curEntTL <- getValueSafe guiDefaultTimeLimit timeEntry s <- Conc.takeMVar stateMVar let sEnt = s {configsMap = adjustOrSetConfig (setTimeLimit curEntTL) prName goal pt (configsMap s)} cfg = getConfig prName goal pt (configsMap sEnt) t = timeLimit cfg t' = (case sp of Up -> maybe (guiDefaultTimeLimit + 10) (+ 10) t _ -> maybe (guiDefaultTimeLimit - 10) (subtract 10) t) s' = sEnt {configsMap = adjustOrSetConfig (setTimeLimit t') prName goal pt (configsMap sEnt)} Conc.putMVar stateMVar s' timeEntry # value (fromMaybe guiDefaultTimeLimit $ timeLimit $ getConfig prName goal pt $ configsMap s') done) (currentGoal st))) isExtraOptions pack right [Expand On, Fill Both, Anchor NorthWest] -- buttons for options buttonsHb1 <- newHBox right [] pack buttonsHb1 [Anchor NorthEast] saveProbButton <- newButton buttonsHb1 [text $ "Save " ++ removeFirstDot (problemOutput $ fileExtensions atpFun) ++ " File"] pack saveProbButton [Side AtLeft] proveButton <- newButton buttonsHb1 [text "Prove"] pack proveButton [Side AtRight] -- result frame resultFrame <- newFrame right [] pack resultFrame [Expand On, Fill Both] l4 <- newLabel resultFrame [text ("Results:" ++ replicate 70 ' ')] pack l4 [Anchor NorthWest] spacer <- newLabel resultFrame [text " "] pack spacer [Side AtLeft] resultContentBox <- newHBox resultFrame [] pack resultContentBox [Expand On, Anchor West, Fill Both] -- labels on the left side rc1 <- newVBox resultContentBox [] pack rc1 [Expand Off, Anchor North] l5 <- newLabel rc1 [text "Status"] pack l5 [Anchor West] l6 <- newLabel rc1 [text "Used Axioms"] pack l6 [Anchor West] -- contents on the right side rc2 <- newVBox resultContentBox [] pack rc2 [Expand On, Fill Both, Anchor North] statusLabel <- newLabel rc2 [text " -- "] pack statusLabel [Anchor West] axiomsFrame <- newFrame rc2 [] pack axiomsFrame [Expand On, Anchor West, Fill Both] axiomsLb <- newListBox axiomsFrame [value ([] :: [String]), bg "white", exportSelection False, selectMode Browse, height 6, width 19] :: IO (ListBox String) pack axiomsLb [Side AtLeft, Expand On, Fill Both] axiomsSb <- newScrollBar axiomsFrame [] pack axiomsSb [Side AtRight, Fill Y, Anchor West] axiomsLb # scrollbar Vertical axiomsSb detailsButton <- newButton resultFrame [text "Show Details"] pack detailsButton [Anchor NorthEast] -- separator sp1 <- newSpace b (cm 0.15) [] pack sp1 [Expand Off, Fill X, Side AtBottom] newHSeparator b sp2 <- newSpace b (cm 0.15) [] pack sp2 [Expand Off, Fill X, Side AtBottom] -- batch mode frame batch <- newFrame b [] pack batch [Expand Off, Fill X] batchTitle <- newLabel batch [text $ prName ++ " Batch Mode:"] pack batchTitle [Side AtTop] batchIFrame <- newFrame batch [] pack batchIFrame [Expand On, Fill X] batchRight <- newVBox batchIFrame [] pack batchRight [Expand On, Fill X, Side AtRight] batchBtnBox <- newHBox batchRight [] pack batchBtnBox [Expand On, Fill X, Side AtRight] stopBatchButton <- newButton batchBtnBox [text "Stop"] pack stopBatchButton [] runBatchButton <- newButton batchBtnBox [text "Run"] pack runBatchButton [] batchSpacer <- newSpace batchRight (pp 150) [orient Horizontal] pack batchSpacer [Side AtRight] batchStatusLabel <- newLabel batchRight [text "\n\n"] pack batchStatusLabel [] OpFrame { ofFrame = batchLeft , ofTimeSpinner = batchTimeSpinner , ofTimeEntry = batchTimeEntry , ofOptionsEntry = batchOptionsEntry} <- newOptionsFrame batchIFrame (\ tEntry sp -> synchronize main (do curEntTL <- getValueSafe batchTLimit tEntry let t' = case sp of Up -> curEntTL + 10 _ -> max batchTLimit (curEntTL - 10) tEntry # value t' done)) isExtraOptions pack batchLeft [Expand On, Fill X, Anchor NorthWest, Side AtLeft] batchGoal <- newHBox batch [] pack batchGoal [Expand On, Fill X, Anchor West, Side AtBottom] batchCurrentGoalTitle <- newLabel batchGoal [text "Current goal:"] pack batchCurrentGoalTitle [] batchCurrentGoalLabel <- newLabel batchGoal [text "--"] pack batchCurrentGoalLabel [] saveProblem_batch <- createTkVariable False saveProblem_batch_checkBox <- newCheckButton batchLeft [variable saveProblem_batch, text $ "Save " ++ removeFirstDot (problemOutput $ fileExtensions atpFun)] enableSaveCheckBox <- getEnvSave False "HETS_ENABLE_BATCH_SAVE" readMaybe when enableSaveCheckBox $ pack saveProblem_batch_checkBox [Expand Off, Fill None, Side AtBottom] batchTimeEntry # value batchTLimit -- separator 2 sp1_2 <- newSpace b (cm 0.15) [] pack sp1_2 [Expand Off, Fill X, Side AtBottom] newHSeparator b sp2_2 <- newSpace b (cm 0.15) [] pack sp2_2 [Expand Off, Fill X, Side AtBottom] -- global options frame globalOptsFr <- newFrame b [] pack globalOptsFr [Expand Off, Fill Both] gOptsTitle <- newLabel globalOptsFr [text "Global Options:"] pack gOptsTitle [Side AtTop] inclProvedThsTK <- createTkVariable True inclProvedThsCheckButton <- newCheckButton globalOptsFr [variable inclProvedThsTK, text ("include preceding proven therorems" ++ " in next proof attempt")] pack inclProvedThsCheckButton [Side AtLeft] -- separator 3 sp1_3 <- newSpace b (cm 0.15) [] pack sp1_3 [Expand Off, Fill X, Side AtBottom] newHSeparator b sp2_3 <- newSpace b (cm 0.15) [] pack sp2_3 [Expand Off, Fill X, Side AtBottom] -- bottom frame (help/save/exit buttons) bottom <- newHBox b [] pack bottom [Expand Off, Fill Both] helpButton <- newButton bottom [text "Help"] pack helpButton [PadX (cm 0.3), IPadX (cm 0.1)] -- wider "Help" button saveButton <- newButton bottom [text "Save Prover Configuration"] pack saveButton [PadX (cm 0.3)] exitButton <- newButton bottom [text "Exit Prover"] pack exitButton [PadX (cm 0.3)] populateGoalsListBox lb (goalsView initState) putWinOnTop main -- MVars for thread-safe communication mVar_batchId <- Conc.newEmptyMVar :: IO (Conc.MVar Conc.ThreadId) windowDestroyedMVar <- Conc.newEmptyMVar :: IO (Conc.MVar ()) -- events (selectGoal, _) <- bindSimple lb (ButtonPress (Just 1)) doProve <- clicked proveButton saveProb <- clicked saveProbButton showDetails <- clicked detailsButton runBatch <- clicked runBatchButton stopBatch <- clicked stopBatchButton help <- clicked helpButton saveConfiguration <- clicked saveButton exit <- clicked exitButton (closeWindow, _) <- bindSimple main Destroy let goalSpecificWids = [EnW timeEntry, EnW timeSpinner, EnW optionsEntry] ++ map EnW [proveButton, detailsButton, saveProbButton] wids = EnW lb : goalSpecificWids ++ [EnW batchTimeEntry, EnW batchTimeSpinner, EnW saveProblem_batch_checkBox, EnW batchOptionsEntry, EnW inclProvedThsCheckButton] ++ map EnW [helpButton, saveButton, exitButton, runBatchButton] disableWids goalSpecificWids disable stopBatchButton -- event handlers _ <- spawnEvent $ forever $ selectGoal >>> do s <- Conc.takeMVar stateMVar let oldGoal = currentGoal s curEntTL <- getValueSafe guiDefaultTimeLimit timeEntry :: IO Int let s' = maybe s (\ og -> s {configsMap = adjustOrSetConfig (setTimeLimit curEntTL) prName og pt (configsMap s)}) oldGoal sel <- getSelection lb :: IO (Maybe [Int]) let s'' = maybe s' (\ sg -> s' {currentGoal = Just $ AS_Anno.senAttr (goalsList s' !! head sg)}) sel Conc.putMVar stateMVar s'' batchModeRunning <- isBatchModeRunning mVar_batchId when (isJust sel && not batchModeRunning) (enableWids goalSpecificWids) when (isJust sel) $ enableWids [EnW detailsButton, EnW saveProbButton] updateDisplay s'' False lb statusLabel timeEntry optionsEntry axiomsLb done +> saveProb >>> do rs <- Conc.readMVar stateMVar curEntTL <- getValueSafe guiDefaultTimeLimit timeEntry :: IO Int inclProvedThs <- readTkVariable inclProvedThsTK maybe (return ()) (\ goal -> do let (nGoal, lp') = prepareLP (proverState rs) rs goal inclProvedThs s = rs {configsMap = adjustOrSetConfig (setTimeLimit curEntTL) prName goal pt (configsMap rs)} extraOptions <- getValue optionsEntry :: IO String let s' = s {configsMap = adjustOrSetConfig (setExtraOpts (words extraOptions)) prName goal pt (configsMap s)} prob <- goalOutput atpFun lp' nGoal $ createProverOptions atpFun (getConfig prName goal pt $ configsMap s') createTextSaveDisplay (prName ++ " Problem for Goal " ++ goal) (thName ++ '_' : goal ++ problemOutput (fileExtensions atpFun)) prob) $ currentGoal rs done +> doProve >>> do rs <- Conc.readMVar stateMVar case currentGoal rs of Nothing -> noGoalSelected >> done Just goal -> do curEntTL <- getValueSafe guiDefaultTimeLimit timeEntry :: IO Int inclProvedThs <- readTkVariable inclProvedThsTK let s = rs {configsMap = adjustOrSetConfig (setTimeLimit curEntTL) prName goal pt (configsMap rs)} (nGoal, lp') = prepareLP (proverState rs) rs goal inclProvedThs extraOptions <- getValue optionsEntry :: IO String let s' = s {configsMap = adjustOrSetConfig (setExtraOpts (words extraOptions)) prName goal pt (configsMap s)} statusLabel # text (snd statusRunning) statusLabel # foreground (show $ fst statusRunning) disableWids wids (retval, cfg) <- runProver atpFun lp' (getConfig prName goal pt $ configsMap s') False thName nGoal -- check if window was closed wDestroyed <- windowDestroyed windowDestroyedMVar if wDestroyed then done else do case retval of ATPError m -> errorDialog "Error" m _ -> return () let s'' = s' { configsMap = adjustOrSetConfig (\ c -> c {timeLimitExceeded = isTimeLimitExceeded retval, proofStatus = (proofStatus cfg) {usedTime = timeUsed cfg}, resultOutput = resultOutput cfg, timeUsed = timeUsed cfg}) prName goal pt (configsMap s')} Conc.modifyMVar_ stateMVar (return . const s'') -- check again if window was closed wDestroyed2 <- windowDestroyed windowDestroyedMVar if wDestroyed2 then done else do enable lb enable axiomsLb updateDisplay s'' True lb statusLabel timeEntry optionsEntry axiomsLb enableWids wids done +> showDetails >>> do Conc.yield s <- Conc.readMVar stateMVar case currentGoal s of Nothing -> noGoalSelected >> done Just goal -> do let result = Map.lookup goal (configsMap s) output = maybe ["This goal hasn't been run through " ++ "the prover yet."] resultOutput result detailsText = concatMap ('\n' :) output createTextSaveDisplay (prName ++ " Output for Goal " ++ goal) (goal ++ proverOutput (fileExtensions atpFun)) (seq (length detailsText) detailsText) done +> runBatch >>> do s <- Conc.readMVar stateMVar -- get options for this batch run curEntTL <- getValueSafe batchTLimit batchTimeEntry :: IO Int let tLimit = if curEntTL > 0 then curEntTL else batchTLimit batchTimeEntry # value tLimit extOpts <- getValue batchOptionsEntry :: IO String let extOpts' = words extOpts openGoalsMap = filterOpenGoals $ configsMap s numGoals = Map.size openGoalsMap firstGoalName = fromMaybe "--" $ find (`Map.member` openGoalsMap) $ map AS_Anno.senAttr (goalsList s) if numGoals > 0 then do let afterEachProofAttempt gPSF nSen nextSen cfg@(retval, _) = do {- this function is called after the prover returns from a proof attempt (... -> IO Bool) -} cont <- goalProcessed stateMVar tLimit extOpts' numGoals prName gPSF nSen False cfg Conc.tryTakeMVar mVar_batchId >>= maybe (return False) (\ tId -> do stored <- Conc.tryPutMVar mVar_batchId tId if not stored then fail $ "GenericATP: Thread " ++ "run check failed" else do wDestroyed <- windowDestroyed windowDestroyedMVar if wDestroyed then return False else do batchStatusLabel # text (if cont then batchInfoText tLimit numGoals gPSF else "Batch mode finished\n\n") setCurrentGoalLabel batchCurrentGoalLabel (if cont then maybe "--" AS_Anno.senAttr nextSen else "--") st <- Conc.readMVar stateMVar updateDisplay st True lb statusLabel timeEntry optionsEntry axiomsLb case retval of ATPError m -> errorDialog "Error" m _ -> return () batchModeRunning <- isBatchModeRunning mVar_batchId let cont' = cont && batchModeRunning unless cont $ do disable stopBatchButton enableWids wids enableWidsUponSelection lb goalSpecificWids cleanupThread mVar_batchId return cont') -- END of afterEachProofAttempt batchStatusLabel # text (batchInfoText tLimit numGoals 0) setCurrentGoalLabel batchCurrentGoalLabel firstGoalName disableWids wids enable stopBatchButton enableWidsUponSelection lb [EnW detailsButton, EnW saveProbButton] enable lb inclProvedThs <- readTkVariable inclProvedThsTK saveProblem_F <- readTkVariable saveProblem_batch batchProverId <- Conc.forkIO $ genericProveBatch False tLimit extOpts' inclProvedThs saveProblem_F afterEachProofAttempt (atpInsertSentence atpFun) (runProver atpFun) prName thName s Nothing >> return () stored <- Conc.tryPutMVar mVar_batchId batchProverId if stored then done else fail "GenericATP: MVar for batchProverId already taken!!" else {- numGoals < 1 -} do batchStatusLabel # text "No further open goals\n\n" batchCurrentGoalLabel # text "--" done +> stopBatch >>> do cleanupThread mVar_batchId wDestroyed <- windowDestroyed windowDestroyedMVar if wDestroyed then done else do disable stopBatchButton enableWids wids enableWidsUponSelection lb goalSpecificWids batchStatusLabel # text "Batch mode stopped\n\n" batchCurrentGoalLabel # text "--" st <- Conc.readMVar stateMVar updateDisplay st True lb statusLabel timeEntry optionsEntry axiomsLb done +> help >>> do createTextDisplay (prName ++ " Help") (proverHelpText atpFun) done +> saveConfiguration >>> do s <- Conc.readMVar stateMVar let cfgText = show $ printCfgText $ configsMap s createTextSaveDisplay (prName ++ " Configuration for Theory " ++ thName) (thName ++ theoryConfiguration (fileExtensions atpFun)) cfgText done sync $ exit >>> destroy main +> closeWindow >>> do Conc.putMVar windowDestroyedMVar () cleanupThread mVar_batchId destroy main s <- Conc.takeMVar stateMVar let Result _ proofstats = revertRenamingOfLabels s $ map ((\ g -> let res = Map.lookup g (configsMap s) g' = Map.findWithDefault (error ("Lookup of name failed: (1) " ++ "should not happen \"" ++ g ++ "\"")) g (namesMap s) in maybe (openProofStatus g' prName $ currentProofTree s) proofStatus res) . AS_Anno.senAttr) $ goalsList s -- diags should not be plainly shown by putStrLn here maybe (fail "reverse translation of names failed") return proofstats where cleanupThread mVar_TId = Conc.tryTakeMVar mVar_TId >>= maybe (return ()) Conc.killThread windowDestroyed sMVar = Conc.yield >> Conc.tryTakeMVar sMVar >>= maybe (return False) (\ un -> Conc.putMVar sMVar un >> return True) isBatchModeRunning tIdMVar = Conc.tryTakeMVar tIdMVar >>= maybe (return False) (\ tId -> Conc.putMVar tIdMVar tId >> return True) noGoalSelected = errorDialog "Error" "Please select a goal first." prepareLP prS s goal inclProvedThs = let (beforeThis, afterThis) = splitAt (fromMaybe (error "GUI.GenericATP: goal shoud be found") $ findIndex ((== goal) . AS_Anno.senAttr) $ goalsList s) $ goalsList s proved = filter (checkGoal (configsMap s) . AS_Anno.senAttr) beforeThis in if inclProvedThs then (head afterThis, foldl (\ lp provedGoal -> atpInsertSentence atpFun lp provedGoal {AS_Anno.isAxiom = True}) prS (reverse proved)) else (fromMaybe (error ("GUI.GenericATP.prepareLP: Goal " ++ goal ++ " not found!!")) (find ((== goal) . AS_Anno.senAttr) (goalsList s)), prS) setCurrentGoalLabel batchLabel s = batchLabel # text (take 65 s) removeFirstDot [] = error "GenericATP: no extension given" removeFirstDot e@(h : ext) = case h of '.' -> ext _ -> e
nevrenato/Hets_Fork
GUI/HTkGenericATP.hs
gpl-2.0
34,711
0
41
13,149
7,856
3,780
4,076
660
20
module Render.Backend.GNUPlot where import Control.Wire import Prelude hiding ((.),id) import Render.Render import Utils.Wire.TestWire gnuPlotBackend :: (Real t, Monoid e, Show e) => t -> Int -> Backend (Timed t ()) e IO (IO ()) a gnuPlotBackend dt n = Backend runGnuplot where runGnuplot r wr = testWire' n dt (either print r) (wr . never) class GNUPlottable a where gnuplot :: a -> String
mstksg/netwire-experiments
src/Render/Backend/GNUPlot.hs
gpl-3.0
422
0
11
95
167
90
77
14
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, OverloadedStrings, FlexibleContexts #-} module Sound.Tidal.Control where import Prelude hiding ((<*), (*>)) import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe, isJust, fromJust) import Data.Ratio import Sound.Tidal.Pattern import Sound.Tidal.Core import Sound.Tidal.UI import qualified Sound.Tidal.Params as P import Sound.Tidal.Utils {- | `spin` will "spin" a layer up a pattern the given number of times, with each successive layer offset in time by an additional `1/n` of a cycle, and panned by an additional `1/n`. The result is a pattern that seems to spin around. This function works best on multichannel systems. @ d1 $ slow 3 $ spin 4 $ sound "drum*3 tabla:4 [arpy:2 ~ arpy] [can:2 can:3]" @ -} spin :: Pattern Int -> ControlPattern -> ControlPattern spin = tParam _spin _spin :: Int -> ControlPattern -> ControlPattern _spin copies p = stack $ map (\i -> let offset = toInteger i % toInteger copies in offset `rotL` p # P.pan (pure $ fromRational offset) ) [0 .. (copies - 1)] {- | `chop` granualizes every sample in place as it is played, turning a pattern of samples into a pattern of sample parts. Use an integer value to specify how many granules each sample is chopped into: @ d1 $ chop 16 $ sound "arpy arp feel*4 arpy*4" @ Different values of `chop` can yield very different results, depending on the samples used: @ d1 $ chop 16 $ sound (samples "arpy*8" (run 16)) d1 $ chop 32 $ sound (samples "arpy*8" (run 16)) d1 $ chop 256 $ sound "bd*4 [sn cp] [hh future]*2 [cp feel]" @ -} chop :: Pattern Int -> ControlPattern -> ControlPattern chop = tParam _chop chopArc :: Arc -> Int -> [Arc] chopArc (Arc s e) n = map (\i -> Arc (s + (e-s)*(fromIntegral i/fromIntegral n)) (s + (e-s)*(fromIntegral (i+1) / fromIntegral n))) [0 .. n-1] _chop :: Int -> ControlPattern -> ControlPattern _chop n = withEvents (concatMap chopEvent) where -- for each part, chopEvent :: Event ControlMap -> [Event ControlMap] chopEvent (Event c (Just w) p' v) = map (chomp c v (length $ chopArc w n)) $ arcs w p' -- ignoring 'analog' events (those without wholes), chopEvent _ = [] -- cut whole into n bits, and number them arcs w' p' = numberedArcs p' $ chopArc w' n -- each bit is a new whole, with part that's the intersection of old part and new whole -- (discard new parts that don't intersect with the old part) numberedArcs :: Arc -> [Arc] -> [(Int, (Arc, Arc))] numberedArcs p' as = map ((fromJust <$>) <$>) $ filter (isJust . snd . snd) $ enumerate $ map (\a -> (a, subArc p' a)) as -- begin set to i/n, end set to i+1/n -- if the old event had a begin and end, then multiply the new -- begin and end values by the old difference (end-begin), and -- add the old begin chomp :: Context -> ControlMap -> Int -> (Int, (Arc, Arc)) -> Event ControlMap chomp c v n' (i, (w,p')) = Event c (Just w) p' (Map.insert "begin" (VF b') $ Map.insert "end" (VF e') v) where b = fromMaybe 0 $ do v' <- Map.lookup "begin" v getF v' e = fromMaybe 1 $ do v' <- Map.lookup "end" v getF v' d = e-b b' = ((fromIntegral i/fromIntegral n') * d) + b e' = ((fromIntegral (i+1) / fromIntegral n') * d) + b {- -- A simpler definition than the above, but this version doesn't chop -- with multiple chops, and only works with a single 'pure' event.. _chop' :: Int -> ControlPattern -> ControlPattern _chop' n p = begin (fromList begins) # end (fromList ends) # p where step = 1/(fromIntegral n) begins = [0,step .. (1-step)] ends = (tail begins) ++ [1] -} {- | Striate is a kind of granulator, for example: @ d1 $ striate 3 $ sound "ho ho:2 ho:3 hc" @ This plays the loop the given number of times, but triggering progressive portions of each sample. So in this case it plays the loop three times, the first time playing the first third of each sample, then the second time playing the second third of each sample, etc.. With the highhat samples in the above example it sounds a bit like reverb, but it isn't really. You can also use striate with very long samples, to cut it into short chunks and pattern those chunks. This is where things get towards granular synthesis. The following cuts a sample into 128 parts, plays it over 8 cycles and manipulates those parts by reversing and rotating the loops. @ d1 $ slow 8 $ striate 128 $ sound "bev" @ -} striate :: Pattern Int -> ControlPattern -> ControlPattern striate = tParam _striate _striate :: Int -> ControlPattern -> ControlPattern _striate n p = fastcat $ map offset [0 .. n-1] where offset i = mergePlayRange (fromIntegral i / fromIntegral n, fromIntegral (i+1) / fromIntegral n) <$> p mergePlayRange :: (Double, Double) -> ControlMap -> ControlMap mergePlayRange (b,e) cm = Map.insert "begin" (VF $ (b*d')+b') $ Map.insert "end" (VF $ (e*d')+b') cm where b' = fromMaybe 0 $ Map.lookup "begin" cm >>= getF e' = fromMaybe 1 $ Map.lookup "end" cm >>= getF d' = e' - b' {-| The `striateBy` function is a variant of `striate` with an extra parameter, which specifies the length of each part. The `striateBy` function still scans across the sample over a single cycle, but if each bit is longer, it creates a sort of stuttering effect. For example the following will cut the bev sample into 32 parts, but each will be 1/16th of a sample long: @ d1 $ slow 32 $ striateBy 32 (1/16) $ sound "bev" @ Note that `striate` uses the `begin` and `end` parameters internally. This means that if you're using `striate` (or `striateBy`) you probably shouldn't also specify `begin` or `end`. -} striateBy :: Pattern Int -> Pattern Double -> ControlPattern -> ControlPattern striateBy = tParam2 _striateBy -- Old name for striateBy, here as a deprecated alias for now. striate' :: Pattern Int -> Pattern Double -> ControlPattern -> ControlPattern striate' = striateBy _striateBy :: Int -> Double -> ControlPattern -> ControlPattern _striateBy n f p = fastcat $ map (offset . fromIntegral) [0 .. n-1] where offset i = p # P.begin (pure (slot * i) :: Pattern Double) # P.end (pure ((slot * i) + f) :: Pattern Double) slot = (1 - f) / fromIntegral n {- | `gap` is similar to `chop` in that it granualizes every sample in place as it is played, but every other grain is silent. Use an integer value to specify how many granules each sample is chopped into: @ d1 $ gap 8 $ sound "jvbass" d1 $ gap 16 $ sound "[jvbass drum:4]" @-} gap :: Pattern Int -> ControlPattern -> ControlPattern gap = tParam _gap _gap :: Int -> ControlPattern -> ControlPattern _gap n p = _fast (toRational n) (cat [pure 1, silence]) |>| _chop n p {- | `weave` applies a function smoothly over an array of different patterns. It uses an `OscPattern` to apply the function at different levels to each pattern, creating a weaving effect. @ d1 $ weave 3 (shape $ sine1) [sound "bd [sn drum:2*2] bd*2 [sn drum:1]", sound "arpy*8 ~"] @ -} weave :: Time -> ControlPattern -> [ControlPattern] -> ControlPattern weave t p ps = weave' t p (map (#) ps) {- | `weaveWith` is similar in that it blends functions at the same time at different amounts over a pattern: @ d1 $ weaveWith 3 (sound "bd [sn drum:2*2] bd*2 [sn drum:1]") [density 2, (# speed "0.5"), chop 16] @ -} weaveWith :: Time -> Pattern a -> [Pattern a -> Pattern a] -> Pattern a weaveWith t p fs | l == 0 = silence | otherwise = _slow t $ stack $ map (\(i, f) -> (fromIntegral i % l) `rotL` _fast t (f (_slow t p))) (zip [0 :: Int ..] fs) where l = fromIntegral $ length fs weave' :: Time -> Pattern a -> [Pattern a -> Pattern a] -> Pattern a weave' = weaveWith {- | (A function that takes two ControlPatterns, and blends them together into a new ControlPattern. An ControlPattern is basically a pattern of messages to a synthesiser.) Shifts between the two given patterns, using distortion. Example: @ d1 $ interlace (sound "bd sn kurt") (every 3 rev $ sound "bd sn:2") @ -} interlace :: ControlPattern -> ControlPattern -> ControlPattern interlace a b = weave 16 (P.shape (sine * 0.9)) [a, b] {- {- | Just like `striate`, but also loops each sample chunk a number of times specified in the second argument. The primed version is just like `striateBy`, where the loop count is the third argument. For example: @ d1 $ striateL' 3 0.125 4 $ sound "feel sn:2" @ Like `striate`, these use the `begin` and `end` parameters internally, as well as the `loop` parameter for these versions. -} striateL :: Pattern Int -> Pattern Int -> ControlPattern -> ControlPattern striateL = tParam2 _striateL striateL' :: Pattern Int -> Pattern Double -> Pattern Int -> ControlPattern -> ControlPattern striateL' = tParam3 _striateL' _striateL :: Int -> Int -> ControlPattern -> ControlPattern _striateL n l p = _striate n p # loop (pure $ fromIntegral l) _striateL' n f l p = _striateBy n f p # loop (pure $ fromIntegral l) en :: [(Int, Int)] -> Pattern String -> Pattern String en ns p = stack $ map (\(i, (k, n)) -> _e k n (samples p (pure i))) $ enumerate ns -} slice :: Pattern Int -> Pattern Int -> ControlPattern -> ControlPattern slice pN pI p = P.begin b # P.end e # p where b = div' <$> pI <* pN e = (\i n -> div' i n + div' 1 n) <$> pI <* pN div' num den = fromIntegral (num `mod` den) / fromIntegral den _slice :: Int -> Int -> ControlPattern -> ControlPattern _slice n i p = p # P.begin (pure $ fromIntegral i / fromIntegral n) # P.end (pure $ fromIntegral (i+1) / fromIntegral n) randslice :: Pattern Int -> ControlPattern -> ControlPattern randslice = tParam $ \n p -> innerJoin $ (\i -> _slice n i p) <$> irand n splice :: Pattern Int -> Pattern Int -> ControlPattern -> Pattern (Map.Map String Value) splice bits ipat pat = withEvent f (slice bits ipat pat) # P.unit (pure "c") where f ev = ev {value = Map.insert "speed" (VF d) (value ev)} where d = sz / (fromRational $ (wholeStop ev) - (wholeStart ev)) sz = 1/(fromIntegral bits) {- | `loopAt` makes a sample fit the given number of cycles. Internally, it works by setting the `unit` parameter to "c", changing the playback speed of the sample with the `speed` parameter, and setting setting the `density` of the pattern to match. @ d1 $ loopAt 4 $ sound "breaks125" d1 $ juxBy 0.6 (|* speed "2") $ slowspread (loopAt) [4,6,2,3] $ chop 12 $ sound "fm:14" @ -} loopAt :: Pattern Time -> ControlPattern -> ControlPattern loopAt n p = slow n p |* P.speed (fromRational <$> (1/n)) # P.unit (pure "c") hurry :: Pattern Rational -> ControlPattern -> ControlPattern hurry x = (|* P.speed (fromRational <$> x)) . fast x {- | Smash is a combination of `spread` and `striate` - it cuts the samples into the given number of bits, and then cuts between playing the loop at different speeds according to the values in the list. So this: @ d1 $ smash 3 [2,3,4] $ sound "ho ho:2 ho:3 hc" @ Is a bit like this: @ d1 $ spread (slow) [2,3,4] $ striate 3 $ sound "ho ho:2 ho:3 hc" @ This is quite dancehall: @ d1 $ (spread' slow "1%4 2 1 3" $ spread (striate) [2,3,4,1] $ sound "sn:2 sid:3 cp sid:4") # speed "[1 2 1 1]/2" @ -} smash :: Pattern Int -> [Pattern Time] -> ControlPattern -> Pattern ControlMap smash n xs p = slowcat $ map (`slow` p') xs where p' = striate n p {- | an altenative form to `smash` is `smash'` which will use `chop` instead of `striate`. -} smash' :: Int -> [Pattern Time] -> ControlPattern -> Pattern ControlMap smash' n xs p = slowcat $ map (`slow` p') xs where p' = _chop n p {- | Stut applies a type of delay to a pattern. It has three parameters, which could be called depth, feedback and time. Depth is an integer and the others floating point. This adds a bit of echo: @ d1 $ stut 4 0.5 0.2 $ sound "bd sn" @ The above results in 4 echos, each one 50% quieter than the last, with 1/5th of a cycle between them. It is possible to reverse the echo: @ d1 $ stut 4 0.5 (-0.2) $ sound "bd sn" @ -} stut :: Pattern Integer -> Pattern Double -> Pattern Rational -> ControlPattern -> ControlPattern stut = tParam3 _stut _stut :: Integer -> Double -> Rational -> ControlPattern -> ControlPattern _stut count feedback steptime p = stack (p:map (\x -> ((x%1)*steptime) `rotR` (p |* P.gain (pure $ scalegain (fromIntegral x)))) [1..(count-1)]) where scalegain = (+feedback) . (*(1-feedback)) . (/ fromIntegral count) . (fromIntegral count -) {- | Instead of just decreasing volume to produce echoes, @stut'@ allows to apply a function for each step and overlays the result delayed by the given time. @ d1 $ stut' 2 (1%3) (# vowel "{a e i o u}%2") $ sound "bd sn" @ In this case there are two _overlays_ delayed by 1/3 of a cycle, where each has the @vowel@ filter applied. -} stutWith :: Pattern Int -> Pattern Time -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a stutWith n t f p = innerJoin $ (\a b -> _stutWith a b f p) <$> n <* t _stutWith :: (Num n, Ord n) => n -> Time -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a _stutWith count steptime f p | count <= 1 = p | otherwise = overlay (f (steptime `rotR` _stutWith (count-1) steptime f p)) p -- | The old name for stutWith stut' :: Pattern Int -> Pattern Time -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a stut' = stutWith -- | Turns a pattern of seconds into a pattern of (rational) cycle durations sec :: Fractional a => Pattern a -> Pattern a sec p = (realToFrac <$> cF 1 "_cps") *| p -- | Turns a pattern of milliseconds into a pattern of (rational) -- cycle durations, according to the current cps. msec :: Fractional a => Pattern a -> Pattern a msec p = ((realToFrac . (/1000)) <$> cF 1 "_cps") *| p _trigger :: Show a => Bool -> a -> Pattern b -> Pattern b _trigger quant k pat = pat {query = q} where q st = query ((offset st) ~> pat) st f | quant = (fromIntegral :: Int -> Rational) . round | otherwise = id offset st = fromMaybe (pure 0) $ do p <- Map.lookup ctrl (controls st) return $ ((f . fromMaybe 0 . getR) <$> p) ctrl = "_t_" ++ show k trigger :: Show a => a -> Pattern b -> Pattern b trigger = _trigger False qtrigger :: Show a => a -> Pattern b -> Pattern b qtrigger = _trigger True qt :: Show a => a -> Pattern b -> Pattern b qt = qtrigger reset :: Show a => a -> Pattern b -> Pattern b reset k pat = pat {query = q} where q st = query ((offset st) ~> (when (<=0) (const silence) pat)) st f = (fromIntegral :: Int -> Rational) . floor offset st = fromMaybe (pure 0) $ do p <- Map.lookup ctrl (controls st) return $ ((f . fromMaybe 0 . getR) <$> p) ctrl = "_t_" ++ show k
d0kt0r0/Tidal
src/Sound/Tidal/Control.hs
gpl-3.0
14,997
0
19
3,465
3,496
1,800
1,696
137
2
module CPU where import Control.Monad.ST import Control.Wire import qualified Data.ByteString as B import Data.Map.Strict import qualified Data.Vector.Unboxed as V import qualified Data.Vector.Unboxed.Mutable as M import Data.Word import Mem import Opcodes import Types cpu :: (HasTime t s) => B.ByteString -> Wire s e m DataBus Int cpu rom = cpu' m $ V.replicate 0x10C (0 :: Word8) where m = memory rom cpu' mem regs = mkSF $ \dt _ -> do let pcLo = regs V.! 0x109 let pcHi = regs V.! 0x108 let pc = fromIntegral pcHi * 0x100 + fromIntegral pcLo -- fetch op <- readMem dt mem pc opLo <- readMem dt mem (pc+1) opHi <- readMem dt mem (pc+2) -- decode let instr = opcodes ! fromIntegral op let operand = case bytes instr of 2 -> fromIntegral opLo 3 -> fromIntegral opHi * 0x100 + fromIntegral opLo _ -> 0 -- execute (regs', mem') <- execute op operand instr regs mem return (cycles instr, cpu' mem' regs') execute :: Monad m => Word8 -> Int -> Instr -> V.Vector Word8 -> MemWire s e m -> m (V.Vector Word8, MemWire s e m) execute op operand instr regs mem = do return (regs, mem) -- TODO write functions to handle different opcode types -- ld :: Operand -> Operand -> ... -- Operand = Register | Address8 | Address 16... -- how to handle internal cpu state? -- I want the registers to be in here -- Should each pass through the arrow be 1 machine/clock cycle or 1 instruction -- keep track of current instruction? -- What Control bits do i need to pass out?
npdawson/arrowGB
src/CPU.hs
gpl-3.0
1,729
0
19
546
478
248
230
36
3
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} -- FIXME: better types in checkLevel {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} -- | -- Copyright : (c) 2010-2012 Simon Meier & Benedikt Schmidt -- License : GPL v3 (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- Portability : GHC only -- -- Types to represent proofs. module Theory.Proof ( -- * Utilities LTree(..) , mergeMapsWith -- * Types , ProofStep(..) , DiffProofStep(..) , Proof , DiffProof -- ** Paths inside proofs , ProofPath , atPath , atPathDiff , insertPaths , insertPathsDiff -- ** Folding/modifying proofs , mapProofInfo , mapDiffProofInfo , foldProof , foldDiffProof , annotateProof , annotateDiffProof , ProofStatus(..) , proofStepStatus , diffProofStepStatus -- ** Unfinished proofs , sorry , unproven , diffSorry , diffUnproven , selectHeuristic , selectDiffHeuristic -- ** Incremental proof construction , IncrementalProof , IncrementalDiffProof , Prover , DiffProver , runProver , runDiffProver , mapProverProof , mapDiffProverDiffProof , orelse , tryProver , sorryProver , sorryDiffProver , oneStepProver , oneStepDiffProver , focus , focusDiff , checkAndExtendProver , checkAndExtendDiffProver , replaceSorryProver , replaceDiffSorryProver , contradictionProver , contradictionDiffProver -- ** Explicit representation of a fully automatic prover , SolutionExtractor(..) , AutoProver(..) , runAutoProver , runAutoDiffProver -- ** Pretty Printing , prettyProof , prettyDiffProof , prettyProofWith , prettyDiffProofWith , showProofStatus , showDiffProofStatus -- ** Parallel Strategy for exploring a proof , parLTreeDFS -- ** Small-step interface to the constraint solver , module Theory.Constraint.Solver ) where import GHC.Generics (Generic) import Data.Binary import Data.List import qualified Data.Label as L import qualified Data.Map as M import Data.Maybe -- import Data.Monoid import Debug.Trace import Control.Basics import Control.DeepSeq import qualified Control.Monad.State as S import Control.Parallel.Strategies import Theory.Constraint.Solver import Theory.Model import Theory.Text.Pretty ------------------------------------------------------------------------------ -- Utility: Trees with uniquely labelled edges. ------------------------------------------------------------------------------ -- | Trees with uniquely labelled edges. data LTree l a = LNode { root :: a , children :: M.Map l (LTree l a) } deriving( Eq, Ord, Show ) instance Functor (LTree l) where fmap f (LNode r cs) = LNode (f r) (M.map (fmap f) cs) instance Foldable (LTree l) where foldMap f (LNode x cs) = f x `mappend` foldMap (foldMap f) cs instance Traversable (LTree l) where traverse f (LNode x cs) = LNode <$> f x <*> traverse (traverse f) cs -- | A parallel evaluation strategy well-suited for DFS traversal: As soon as -- a node is forced it sparks off the computation of the number of case-maps -- of all its children. This way most of the data is already evaulated, when -- the actual DFS traversal visits it. -- -- NOT used for now. It sometimes required too much memory. parLTreeDFS :: Strategy (LTree l a) parLTreeDFS (LNode x0 cs0) = do cs0' <- (`parTraversable` cs0) $ \(LNode x cs) -> LNode x <$> rseq cs return $ LNode x0 (M.map (runEval . parLTreeDFS) cs0') ------------------------------------------------------------------------------ -- Utility: Merging maps ------------------------------------------------------------------------------ -- | /O(n+m)/. A generalized union operator for maps with differing types. mergeMapsWith :: Ord k => (a -> c) -> (b -> c) -> (a -> b -> c) -> M.Map k a -> M.Map k b -> M.Map k c mergeMapsWith leftOnly rightOnly combine l r = M.map extract $ M.unionWith combine' l' r' where l' = M.map (Left . Left) l r' = M.map (Left . Right) r combine' (Left (Left a)) (Left (Right b)) = Right $ combine a b combine' _ _ = error "mergeMapsWith: impossible" extract (Left (Left a)) = leftOnly a extract (Left (Right b)) = rightOnly b extract (Right c) = c ------------------------------------------------------------------------------ -- Proof Steps ------------------------------------------------------------------------------ -- | A proof steps is a proof method together with additional context-dependent -- information. data ProofStep a = ProofStep { psMethod :: ProofMethod , psInfo :: a } deriving( Eq, Ord, Show, Generic, NFData, Binary ) instance Functor ProofStep where fmap f (ProofStep m i) = ProofStep m (f i) instance Foldable ProofStep where foldMap f = f . psInfo instance Traversable ProofStep where traverse f (ProofStep m i) = ProofStep m <$> f i instance HasFrees a => HasFrees (ProofStep a) where foldFrees f (ProofStep m i) = foldFrees f m `mappend` foldFrees f i foldFreesOcc _ _ = const mempty mapFrees f (ProofStep m i) = ProofStep <$> mapFrees f m <*> mapFrees f i -- | A diff proof steps is a proof method together with additional context-dependent -- information. data DiffProofStep a = DiffProofStep { dpsMethod :: DiffProofMethod , dpsInfo :: a } deriving( Eq, Ord, Show, Generic, NFData, Binary ) instance Functor DiffProofStep where fmap f (DiffProofStep m i) = DiffProofStep m (f i) instance Foldable DiffProofStep where foldMap f = f . dpsInfo instance Traversable DiffProofStep where traverse f (DiffProofStep m i) = DiffProofStep m <$> f i instance HasFrees a => HasFrees (DiffProofStep a) where foldFrees f (DiffProofStep m i) = foldFrees f m `mappend` foldFrees f i foldFreesOcc _ _ = const mempty mapFrees f (DiffProofStep m i) = DiffProofStep <$> mapFrees f m <*> mapFrees f i ------------------------------------------------------------------------------ -- Proof Trees ------------------------------------------------------------------------------ -- | A path to a subproof. type ProofPath = [CaseName] -- | A proof is a tree of proof steps whose edges are labelled with case names. type Proof a = LTree CaseName (ProofStep a) -- | A diff proof is a tree of proof steps whose edges are labelled with case names. type DiffProof a = LTree CaseName (DiffProofStep a) -- Unfinished proofs -------------------- -- | A proof using the 'sorry' proof method. sorry :: Maybe String -> a -> Proof a sorry reason ann = LNode (ProofStep (Sorry reason) ann) M.empty -- | A proof using the 'sorry' proof method. diffSorry :: Maybe String -> a -> DiffProof a diffSorry reason ann = LNode (DiffProofStep (DiffSorry reason) ann) M.empty -- | A proof denoting an unproven part of the proof. unproven :: a -> Proof a unproven = sorry Nothing -- | A proof denoting an unproven part of the proof. diffUnproven :: a -> DiffProof a diffUnproven = diffSorry Nothing -- Paths in proofs ------------------ -- | @prf `atPath` path@ returns the subproof at the @path@ in @prf@. atPath :: Proof a -> ProofPath -> Maybe (Proof a) atPath = foldM (flip M.lookup . children) -- | @prf `atPath` path@ returns the subproof at the @path@ in @prf@. atPathDiff :: DiffProof a -> ProofPath -> Maybe (DiffProof a) atPathDiff = foldM (flip M.lookup . children) -- | @modifyAtPath f path prf@ applies @f@ to the subproof at @path@, -- if there is one. modifyAtPath :: (Proof a -> Maybe (Proof a)) -> ProofPath -> Proof a -> Maybe (Proof a) modifyAtPath f = go where go [] prf = f prf go (l:ls) prf = do let cs = children prf prf' <- go ls =<< M.lookup l cs return (prf { children = M.insert l prf' cs }) -- | @modifyAtPath f path prf@ applies @f@ to the subproof at @path@, -- if there is one. modifyAtPathDiff :: (DiffProof a -> Maybe (DiffProof a)) -> ProofPath -> DiffProof a -> Maybe (DiffProof a) modifyAtPathDiff f = go where go [] prf = f prf go (l:ls) prf = do let cs = children prf prf' <- go ls =<< M.lookup l cs return (prf { children = M.insert l prf' cs }) -- | @insertPaths prf@ inserts the path to every proof node. insertPaths :: Proof a -> Proof (a, ProofPath) insertPaths = insertPath [] where insertPath path (LNode ps cs) = LNode (fmap (,reverse path) ps) (M.mapWithKey (\n prf -> insertPath (n:path) prf) cs) -- | @insertPaths prf@ inserts the path to every diff proof node. insertPathsDiff :: DiffProof a -> DiffProof (a, ProofPath) insertPathsDiff = insertPath [] where insertPath path (LNode ps cs) = LNode (fmap (,reverse path) ps) (M.mapWithKey (\n prf -> insertPath (n:path) prf) cs) -- Utilities for dealing with proofs ------------------------------------ -- | Apply a function to the information of every proof step. mapProofInfo :: (a -> b) -> Proof a -> Proof b mapProofInfo = fmap . fmap -- | Apply a function to the information of every proof step. mapDiffProofInfo :: (a -> b) -> DiffProof a -> DiffProof b mapDiffProofInfo = fmap . fmap -- | @boundProofDepth bound prf@ bounds the depth of the proof @prf@ using -- 'Sorry' steps to replace the cut sub-proofs. boundProofDepth :: Int -> Proof a -> Proof a boundProofDepth bound = go bound where go n (LNode ps@(ProofStep _ info) cs) | 0 < n = LNode ps $ M.map (go (pred n)) cs | otherwise = sorry (Just $ "bound " ++ show bound ++ " hit") info -- | @boundProofDepth bound prf@ bounds the depth of the proof @prf@ using -- 'Sorry' steps to replace the cut sub-proofs. boundDiffProofDepth :: Int -> DiffProof a -> DiffProof a boundDiffProofDepth bound = go bound where go n (LNode ps@(DiffProofStep _ info) cs) | 0 < n = LNode ps $ M.map (go (pred n)) cs | otherwise = diffSorry (Just $ "bound " ++ show bound ++ " hit") info -- | Fold a proof. foldProof :: Monoid m => (ProofStep a -> m) -> Proof a -> m foldProof f = go where go (LNode step cs) = f step `mappend` foldMap go (M.elems cs) -- | Fold a proof. foldDiffProof :: Monoid m => (DiffProofStep a -> m) -> DiffProof a -> m foldDiffProof f = go where go (LNode step cs) = f step `mappend` foldMap go (M.elems cs) -- | Annotate a proof in a bottom-up fashion. annotateProof :: (ProofStep a -> [b] -> b) -> Proof a -> Proof b annotateProof f = go where go (LNode step@(ProofStep method _) cs) = LNode (ProofStep method info') cs' where cs' = M.map go cs info' = f step (map (psInfo . root . snd) (M.toList cs')) -- | Annotate a proof in a bottom-up fashion. annotateDiffProof :: (DiffProofStep a -> [b] -> b) -> DiffProof a -> DiffProof b annotateDiffProof f = go where go (LNode step@(DiffProofStep method _) cs) = LNode (DiffProofStep method info') cs' where cs' = M.map go cs info' = f step (map (dpsInfo . root . snd) (M.toList cs')) -- Proof cutting ---------------- -- | The status of a 'Proof'. data ProofStatus = UndeterminedProof -- ^ All steps are unannotated | CompleteProof -- ^ The proof is complete: no annotated sorry, -- no annotated solved step | IncompleteProof -- ^ There is a annotated sorry, -- but no annotated solved step. | TraceFound -- ^ There is an annotated solved step deriving ( Show, Generic, NFData, Binary ) instance Semigroup ProofStatus where TraceFound <> _ = TraceFound _ <> TraceFound = TraceFound IncompleteProof <> _ = IncompleteProof _ <> IncompleteProof = IncompleteProof _ <> CompleteProof = CompleteProof CompleteProof <> _ = CompleteProof UndeterminedProof <> UndeterminedProof = UndeterminedProof instance Monoid ProofStatus where mempty = CompleteProof -- | The status of a 'ProofStep'. proofStepStatus :: ProofStep (Maybe a) -> ProofStatus proofStepStatus (ProofStep _ Nothing ) = UndeterminedProof proofStepStatus (ProofStep Solved (Just _)) = TraceFound proofStepStatus (ProofStep (Sorry _) (Just _)) = IncompleteProof proofStepStatus (ProofStep _ (Just _)) = CompleteProof -- | The status of a 'DiffProofStep'. diffProofStepStatus :: DiffProofStep (Maybe a) -> ProofStatus diffProofStepStatus (DiffProofStep _ Nothing ) = UndeterminedProof diffProofStepStatus (DiffProofStep DiffAttack (Just _)) = TraceFound diffProofStepStatus (DiffProofStep (DiffSorry _) (Just _)) = IncompleteProof diffProofStepStatus (DiffProofStep _ (Just _)) = CompleteProof {- TODO: Test and probably improve -- | @proveSystem rules se@ tries to construct a proof that @se@ is valid. -- This proof may contain 'Sorry' steps, if the prover is stuck. It can also be -- of infinite depth, if the proof strategy loops. proveSystemIterDeep :: ProofContext -> System -> Proof System proveSystemIterDeep rules se0 = fromJust $ asum $ map (prove se0 . round) $ iterate (*1.5) (3::Double) where prove :: System -> Int -> Maybe (Proof System) prove se bound | bound < 0 = Nothing | otherwise = case next of [] -> pure $ sorry "prover stuck => possible attack found" se xs -> asum $ map mkProof xs where next = do m <- possibleProofMethods se (m,) <$> maybe mzero return (execProofMethod rules m se) mkProof (method, cases) = LNode (ProofStep method se) <$> traverse (`prove` (bound - 1)) cases -} -- | @checkProof rules se prf@ replays the proof @prf@ against the start -- sequent @se@. A failure to apply a proof method is denoted by a resulting -- proof step without an annotated sequent. An unhandled case is denoted using -- the 'Sorry' proof method. checkProof :: ProofContext -> (Int -> System -> Proof (Maybe System)) -- prover for new cases in depth -> Int -- ^ Original depth -> System -> Proof a -> Proof (Maybe a, Maybe System) checkProof ctxt prover d sys prf@(LNode (ProofStep method info) cs) = case (method, execProofMethod ctxt method sys) of (Sorry reason, _ ) -> sorryNode reason cs (_ , Just cases) -> node method $ checkChildren cases (_ , Nothing ) -> sorryNode (Just "invalid proof step encountered") (M.singleton "" prf) where node m = LNode (ProofStep m (Just info, Just sys)) sorryNode reason cases = node (Sorry reason) (M.map noSystemPrf cases) noSystemPrf = mapProofInfo (\i -> (Just i, Nothing)) checkChildren cases = mergeMapsWith unhandledCase noSystemPrf (checkProof ctxt prover (d + 1)) cases cs where unhandledCase = mapProofInfo ((,) Nothing) . prover d -- | @checkDiffProof rules se prf@ replays the proof @prf@ against the start -- sequent @se@. A failure to apply a proof method is denoted by a resulting -- proof step without an annotated sequent. An unhandled case is denoted using -- the 'Sorry' proof method. checkDiffProof :: DiffProofContext -> (Int -> DiffSystem -> DiffProof (Maybe DiffSystem)) -- prover for new cases in depth -> Int -- ^ Original depth -> DiffSystem -> DiffProof a -> DiffProof (Maybe a, Maybe DiffSystem) checkDiffProof ctxt prover d sys prf@(LNode (DiffProofStep method info) cs) = case (method, execDiffProofMethod ctxt method sys) of (DiffSorry reason, _ ) -> sorryNode reason cs (_ , Just cases) -> node method $ checkChildren cases (_ , Nothing ) -> sorryNode (Just "invalid proof step encountered") (M.singleton "" prf) where node m = LNode (DiffProofStep m (Just info, Just sys)) sorryNode reason cases = node (DiffSorry reason) (M.map noSystemPrf cases) noSystemPrf = mapDiffProofInfo (\i -> (Just i, Nothing)) checkChildren cases = mergeMapsWith unhandledCase noSystemPrf (checkDiffProof ctxt prover (d + 1)) cases cs where unhandledCase = mapDiffProofInfo ((,) Nothing) . prover d -- | Annotate a proof with the constraint systems of all intermediate steps -- under the assumption that all proof steps are valid. If some proof steps -- might be invalid, then you must use 'checkProof', which handles them -- gracefully. annotateWithSystems :: ProofContext -> System -> Proof () -> Proof System annotateWithSystems ctxt = go where -- Here we are careful to construct the result such that an inspection of -- the proof does not force the recomputed constraint systems. go sysOrig (LNode (ProofStep method _) csOrig) = LNode (ProofStep method sysOrig) $ M.fromList $ do (name, prf) <- M.toList csOrig let sysAnn = extract ("case '" ++ name ++ "' non-existent") $ M.lookup name csAnn return (name, go sysAnn prf) where extract msg = fromMaybe (error $ "annotateWithSystems: " ++ msg) csAnn = extract "proof method execution failed" $ execProofMethod ctxt method sysOrig -- | Annotate a proof with the constraint systems of all intermediate steps -- under the assumption that all proof steps are valid. If some proof steps -- might be invalid, then you must use 'checkProof', which handles them -- gracefully. annotateWithDiffSystems :: DiffProofContext -> DiffSystem -> DiffProof () -> DiffProof DiffSystem annotateWithDiffSystems ctxt = go where -- Here we are careful to construct the result such that an inspection of -- the proof does not force the recomputed constraint systems. go sysOrig (LNode (DiffProofStep method _) csOrig) = LNode (DiffProofStep method sysOrig) $ M.fromList $ do (name, prf) <- M.toList csOrig let sysAnn = extract ("case '" ++ name ++ "' non-existent") $ M.lookup name csAnn return (name, go sysAnn prf) where extract msg = fromMaybe (error $ "annotateWithSystems: " ++ msg) csAnn = extract "diff proof method execution failed" $ execDiffProofMethod ctxt method sysOrig ------------------------------------------------------------------------------ -- Provers: the interface to the outside world. ------------------------------------------------------------------------------ -- | Incremental proofs are used to represent intermediate results of proof -- checking/construction. type IncrementalProof = Proof (Maybe System) -- | Incremental diff proofs are used to represent intermediate results of proof -- checking/construction. type IncrementalDiffProof = DiffProof (Maybe DiffSystem) -- | Provers whose sequencing is handled via the 'Monoid' instance. -- -- > p1 `mappend` p2 -- -- Is a prover that first runs p1 and then p2 on the resulting proof. newtype Prover = Prover { runProver :: ProofContext -- proof rules to use -> Int -- proof depth -> System -- original sequent to start with -> IncrementalProof -- original proof -> Maybe IncrementalProof -- resulting proof } instance Semigroup Prover where p1 <> p2 = Prover $ \ctxt d se -> runProver p1 ctxt d se >=> runProver p2 ctxt d se instance Monoid Prover where mempty = Prover $ \_ _ _ -> Just -- | Provers whose sequencing is handled via the 'Monoid' instance. -- -- > p1 `mappend` p2 -- -- Is a prover that first runs p1 and then p2 on the resulting proof. newtype DiffProver = DiffProver { runDiffProver :: DiffProofContext -- proof rules to use -> Int -- proof depth -> DiffSystem -- original sequent to start with -> IncrementalDiffProof -- original proof -> Maybe IncrementalDiffProof -- resulting proof } instance Semigroup DiffProver where p1 <> p2 = DiffProver $ \ctxt d se -> runDiffProver p1 ctxt d se >=> runDiffProver p2 ctxt d se instance Monoid DiffProver where mempty = DiffProver $ \_ _ _ -> Just -- | Map the proof generated by the prover. mapProverProof :: (IncrementalProof -> IncrementalProof) -> Prover -> Prover mapProverProof f p = Prover $ \ ctxt d se prf -> f <$> runProver p ctxt d se prf -- | Map the proof generated by the prover. mapDiffProverDiffProof :: (IncrementalDiffProof -> IncrementalDiffProof) -> DiffProver -> DiffProver mapDiffProverDiffProof f p = DiffProver $ \ctxt d se prf -> f <$> runDiffProver p ctxt d se prf -- | Prover that always fails. failProver :: Prover failProver = Prover (\ _ _ _ _ -> Nothing) -- | Prover that always fails. failDiffProver :: DiffProver failDiffProver = DiffProver (\_ _ _ _ -> Nothing) -- | Resorts to the second prover, if the first one is not successful. orelse :: Prover -> Prover -> Prover orelse p1 p2 = Prover $ \ctxt d se prf -> runProver p1 ctxt d se prf `mplus` runProver p2 ctxt d se prf -- | Resorts to the second prover, if the first one is not successful. orelseDiff :: DiffProver -> DiffProver -> DiffProver orelseDiff p1 p2 = DiffProver $ \ctxt d se prf -> runDiffProver p1 ctxt d se prf `mplus` runDiffProver p2 ctxt d se prf -- | Try to apply a prover. If it fails, just return the original proof. tryProver :: Prover -> Prover tryProver = (`orelse` mempty) -- | Try to execute one proof step using the given proof method. oneStepProver :: ProofMethod -> Prover oneStepProver method = Prover $ \ctxt _ se _ -> do cases <- execProofMethod ctxt method se return $ LNode (ProofStep method (Just se)) (M.map (unproven . Just) cases) -- | Try to execute one proof step using the given proof method. oneStepDiffProver :: DiffProofMethod -> DiffProver oneStepDiffProver method = DiffProver $ \ctxt _ se _ -> do cases <- execDiffProofMethod ctxt method se return $ LNode (DiffProofStep method (Just se)) (M.map (diffUnproven . Just) cases) -- | Replace the current proof with a sorry step and the given reason. sorryProver :: Maybe String -> Prover sorryProver reason = Prover $ \_ _ se _ -> return $ sorry reason (Just se) -- | Replace the current proof with a sorry step and the given reason. sorryDiffProver :: Maybe String -> DiffProver sorryDiffProver reason = DiffProver $ \_ _ se _ -> return $ diffSorry reason (Just se) -- | Apply a prover only to a sub-proof, fails if the subproof doesn't exist. focus :: ProofPath -> Prover -> Prover focus [] prover = prover focus path prover = Prover $ \ctxt d _ prf -> modifyAtPath (prover' ctxt (d + length path)) path prf where prover' ctxt d prf = do se <- psInfo (root prf) runProver prover ctxt d se prf -- | Apply a diff prover only to a sub-proof, fails if the subproof doesn't exist. focusDiff :: ProofPath -> DiffProver -> DiffProver focusDiff [] prover = prover focusDiff path prover = DiffProver $ \ctxt d _ prf -> modifyAtPathDiff (prover' ctxt (d + length path)) path prf where prover' ctxt d prf = do se <- dpsInfo (root prf) runDiffProver prover ctxt d se prf -- | Check the proof and handle new cases using the given prover. checkAndExtendProver :: Prover -> Prover checkAndExtendProver prover0 = Prover $ \ctxt d se prf -> return $ mapProofInfo snd $ checkProof ctxt (prover ctxt) d se prf where unhandledCase = sorry (Just "unhandled case") Nothing prover ctxt d se = fromMaybe unhandledCase $ runProver prover0 ctxt d se unhandledCase -- | Check the proof and handle new cases using the given prover. checkAndExtendDiffProver :: DiffProver -> DiffProver checkAndExtendDiffProver prover0 = DiffProver $ \ctxt d se prf -> return $ mapDiffProofInfo snd $ checkDiffProof ctxt (prover ctxt) d se prf where unhandledCase = diffSorry (Just "unhandled case") Nothing prover ctxt d se = fromMaybe unhandledCase $ runDiffProver prover0 ctxt d se unhandledCase -- | Replace all annotated sorry steps using the given prover. replaceSorryProver :: Prover -> Prover replaceSorryProver prover0 = Prover prover where prover ctxt d _ = return . replace where replace prf@(LNode (ProofStep (Sorry _) (Just se)) _) = fromMaybe prf $ runProver prover0 ctxt d se prf replace (LNode ps cases) = LNode ps $ M.map replace cases -- | Replace all annotated sorry steps using the given prover. replaceDiffSorryProver :: DiffProver -> DiffProver replaceDiffSorryProver prover0 = DiffProver prover where prover ctxt d _ = return . replace where replace prf@(LNode (DiffProofStep (DiffSorry _) (Just se)) _) = fromMaybe prf $ runDiffProver prover0 ctxt d se prf replace (LNode ps cases) = LNode ps $ M.map replace cases -- | Use the first prover that works. firstProver :: [Prover] -> Prover firstProver = foldr orelse failProver -- | Prover that does one contradiction step. contradictionProver :: Prover contradictionProver = Prover $ \ctxt d sys prf -> runProver (firstProver $ map oneStepProver $ (Contradiction . Just <$> contradictions ctxt sys)) ctxt d sys prf -- | Use the first diff prover that works. firstDiffProver :: [DiffProver] -> DiffProver firstDiffProver = foldr orelseDiff failDiffProver -- | Diff Prover that does one contradiction step if possible. contradictionDiffProver :: DiffProver contradictionDiffProver = DiffProver $ \ctxt d sys prf -> case (L.get dsCurrentRule sys, L.get dsSide sys, L.get dsSystem sys) of (Just _, Just s, Just sys') -> runDiffProver (firstDiffProver $ map oneStepDiffProver $ (DiffBackwardSearchStep . Contradiction . Just <$> contradictions (eitherProofContext ctxt s) sys')) ctxt d sys prf (_ , _ , _ ) -> Nothing ------------------------------------------------------------------------------ -- Automatic Prover's ------------------------------------------------------------------------------ data SolutionExtractor = CutDFS | CutBFS | CutSingleThreadDFS | CutNothing deriving( Eq, Ord, Show, Read, Generic, NFData, Binary ) data AutoProver = AutoProver { apDefaultHeuristic :: Maybe Heuristic , apBound :: Maybe Int , apCut :: SolutionExtractor } deriving ( Generic, NFData, Binary ) selectHeuristic :: AutoProver -> ProofContext -> Heuristic selectHeuristic prover ctx = fromMaybe (defaultHeuristic False) (apDefaultHeuristic prover <|> L.get pcHeuristic ctx) selectDiffHeuristic :: AutoProver -> DiffProofContext -> Heuristic selectDiffHeuristic prover ctx = fromMaybe (defaultHeuristic True) (apDefaultHeuristic prover <|> L.get pcHeuristic (L.get dpcPCLeft ctx)) runAutoProver :: AutoProver -> Prover runAutoProver aut@(AutoProver _ bound cut) = mapProverProof cutSolved $ maybe id boundProver bound autoProver where cutSolved = case cut of CutDFS -> cutOnSolvedDFS CutBFS -> cutOnSolvedBFS CutSingleThreadDFS -> cutOnSolvedSingleThreadDFS CutNothing -> id -- | The standard automatic prover that ignores the existing proof and -- tries to find one by itself. autoProver :: Prover autoProver = Prover $ \ctxt depth sys _ -> return $ fmap (fmap Just) $ annotateWithSystems ctxt sys $ proveSystemDFS (selectHeuristic aut ctxt) ctxt depth sys -- | Bound the depth of proofs generated by the given prover. boundProver :: Int -> Prover -> Prover boundProver b p = Prover $ \ctxt d se prf -> boundProofDepth b <$> runProver p ctxt d se prf runAutoDiffProver :: AutoProver -> DiffProver runAutoDiffProver aut@(AutoProver _ bound cut) = mapDiffProverDiffProof cutSolved $ maybe id boundProver bound autoProver where cutSolved = case cut of CutDFS -> cutOnSolvedDFSDiff CutBFS -> cutOnSolvedBFSDiff CutSingleThreadDFS -> cutOnSolvedSingleThreadDFSDiff CutNothing -> id -- | The standard automatic prover that ignores the existing proof and -- tries to find one by itself. autoProver :: DiffProver autoProver = DiffProver $ \ctxt depth sys _ -> return $ fmap (fmap Just) $ annotateWithDiffSystems ctxt sys $ proveDiffSystemDFS (selectDiffHeuristic aut ctxt) ctxt depth sys -- | Bound the depth of proofs generated by the given prover. boundProver :: Int -> DiffProver -> DiffProver boundProver b p = DiffProver $ \ctxt d se prf -> boundDiffProofDepth b <$> runDiffProver p ctxt d se prf -- | The result of one pass of iterative deepening. data IterDeepRes = NoSolution | MaybeNoSolution | Solution ProofPath instance Semigroup IterDeepRes where x@(Solution _) <> _ = x _ <> y@(Solution _) = y MaybeNoSolution <> _ = MaybeNoSolution _ <> MaybeNoSolution = MaybeNoSolution NoSolution <> NoSolution = NoSolution instance Monoid IterDeepRes where mempty = NoSolution -- | @cutOnSolvedSingleThreadDFS prf@ removes all other cases if an attack is -- found. The attack search is performed using a single-thread DFS traversal. -- -- FIXME: Note that this function may use a lot of space, as it holds onto the -- whole proof tree. cutOnSolvedSingleThreadDFS :: Proof (Maybe a) -> Proof (Maybe a) cutOnSolvedSingleThreadDFS prf0 = go $ insertPaths prf0 where go prf = case findSolved prf of NoSolution -> prf0 Solution path -> extractSolved path prf0 MaybeNoSolution -> error "Theory.Constraint.cutOnSolvedSingleThreadDFS: impossible, MaybeNoSolution in single thread dfs" where findSolved node = case node of -- do not search in nodes that are not annotated LNode (ProofStep _ (Nothing, _ )) _ -> NoSolution LNode (ProofStep Solved (Just _ , path)) _ -> Solution path LNode (ProofStep _ (Just _ , _ )) cs -> foldMap findSolved cs extractSolved [] p = p extractSolved (label:ps) (LNode pstep m) = case M.lookup label m of Just subprf -> LNode pstep (M.fromList [(label, extractSolved ps subprf)]) Nothing -> error "Theory.Constraint.cutOnSolvedSingleThreadDFS: impossible, extractSolved failed, invalid path" -- | @cutOnSolvedSingleThreadDFSDiffDFS prf@ removes all other cases if an -- attack is found. The attack search is performed using a single-thread DFS -- traversal. -- -- FIXME: Note that this function may use a lot of space, as it holds onto the -- whole proof tree. cutOnSolvedSingleThreadDFSDiff :: DiffProof (Maybe a) -> DiffProof (Maybe a) cutOnSolvedSingleThreadDFSDiff prf0 = go $ insertPathsDiff prf0 where go prf = case findSolved prf of NoSolution -> prf0 Solution path -> extractSolved path prf0 MaybeNoSolution -> error "Theory.Constraint.cutOnSolvedSingleThreadDFSDiff: impossible, MaybeNoSolution in single thread dfs" where findSolved node = case node of -- do not search in nodes that are not annotated LNode (DiffProofStep _ (Nothing, _ )) _ -> NoSolution LNode (DiffProofStep DiffAttack (Just _ , path)) _ -> Solution path LNode (DiffProofStep _ (Just _ , _ )) cs -> foldMap findSolved cs extractSolved [] p = p extractSolved (label:ps) (LNode pstep m) = case M.lookup label m of Just subprf -> LNode pstep (M.fromList [(label, extractSolved ps subprf)]) Nothing -> error "Theory.Constraint.cutOnSolvedSingleThreadDFSDiff: impossible, extractSolved failed, invalid path" -- | @cutOnSolvedDFS prf@ removes all other cases if an attack is found. The -- attack search is performed using a parallel DFS traversal with iterative -- deepening. -- Note that when an attack is found, other, already started threads will not be -- stopped. They will first run to completion, and only afterwards will the proof -- complete. If this is undesirable bahavior, use cutOnSolvedSingleThreadDFS. -- -- FIXME: Note that this function may use a lot of space, as it holds onto the -- whole proof tree. cutOnSolvedDFS :: Proof (Maybe a) -> Proof (Maybe a) cutOnSolvedDFS prf0 = go (4 :: Integer) $ insertPaths prf0 where go dMax prf = case findSolved 0 prf of NoSolution -> prf0 MaybeNoSolution -> go (2 * dMax) prf Solution path -> extractSolved path prf0 where findSolved d node | d >= dMax = MaybeNoSolution | otherwise = case node of -- do not search in nodes that are not annotated LNode (ProofStep _ (Nothing, _ )) _ -> NoSolution LNode (ProofStep Solved (Just _ , path)) _ -> Solution path LNode (ProofStep _ (Just _ , _ )) cs -> foldMap (findSolved (succ d)) (cs `using` parTraversable nfProofMethod) nfProofMethod node = do void $ rseq (psMethod $ root node) void $ rseq (psInfo $ root node) void $ rseq (children node) return node extractSolved [] p = p extractSolved (label:ps) (LNode pstep m) = case M.lookup label m of Just subprf -> LNode pstep (M.fromList [(label, extractSolved ps subprf)]) Nothing -> error "Theory.Constraint.cutOnSolvedDFS: impossible, extractSolved failed, invalid path" -- | @cutOnSolvedDFSDiff prf@ removes all other cases if an attack is found. The -- attack search is performed using a parallel DFS traversal with iterative -- deepening. -- Note that when an attack is found, other, already started threads will not be -- stopped. They will first run to completion, and only afterwards will the proof -- complete. If this is undesirable bahavior, use cutOnSolvedSingleThreadDFSDiff. -- -- FIXME: Note that this function may use a lot of space, as it holds onto the -- whole proof tree. cutOnSolvedDFSDiff :: DiffProof (Maybe a) -> DiffProof (Maybe a) cutOnSolvedDFSDiff prf0 = go (4 :: Integer) $ insertPathsDiff prf0 where go dMax prf = case findSolved 0 prf of NoSolution -> prf0 MaybeNoSolution -> go (2 * dMax) prf Solution path -> extractSolved path prf0 where findSolved d node | d >= dMax = MaybeNoSolution | otherwise = case node of -- do not search in nodes that are not annotated LNode (DiffProofStep _ (Nothing, _ )) _ -> NoSolution LNode (DiffProofStep DiffAttack (Just _ , path)) _ -> Solution path LNode (DiffProofStep _ (Just _ , _ )) cs -> foldMap (findSolved (succ d)) (cs `using` parTraversable nfProofMethod) nfProofMethod node = do void $ rseq (dpsMethod $ root node) void $ rseq (dpsInfo $ root node) void $ rseq (children node) return node extractSolved [] p = p extractSolved (label:ps) (LNode pstep m) = case M.lookup label m of Just subprf -> LNode pstep (M.fromList [(label, extractSolved ps subprf)]) Nothing -> error "Theory.Constraint.cutOnSolvedDFSDiff: impossible, extractSolved failed, invalid path" -- | Search for attacks in a BFS manner. cutOnSolvedBFS :: Proof (Maybe a) -> Proof (Maybe a) cutOnSolvedBFS = go (1::Int) where go l prf = -- FIXME: See if that poor man's logging could be done better. trace ("searching for attacks at depth: " ++ show l) $ case S.runState (checkLevel l prf) CompleteProof of (_, UndeterminedProof) -> error "cutOnSolvedBFS: impossible" (_, CompleteProof) -> prf (_, IncompleteProof) -> go (l+1) prf (prf', TraceFound) -> trace ("attack found at depth: " ++ show l) prf' checkLevel 0 (LNode step@(ProofStep Solved (Just _)) _) = S.put TraceFound >> return (LNode step M.empty) checkLevel 0 prf@(LNode (ProofStep _ x) cs) | M.null cs = return prf | otherwise = do st <- S.get msg <- case st of TraceFound -> return $ "ignored (attack exists)" _ -> S.put IncompleteProof >> return "bound reached" return $ LNode (ProofStep (Sorry (Just msg)) x) M.empty checkLevel l prf@(LNode step cs) | isNothing (psInfo step) = return prf | otherwise = LNode step <$> traverse (checkLevel (l-1)) cs -- | Search for attacks in a BFS manner. cutOnSolvedBFSDiff :: DiffProof (Maybe a) -> DiffProof (Maybe a) cutOnSolvedBFSDiff = go (1::Int) where go l prf = -- FIXME: See if that poor man's logging could be done better. trace ("searching for attacks at depth: " ++ show l) $ case S.runState (checkLevel l prf) CompleteProof of (_, UndeterminedProof) -> error "cutOnSolvedBFS: impossible" (_, CompleteProof) -> prf (_, IncompleteProof) -> go (l+1) prf (prf', TraceFound) -> trace ("attack found at depth: " ++ show l) prf' checkLevel 0 (LNode step@(DiffProofStep DiffAttack (Just _)) _) = S.put TraceFound >> return (LNode step M.empty) checkLevel 0 prf@(LNode (DiffProofStep _ x) cs) | M.null cs = return prf | otherwise = do st <- S.get msg <- case st of TraceFound -> return $ "ignored (attack exists)" _ -> S.put IncompleteProof >> return "bound reached" return $ LNode (DiffProofStep (DiffSorry (Just msg)) x) M.empty checkLevel l prf@(LNode step cs) | isNothing (dpsInfo step) = return prf | otherwise = LNode step <$> traverse (checkLevel (l-1)) cs -- | @proveSystemDFS rules se@ explores all solutions of the initial -- constraint system using a depth-first-search strategy to resolve the -- non-determinism wrt. what goal to solve next. This proof can be of -- infinite depth, if the proof strategy loops. -- -- Use 'annotateWithSystems' to annotate the proof tree with the constraint -- systems. proveSystemDFS :: Heuristic -> ProofContext -> Int -> System -> Proof () proveSystemDFS heuristic ctxt d0 sys0 = prove d0 sys0 where prove !depth sys = case rankProofMethods (useHeuristic heuristic depth) ctxt sys of [] -> node Solved M.empty (method, (cases, _expl)):_ -> node method cases where node method cases = LNode (ProofStep method ()) (M.map (prove (succ depth)) cases) -- | @proveSystemDFS rules se@ explores all solutions of the initial -- constraint system using a depth-first-search strategy to resolve the -- non-determinism wrt. what goal to solve next. This proof can be of -- infinite depth, if the proof strategy loops. -- -- Use 'annotateWithSystems' to annotate the proof tree with the constraint -- systems. proveDiffSystemDFS :: Heuristic -> DiffProofContext -> Int -> DiffSystem -> DiffProof () proveDiffSystemDFS heuristic ctxt d0 sys0 = prove d0 sys0 where prove !depth sys = case rankDiffProofMethods (useHeuristic heuristic depth) ctxt sys of [] -> node (DiffSorry (Just "Cannot prove")) M.empty (method, (cases, _expl)):_ -> node method cases where node method cases = LNode (DiffProofStep method ()) (M.map (prove (succ depth)) cases) ------------------------------------------------------------------------------ -- Pretty printing ------------------------------------------------------------------------------ prettyProof :: HighlightDocument d => Proof a -> d prettyProof = prettyProofWith (prettyProofMethod . psMethod) (const id) prettyProofWith :: HighlightDocument d => (ProofStep a -> d) -- ^ Make proof step pretty -> (ProofStep a -> d -> d) -- ^ Make whole case pretty -> Proof a -- ^ The proof to prettify -> d prettyProofWith prettyStep prettyCase = ppPrf where ppPrf (LNode ps cs) = ppCases ps (M.toList cs) ppCases ps@(ProofStep Solved _) [] = prettyStep ps ppCases ps [] = prettyCase ps (kwBy <> text " ") <> prettyStep ps ppCases ps [("", prf)] = prettyStep ps $-$ ppPrf prf ppCases ps cases = prettyStep ps $-$ (vcat $ intersperse (prettyCase ps kwNext) $ map ppCase cases) $-$ prettyCase ps kwQED ppCase (name, prf) = nest 2 $ (prettyCase (root prf) $ kwCase <-> text name) $-$ ppPrf prf prettyDiffProof :: HighlightDocument d => DiffProof a -> d prettyDiffProof = prettyDiffProofWith (prettyDiffProofMethod . dpsMethod) (const id) prettyDiffProofWith :: HighlightDocument d => (DiffProofStep a -> d) -- ^ Make proof step pretty -> (DiffProofStep a -> d -> d) -- ^ Make whole case pretty -> DiffProof a -- ^ The proof to prettify -> d prettyDiffProofWith prettyStep prettyCase = ppPrf where ppPrf (LNode ps cs) = ppCases ps (M.toList cs) ppCases ps@(DiffProofStep DiffMirrored _) [] = prettyStep ps ppCases ps [] = prettyCase ps (kwBy <> text " ") <> prettyStep ps ppCases ps [("", prf)] = prettyStep ps $-$ ppPrf prf ppCases ps cases = prettyStep ps $-$ (vcat $ intersperse (prettyCase ps kwNext) $ map ppCase cases) $-$ prettyCase ps kwQED ppCase (name, prf) = nest 2 $ (prettyCase (root prf) $ kwCase <-> text name) $-$ ppPrf prf -- | Convert a proof status to a readable string. showProofStatus :: SystemTraceQuantifier -> ProofStatus -> String showProofStatus ExistsNoTrace TraceFound = "falsified - found trace" showProofStatus ExistsNoTrace CompleteProof = "verified" showProofStatus ExistsSomeTrace CompleteProof = "falsified - no trace found" showProofStatus ExistsSomeTrace TraceFound = "verified" showProofStatus _ IncompleteProof = "analysis incomplete" showProofStatus _ UndeterminedProof = "analysis undetermined" -- | Convert a proof status to a readable string. showDiffProofStatus :: ProofStatus -> String showDiffProofStatus TraceFound = "falsified - found trace" showDiffProofStatus CompleteProof = "verified" showDiffProofStatus IncompleteProof = "analysis incomplete" showDiffProofStatus UndeterminedProof = "analysis undetermined" -- Instances -------------------- instance (Ord l, NFData l, NFData a) => NFData (LTree l a) where rnf (LNode r m) = rnf r `seq` rnf m instance (Ord l, Binary l, Binary a) => Binary (LTree l a) where put (LNode r m) = put r >> put m get = LNode <$> get <*> get
tamarin-prover/tamarin-prover
lib/theory/src/Theory/Proof.hs
gpl-3.0
44,308
0
17
11,911
10,668
5,468
5,200
687
7
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Constraint.Strategy.Cyclic ( CyclicStrategy -- , selectCyclicArrangement ) where import Constraint.Strategy import Control.Applicative ((<$>),(<*>),(<|>)) import Control.Arrow (second) import Control.Monad.State import Control.Monad.Random (MonadRandom) import Data.List (delete,find,minimumBy) import Data.Map ((!),assocs,empty,fromList,keys) import Data.Foldable (foldl') import Data.Maybe (mapMaybe) import Data.Ord (comparing) import Data.Tree import System.Random import System.Random.Shuffle data CyclicStrategy = Cyclic type CyclicArrangement a = [a] -- | Represents a valid secret santa arrangement -- | which is also a Hamiltonian Cycle instance ConstraintStrategy CyclicStrategy where feasibleArrangements = const $ fmap cycleToMap . feasibleCyclicArrangements selectArrangement = const $ cycleToMap . selectCyclicArrangement -- | Converts a CyclicArrangement to a normal Arrangement cycleToMap :: Ord a => CyclicArrangement a -> Arrangement a cycleToMap [] = fromList [] cycleToMap (x:xs) = fromList $ cycleToMap' (x:xs) where cycleToMap' [] = [] cycleToMap' [y] = [(y,x)] cycleToMap' (y:z:zs) = (y,z) : cycleToMap' (z:zs) -- | List of all hamiltonian cycles satisfying the constraints feasibleCyclicArrangements :: ConstraintMap a -> [CyclicArrangement a] feasibleCyclicArrangements xs = cycles len $ mapToTree xs where len = foldl' (\x _ -> x+1) 0 xs -- | Builds an intermidate Tree data structure used for cycle search mapToTree :: Eq a => ConstraintMap a -> Tree a mapToTree = constructNode <$> assocs <*> (minimumBy (comparing (length . snd)) . assocs) -- | Recursively builds Tree from associating list constructNode :: Eq a => [(a,[a])] -> (a,[a]) -> Tree a constructNode ys (x,xs) -- if the "MapList" is empty, we cannot recurse | null ys = Node x [] -- otherwise we create the node and recurse for it's children | otherwise = Node x $ fmap (constructNode ys') xs' where -- remove the current node from the "MapList" -- remove it's reference from the value list of all keys ys' = fmap (second (delete x)) $ delete (x,xs) ys -- get the node data to expand -- ignore nodes with xs' = mapMaybe (flip find ys' . (\y -> (==y).fst)) xs -- | Augmented Depth-Limited Search on tree structure -- | to find hamiltonian cycles satisfying the constraints cycles :: Int -> Tree a -> [CyclicArrangement a] cycles 1 tree = [[rootLabel tree]] cycles n tree | (null . subForest) tree = [] | otherwise = concatMap ( fmap (rootLabel tree :) . filter (not.null) . cycles (n-1) ) $ subForest tree -- | Augmented depth-limited search -- | over a randomization of the hamiltonian cycle search space. -- | Returns the first valid hamiltonian cycle found during the random search -- | /Ω(n)/ & /O(n!)/ -- | Best Case Complexity: -- | Linear time to generate a valid solution in the first few attempts -- | Worst Case Complexity: -- | Factorial time to generate all possible solutions -- | and deterimine none satisfy constraints selectCyclicArrangement :: MonadRandom m => ConstraintMap a -> m (Maybe (CyclicArrangement a)) selectCyclicArrangement originalConstraints = newStdGen >>= return . selectCyclicArrangement' originalConstraints 0 root where -- The height of the expanded tree iff it -- contains a path representing a hamiltonian cycle height = pred . length $ keys originalConstraints -- Without loss of generality, we can arbitrarily fix the root node -- We choose for complexity sake, to select the key with -- the most constrainted value set. root = mostConstraintedKey originalConstraints -- Recursive Definition selectCyclicArrangement' :: RandomGen gen => ConstraintMap a -> Int -> a -> gen -> Maybe (CyclicArrangement a) selectCyclicArrangement' constraints depth key gen | constraints == empty || not atTerminalDepth && null branches || atTerminalDepth && not validTerminalNode = Nothing | atTerminalDepth && validTerminalNode = Just [key] | otherwise = prependKey . coalesce . map branchMay $ zip branches' branchGens where atTerminalDepth = depth == height validTerminalNode = root `elem` originalRecipients originalRecipients = originalConstraints ! key prependKey = fmap (key:) branchMay = uncurry $ selectCyclicArrangement' constraints' (depth + 1) branches = constraints ! key branches' = shuffle' branches branchCount shuffleGen branchCount = length branches constraints' = reduceReceipiants key constraints (branchGens,shuffleGen) = runState (replicateM branchCount (state split >> get)) gen mostConstraintedKey :: ConstraintMap a -> a mostConstraintedKey = fst . minimumBy (comparing (length . snd)) . assocs reduceReceipiants :: Eq a => a -> ConstraintMap a -> ConstraintMap a reduceReceipiants key = fmap (delete key) coalesce :: [Maybe a] -> Maybe a coalesce = foldr (<|>) Nothing
recursion-ninja/SecretSanta
Constraint/Strategy/Cyclic.hs
gpl-3.0
5,382
0
14
1,283
1,274
680
594
86
3
-- Laatste element van een lijst laatste::[Int]->Int laatste l = last l -- Herhaal n keer het getal x in een lijst herhaal::Int->Int->[Int] herhaal n x = take n (repeat x) -- Metalijst -> Platte lijst lineariseer::[[Int]]->[Int] lineariseer a = concat a -- Lijst van getallen tussen 2 gegeven getallen bereik::Int->Int->[Int] bereik a b = scanl (+) 1 (take (b-a-1) (repeat a)) -- Verwijder veelvouden van een getal uit een lijst verwijderVeelvouden::Int->[Int]->[Int] verwijderVeelvouden a b = filter (\x -> not $ (mod x a)==0) b -- Werkt niet vvalt::Int->[Int]->[Int] vvalt a b = filter (not . 0==(flip . mod ($) a)) b
jorenverspeurt/joren-assignments-haskell
horsdoeuvres-lf.hs
gpl-3.0
621
0
11
103
273
148
125
12
1
import Control.Monad import System.Directory import System.IO reverseList :: [a] -> [a] reverseList [] = [] reverseList (x:xs) = reverseList xs ++ [x] rename :: FilePath -> String -> IO () rename a filePath = renameFile filePath (filePath ++ a) bulkRename :: FilePath -> String -> IO () bulkRename filePath suffix = do files <- getDirectoryContents filePath let correctedFilePath = map ((filePath ++ "/") ++ ) (filter (/= "..") (filter (/= ".") files)) mapM_ (rename suffix) correctedFilePath return () squash :: [String] -> String squash [] = "" squash [x] = x squash (x:xs) = x ++ squash xs combineContent :: FilePath -> String -> IO () combineContent inputDirectory outputFile = do files <- getDirectoryContents inputDirectory let correctedFilePath = map ((inputDirectory ++ "/") ++ ) (filter (/= "..") (filter (/= ".") files)) content <- mapM readFile correctedFilePath print content writeFile outputFile (squash content) return () combineContentWithHandle :: FilePath -> String -> IO () combineContentWithHandle inputDirectory outputFile = do files <- getDirectoryContents inputDirectory let correctedFilePath = map ((inputDirectory ++ "/") ++ ) (filter (/= "..") (filter (/= ".") files)) withFile outputFile WriteMode $ \handle -> forM_ correctedFilePath $ \element -> do content <- readFile element hPutStrLn handle content return () {- main :: IO () main = do [filePath, suffix] <- getArgs bulkRename filePath suffix -} main :: IO () main = do input <- getLine putStrLn (reverse input)
jgonsior/haskellCourse
ex5.hs
gpl-3.0
1,650
0
15
383
576
287
289
42
1
module Text.Parse.SvgPath.Parsing ( svgPath , p_moveto_drawto_command_group , p_drawto_command , p_moveto , p_lineto , p_closepath , p_comma_wsp , p_coordinate_pair , p_float , p_number , PathInstruction ( MoveTo , LineTo , HorizontalLineTo , VerticalLineTo , CurveTo , SmoothCurveTo , QuadraticBezierCurveTo , SmoothQuadraticBezierCurveTo , EllipticalArcTo , ClosePath ) , Path , Coordinates ) where import Control.Applicative hiding (many, optional, (<|>)) import Text.ParserCombinators.Parsec import Numeric (readSigned, readFloat) data PathInstruction = MoveTo Bool Coordinates | LineTo Bool Coordinates | HorizontalLineTo Bool Double | VerticalLineTo Bool Double | CurveTo Bool Coordinates Coordinates Coordinates | SmoothCurveTo Bool Coordinates Coordinates | QuadraticBezierCurveTo Bool Coordinates Coordinates | SmoothQuadraticBezierCurveTo Bool Coordinates | EllipticalArcTo Coordinates Double Bool Bool Coordinates | ClosePath deriving (Show, Eq) type Path = [PathInstruction] type Coordinates = (Double, Double) -- Parser modeled after http://www.w3.org/TR/SVG/paths.html#PathDataBNF svgPath :: CharParser () Path svgPath = do spaces paths <- p_moveto_drawto_command_group `sepEndBy` spaces eof return $ concat paths p_moveto_drawto_command_group :: CharParser () Path p_moveto_drawto_command_group = do m <- p_moveto spaces ds <- p_drawto_command `sepEndBy` spaces return $ m ++ (concat ds) p_drawto_command :: CharParser () Path p_drawto_command = choice [ p_lineto <?> "LineTo" , p_closepath <?> "ClosePath" ] p_moveto :: CharParser () Path p_moveto = do command <- oneOf "Mm" <* spaces let isRelative = command == 'm' mkLineto (x, y) = LineTo isRelative (x, y) coords <- p_coordinate_pair `sepEndBy` p_comma_wsp let (x, y) = head coords move = MoveTo isRelative (x, y) return $ move:(map mkLineto (tail coords)) p_lineto :: CharParser () Path p_lineto = do command <- oneOf "Ll" <* spaces let isRelative = command == 'l' mkLineto (x, y) = LineTo isRelative (x, y) coords <- p_coordinate_pair `sepEndBy` p_comma_wsp let (x, y) = head coords line = LineTo isRelative (x, y) return $ line:(map mkLineto (tail coords)) p_closepath :: CharParser () Path p_closepath = oneOf "Zz" >> return [ClosePath] p_comma_wsp :: CharParser () () p_comma_wsp = try (spaces >> char ',' >> spaces) <|> skipMany1 space p_coordinate_pair :: CharParser () Coordinates p_coordinate_pair = do x <- p_number p_comma_wsp y <- p_number return (x, y) p_float :: CharParser () Double p_float = do s <- getInput case readSigned readFloat s of [(n, s')] -> n <$ setInput s' _ -> empty p_number :: CharParser () Double p_number = (optional $ char '+') *> (p_float <?> "number")
r24y/svg2gcode
Text/Parse/SvgPath/Parsing.hs
gpl-3.0
3,355
0
11
1,072
866
468
398
89
2
import Text.Parsec.String (Parser) import Text.ParserCombinators.Parsec main = do input <- readFile "input.txt" case parse_str input of Left err -> print err Right n -> print (n-1) parse_str :: String -> Either ParseError Int parse_str s = parse message "(unkwown)" s message :: Parser Int message = many segment >>= return . sum segment :: Parser Int segment = try marker <|> text text :: Parser Int text = many1 (noneOf "(") >>= return . length marker :: Parser Int marker = do char '(' cs <- uint char 'x' n <- uint char ')' ss <- count cs anyChar case parse_str ss of Left err -> fail $ show err Right m -> return (n*m) uint :: Parser Int uint = read <$> many1 digit
ayron/AoC
2016/Day 9/solution2.hs
gpl-3.0
714
0
12
168
299
141
158
28
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Datastore.Types.Sum -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.Datastore.Types.Sum where import Network.Google.Prelude -- | The direction to order by. Defaults to \`ASCENDING\`. data PropertyOrderDirection = DirectionUnspecified -- ^ @DIRECTION_UNSPECIFIED@ -- Unspecified. This value must not be used. | Ascending -- ^ @ASCENDING@ -- Ascending. | Descending -- ^ @DESCENDING@ -- Descending. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PropertyOrderDirection instance FromHttpApiData PropertyOrderDirection where parseQueryParam = \case "DIRECTION_UNSPECIFIED" -> Right DirectionUnspecified "ASCENDING" -> Right Ascending "DESCENDING" -> Right Descending x -> Left ("Unable to parse PropertyOrderDirection from: " <> x) instance ToHttpApiData PropertyOrderDirection where toQueryParam = \case DirectionUnspecified -> "DIRECTION_UNSPECIFIED" Ascending -> "ASCENDING" Descending -> "DESCENDING" instance FromJSON PropertyOrderDirection where parseJSON = parseJSONText "PropertyOrderDirection" instance ToJSON PropertyOrderDirection where toJSON = toJSONText -- | The operator for combining multiple filters. data CompositeFilterOp = OperatorUnspecified -- ^ @OPERATOR_UNSPECIFIED@ -- Unspecified. This value must not be used. | And -- ^ @AND@ -- The results are required to satisfy each of the combined filters. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CompositeFilterOp instance FromHttpApiData CompositeFilterOp where parseQueryParam = \case "OPERATOR_UNSPECIFIED" -> Right OperatorUnspecified "AND" -> Right And x -> Left ("Unable to parse CompositeFilterOp from: " <> x) instance ToHttpApiData CompositeFilterOp where toQueryParam = \case OperatorUnspecified -> "OPERATOR_UNSPECIFIED" And -> "AND" instance FromJSON CompositeFilterOp where parseJSON = parseJSONText "CompositeFilterOp" instance ToJSON CompositeFilterOp where toJSON = toJSONText -- | The result type for every entity in \`entity_results\`. data QueryResultBatchEntityResultType = QRBERTResultTypeUnspecified -- ^ @RESULT_TYPE_UNSPECIFIED@ -- Unspecified. This value is never used. | QRBERTFull -- ^ @FULL@ -- The key and properties. | QRBERTProjection -- ^ @PROJECTION@ -- A projected subset of properties. The entity may have no key. | QRBERTKeyOnly -- ^ @KEY_ONLY@ -- Only the key. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable QueryResultBatchEntityResultType instance FromHttpApiData QueryResultBatchEntityResultType where parseQueryParam = \case "RESULT_TYPE_UNSPECIFIED" -> Right QRBERTResultTypeUnspecified "FULL" -> Right QRBERTFull "PROJECTION" -> Right QRBERTProjection "KEY_ONLY" -> Right QRBERTKeyOnly x -> Left ("Unable to parse QueryResultBatchEntityResultType from: " <> x) instance ToHttpApiData QueryResultBatchEntityResultType where toQueryParam = \case QRBERTResultTypeUnspecified -> "RESULT_TYPE_UNSPECIFIED" QRBERTFull -> "FULL" QRBERTProjection -> "PROJECTION" QRBERTKeyOnly -> "KEY_ONLY" instance FromJSON QueryResultBatchEntityResultType where parseJSON = parseJSONText "QueryResultBatchEntityResultType" instance ToJSON QueryResultBatchEntityResultType where toJSON = toJSONText -- | The state of the query after the current batch. data QueryResultBatchMoreResults = MoreResultsTypeUnspecified -- ^ @MORE_RESULTS_TYPE_UNSPECIFIED@ -- Unspecified. This value is never used. | NotFinished -- ^ @NOT_FINISHED@ -- There may be additional batches to fetch from this query. | MoreResultsAfterLimit -- ^ @MORE_RESULTS_AFTER_LIMIT@ -- The query is finished, but there may be more results after the limit. | MoreResultsAfterCursor -- ^ @MORE_RESULTS_AFTER_CURSOR@ -- The query is finished, but there may be more results after the end -- cursor. | NoMoreResults -- ^ @NO_MORE_RESULTS@ -- The query has been exhausted. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable QueryResultBatchMoreResults instance FromHttpApiData QueryResultBatchMoreResults where parseQueryParam = \case "MORE_RESULTS_TYPE_UNSPECIFIED" -> Right MoreResultsTypeUnspecified "NOT_FINISHED" -> Right NotFinished "MORE_RESULTS_AFTER_LIMIT" -> Right MoreResultsAfterLimit "MORE_RESULTS_AFTER_CURSOR" -> Right MoreResultsAfterCursor "NO_MORE_RESULTS" -> Right NoMoreResults x -> Left ("Unable to parse QueryResultBatchMoreResults from: " <> x) instance ToHttpApiData QueryResultBatchMoreResults where toQueryParam = \case MoreResultsTypeUnspecified -> "MORE_RESULTS_TYPE_UNSPECIFIED" NotFinished -> "NOT_FINISHED" MoreResultsAfterLimit -> "MORE_RESULTS_AFTER_LIMIT" MoreResultsAfterCursor -> "MORE_RESULTS_AFTER_CURSOR" NoMoreResults -> "NO_MORE_RESULTS" instance FromJSON QueryResultBatchMoreResults where parseJSON = parseJSONText "QueryResultBatchMoreResults" instance ToJSON QueryResultBatchMoreResults where toJSON = toJSONText -- | A null value. data ValueNullValue = NullValue -- ^ @NULL_VALUE@ -- Null value. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ValueNullValue instance FromHttpApiData ValueNullValue where parseQueryParam = \case "NULL_VALUE" -> Right NullValue x -> Left ("Unable to parse ValueNullValue from: " <> x) instance ToHttpApiData ValueNullValue where toQueryParam = \case NullValue -> "NULL_VALUE" instance FromJSON ValueNullValue where parseJSON = parseJSONText "ValueNullValue" instance ToJSON ValueNullValue where toJSON = toJSONText -- | The non-transactional read consistency to use. Cannot be set to -- \`STRONG\` for global queries. data ReadOptionsReadConsistency = ReadConsistencyUnspecified -- ^ @READ_CONSISTENCY_UNSPECIFIED@ -- Unspecified. This value must not be used. | Strong -- ^ @STRONG@ -- Strong consistency. | Eventual -- ^ @EVENTUAL@ -- Eventual consistency. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReadOptionsReadConsistency instance FromHttpApiData ReadOptionsReadConsistency where parseQueryParam = \case "READ_CONSISTENCY_UNSPECIFIED" -> Right ReadConsistencyUnspecified "STRONG" -> Right Strong "EVENTUAL" -> Right Eventual x -> Left ("Unable to parse ReadOptionsReadConsistency from: " <> x) instance ToHttpApiData ReadOptionsReadConsistency where toQueryParam = \case ReadConsistencyUnspecified -> "READ_CONSISTENCY_UNSPECIFIED" Strong -> "STRONG" Eventual -> "EVENTUAL" instance FromJSON ReadOptionsReadConsistency where parseJSON = parseJSONText "ReadOptionsReadConsistency" instance ToJSON ReadOptionsReadConsistency where toJSON = toJSONText -- | V1 error format. data Xgafv = X1 -- ^ @1@ -- v1 error format | X2 -- ^ @2@ -- v2 error format deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable Xgafv instance FromHttpApiData Xgafv where parseQueryParam = \case "1" -> Right X1 "2" -> Right X2 x -> Left ("Unable to parse Xgafv from: " <> x) instance ToHttpApiData Xgafv where toQueryParam = \case X1 -> "1" X2 -> "2" instance FromJSON Xgafv where parseJSON = parseJSONText "Xgafv" instance ToJSON Xgafv where toJSON = toJSONText -- | The operator to filter by. data PropertyFilterOp = PFOOperatorUnspecified -- ^ @OPERATOR_UNSPECIFIED@ -- Unspecified. This value must not be used. | PFOLessThan -- ^ @LESS_THAN@ -- Less than. | PFOLessThanOrEqual -- ^ @LESS_THAN_OR_EQUAL@ -- Less than or equal. | PFOGreaterThan -- ^ @GREATER_THAN@ -- Greater than. | PFOGreaterThanOrEqual -- ^ @GREATER_THAN_OR_EQUAL@ -- Greater than or equal. | PFOEqual -- ^ @EQUAL@ -- Equal. | PFOHasAncestor -- ^ @HAS_ANCESTOR@ -- Has ancestor. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PropertyFilterOp instance FromHttpApiData PropertyFilterOp where parseQueryParam = \case "OPERATOR_UNSPECIFIED" -> Right PFOOperatorUnspecified "LESS_THAN" -> Right PFOLessThan "LESS_THAN_OR_EQUAL" -> Right PFOLessThanOrEqual "GREATER_THAN" -> Right PFOGreaterThan "GREATER_THAN_OR_EQUAL" -> Right PFOGreaterThanOrEqual "EQUAL" -> Right PFOEqual "HAS_ANCESTOR" -> Right PFOHasAncestor x -> Left ("Unable to parse PropertyFilterOp from: " <> x) instance ToHttpApiData PropertyFilterOp where toQueryParam = \case PFOOperatorUnspecified -> "OPERATOR_UNSPECIFIED" PFOLessThan -> "LESS_THAN" PFOLessThanOrEqual -> "LESS_THAN_OR_EQUAL" PFOGreaterThan -> "GREATER_THAN" PFOGreaterThanOrEqual -> "GREATER_THAN_OR_EQUAL" PFOEqual -> "EQUAL" PFOHasAncestor -> "HAS_ANCESTOR" instance FromJSON PropertyFilterOp where parseJSON = parseJSONText "PropertyFilterOp" instance ToJSON PropertyFilterOp where toJSON = toJSONText -- | The type of commit to perform. Defaults to \`TRANSACTIONAL\`. data CommitRequestMode = ModeUnspecified -- ^ @MODE_UNSPECIFIED@ -- Unspecified. This value must not be used. | Transactional -- ^ @TRANSACTIONAL@ -- Transactional: The mutations are either all applied, or none are -- applied. Learn about transactions -- [here](https:\/\/cloud.google.com\/datastore\/docs\/concepts\/transactions). | NonTransactional -- ^ @NON_TRANSACTIONAL@ -- Non-transactional: The mutations may not apply as all or none. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CommitRequestMode instance FromHttpApiData CommitRequestMode where parseQueryParam = \case "MODE_UNSPECIFIED" -> Right ModeUnspecified "TRANSACTIONAL" -> Right Transactional "NON_TRANSACTIONAL" -> Right NonTransactional x -> Left ("Unable to parse CommitRequestMode from: " <> x) instance ToHttpApiData CommitRequestMode where toQueryParam = \case ModeUnspecified -> "MODE_UNSPECIFIED" Transactional -> "TRANSACTIONAL" NonTransactional -> "NON_TRANSACTIONAL" instance FromJSON CommitRequestMode where parseJSON = parseJSONText "CommitRequestMode" instance ToJSON CommitRequestMode where toJSON = toJSONText
rueshyna/gogol
gogol-datastore/gen/Network/Google/Datastore/Types/Sum.hs
mpl-2.0
11,442
0
11
2,546
1,731
926
805
206
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.EC2.ImportKeyPair -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Imports the public key from an RSA key pair that you created with a -- third-party tool. Compare this with 'CreateKeyPair', in which AWS creates the -- key pair and gives the keys to you (AWS keeps a copy of the public key). With -- ImportKeyPair, you create the key pair and give AWS just the public key. The -- private key is never transferred between you and AWS. -- -- For more information about key pairs, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html Key Pairs> in the /Amazon ElasticCompute Cloud User Guide/. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ImportKeyPair.html> module Network.AWS.EC2.ImportKeyPair ( -- * Request ImportKeyPair -- ** Request constructor , importKeyPair -- ** Request lenses , ikpDryRun , ikpKeyName , ikpPublicKeyMaterial -- * Response , ImportKeyPairResponse -- ** Response constructor , importKeyPairResponse -- ** Response lenses , ikprKeyFingerprint , ikprKeyName ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data ImportKeyPair = ImportKeyPair { _ikpDryRun :: Maybe Bool , _ikpKeyName :: Text , _ikpPublicKeyMaterial :: Base64 } deriving (Eq, Read, Show) -- | 'ImportKeyPair' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ikpDryRun' @::@ 'Maybe' 'Bool' -- -- * 'ikpKeyName' @::@ 'Text' -- -- * 'ikpPublicKeyMaterial' @::@ 'Base64' -- importKeyPair :: Text -- ^ 'ikpKeyName' -> Base64 -- ^ 'ikpPublicKeyMaterial' -> ImportKeyPair importKeyPair p1 p2 = ImportKeyPair { _ikpKeyName = p1 , _ikpPublicKeyMaterial = p2 , _ikpDryRun = Nothing } -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have the -- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'. ikpDryRun :: Lens' ImportKeyPair (Maybe Bool) ikpDryRun = lens _ikpDryRun (\s a -> s { _ikpDryRun = a }) -- | A unique name for the key pair. ikpKeyName :: Lens' ImportKeyPair Text ikpKeyName = lens _ikpKeyName (\s a -> s { _ikpKeyName = a }) -- | The public key. You must base64 encode the public key material before sending -- it to AWS. ikpPublicKeyMaterial :: Lens' ImportKeyPair Base64 ikpPublicKeyMaterial = lens _ikpPublicKeyMaterial (\s a -> s { _ikpPublicKeyMaterial = a }) data ImportKeyPairResponse = ImportKeyPairResponse { _ikprKeyFingerprint :: Maybe Text , _ikprKeyName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'ImportKeyPairResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ikprKeyFingerprint' @::@ 'Maybe' 'Text' -- -- * 'ikprKeyName' @::@ 'Maybe' 'Text' -- importKeyPairResponse :: ImportKeyPairResponse importKeyPairResponse = ImportKeyPairResponse { _ikprKeyName = Nothing , _ikprKeyFingerprint = Nothing } -- | The MD5 public key fingerprint as specified in section 4 of RFC 4716. ikprKeyFingerprint :: Lens' ImportKeyPairResponse (Maybe Text) ikprKeyFingerprint = lens _ikprKeyFingerprint (\s a -> s { _ikprKeyFingerprint = a }) -- | The key pair name you provided. ikprKeyName :: Lens' ImportKeyPairResponse (Maybe Text) ikprKeyName = lens _ikprKeyName (\s a -> s { _ikprKeyName = a }) instance ToPath ImportKeyPair where toPath = const "/" instance ToQuery ImportKeyPair where toQuery ImportKeyPair{..} = mconcat [ "DryRun" =? _ikpDryRun , "KeyName" =? _ikpKeyName , "PublicKeyMaterial" =? _ikpPublicKeyMaterial ] instance ToHeaders ImportKeyPair instance AWSRequest ImportKeyPair where type Sv ImportKeyPair = EC2 type Rs ImportKeyPair = ImportKeyPairResponse request = post "ImportKeyPair" response = xmlResponse instance FromXML ImportKeyPairResponse where parseXML x = ImportKeyPairResponse <$> x .@? "keyFingerprint" <*> x .@? "keyName"
romanb/amazonka
amazonka-ec2/gen/Network/AWS/EC2/ImportKeyPair.hs
mpl-2.0
5,214
0
9
1,166
633
384
249
74
1
{- Created : 2014 May 23 (Fri) 14:32:50 by Harold Carr. Last Modified : 2014 Sep 17 (Wed) 10:08:02 by Harold Carr. -} module HW01_HC where import Data.List (unfoldr) import qualified Test.HUnit as T import qualified Test.HUnit.Util as U ------------------------------------------------------------------------------ -- Exercise 1 lastDigit :: Integer -> Integer lastDigit = (`mod` 10) dropLastDigit :: Integer -> Integer dropLastDigit = (`div` 10) e1 :: T.Test e1 = T.TestList [ U.teq "123last" (lastDigit 123) 3 , U.teq "0last" (lastDigit 0) 0 , U.teq "123drop" (dropLastDigit 123) 12 , U.teq "5drop" (dropLastDigit 5) 0 --------------------------------------- , U.teq "397last" (lastDigit 397) 7 , U.teq "397drop" (dropLastDigit 397) 39 , U.teq "39last" (lastDigit 39) 9 , U.teq "39drop" (dropLastDigit 39) 3 , U.teq "3last" (lastDigit 3) 3 , U.teq "3drop" (dropLastDigit 3) 0 ] ------------------------------------------------------------------------------ -- Exercise 2 toDigits :: Integer -> [Integer] toDigits = reverse . toDigitsRev toDigitsRev :: Integer -> [Integer] toDigitsRev = unfoldr (\n -> if n <= 0 then Nothing else Just (lastDigit n, dropLastDigit n)) e2 :: T.Test e2 = T.TestList [ U.teq "7" (toDigits 1234) [1,2,3,4] , U.teq "9" (toDigitsRev 1234) [4,3,2,1] , U.teq "9" (toDigits 0) [] , U.teq "0" (toDigits (-17)) [] ] ------------------------------------------------------------------------------ -- Exercise 3 -- O(n) -- correct type sig is: -- doubleEveryOther :: Num a => [a] -> [a] -- but pinning it at Integer to avoid "defaulting to" messages in test doubleEveryOther :: [Integer] -> [Integer] doubleEveryOther = snd . foldr (\n (b,xs) -> (not b, (if b then 2*n else n) : xs)) (False, []) e3 :: T.Test e3 = T.TestList [ U.teq "deo8765" (doubleEveryOther [8,7,6,5]) [16,7,12,5] , U.teq "deo123" (doubleEveryOther [1,2,3]) [1,4,3] ---------------------- , U.teq "deo1386" (doubleEveryOther [1,3,8,6]) [2,3,16,6] ] -- http://stackoverflow.com/questions/23842473/what-to-use-instead-of-explicit-recursion-in-haskell -- doubleEveryOtherLens = over (elements even) (*2) [8,7,6,5] ------------------------------------------------------------------------------ -- Exercise 4 sumDigits :: [Integer] -> Integer sumDigits = foldr (\x acc -> dropLastDigit x + lastDigit x + acc) 0 e4 :: T.Test e4 = T.TestList [ U.teq "0" (sumDigits [16,7,12,5]) 22 , U.teq "1" (sumDigits [2,3,16,6]) 18 ] ------------------------------------------------------------------------------ -- Exercise 5 validate :: Integer -> Bool validate = (== 0) . (`mod` 10) . sumDigits . doubleEveryOther . toDigits e5 :: T.Test e5 = T.TestList [ U.teq "vt" (validate 4012888888881881) True , U.teq "vf" (validate 4012888888881882) False ] ------------------------------------------------------------------------------ -- Exercise 6 - Towers of Hanoi {- 0 - -- --- 1 -- --- - 2 --- -- - 3 - --- -- 4 - -- --- 5 - -- --- 6 -- - --- 7 - -- --- -} type Peg = String type Move = (Integer, Peg, Peg) -- src tmp dst hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] hanoi n a b c = case n of 0 -> [] _ -> hanoi (n - 1) a c b ++ [(n, a, c)] ++ hanoi (n - 1) b a c hN :: Integer -> [Move] hN n = hanoi n "a" "b" "c" checkLastMove :: [Move] -> Bool checkLastMove m = case last m of (1, _ ,"c") -> True _ -> False h3, h4, h5, h9, h15 :: [Move] h3 = hN 3 h4 = hN 4 h5 = hN 5 h9 = hN 9 h15 = hN 15 -- to avoid "defaulting to" messages twoToNMinusOne :: Int -> Int twoToNMinusOne n= 2^n-1 e6 :: T.Test e6 = T.TestList [ U.teq "h3" h3 [(1,"a","c"),(2,"a","b"),(1,"c","b"),(3,"a","c"),(1,"b","a"),(2,"b","c"),(1,"a","c")] , U.teq "h3m" (checkLastMove h3) True , U.teq "h3l" (length h3) (twoToNMinusOne 3) , U.teq "h4" h4 [(1,"a","b"),(2,"a","c"),(1,"b","c"),(3,"a","b"),(1,"c","a"),(2,"c","b"),(1,"a","b"),(4,"a","c"),(1,"b","c"),(2,"b","a"),(1,"c","a"),(3,"b","c"),(1,"a","b"),(2,"a","c"),(1,"b","c")] , U.teq "h4m" (checkLastMove h4) True , U.teq "h4l" (length h4) (twoToNMinusOne 4) , U.teq "h5" h5 [(1,"a","c"),(2,"a","b"),(1,"c","b"),(3,"a","c"),(1,"b","a"),(2,"b","c"),(1,"a","c"),(4,"a","b"),(1,"c","b"),(2,"c","a"),(1,"b","a"),(3,"c","b"),(1,"a","c"),(2,"a","b"),(1,"c","b"),(5,"a","c"),(1,"b","a"),(2,"b","c"),(1,"a","c"),(3,"b","a"),(1,"c","b"),(2,"c","a"),(1,"b","a"),(4,"b","c"),(1,"a","c"),(2,"a","b"),(1,"c","b"),(3,"a","c"),(1,"b","a"),(2,"b","c"),(1,"a","c")] , U.teq "h5m" (checkLastMove h5) True , U.teq "h5l" (length h5) (twoToNMinusOne 5) , U.teq "h9m" (checkLastMove h9) True , U.teq "h9l" (length h9) (twoToNMinusOne 9) , U.teq "h15m" (checkLastMove h15) True , U.teq "h15l" (length h15) (twoToNMinusOne 15) ] ------------------------------------------------------------------------------ -- Exercise 7 -- TODO hanoi4p :: Integer -> Peg -> Peg -> Peg -> Peg -> [Move] hanoi4p = undefined -- hanoi4p 3 "a" "b" "c" "d" ------------------------------------------------------------------------------ hw01 :: IO [T.Counts] hw01 = mapM T.runTestTT [e1,e2,e3,e4,e5,e6] -- End of file.
haroldcarr/learn-haskell-coq-ml-etc
haskell/course/2014-06-upenn/cis194/src/HW01_HC.hs
unlicense
5,646
0
13
1,357
2,192
1,287
905
95
2
{-# LANGUAGE GADTs,RankNTypes,DeriveFunctor #-} module Faceted.FIORef ( FIORef, newFIORef, readFIORef, writeFIORef, ) where import Faceted.Internal import Data.IORef -- | Variables of type 'FIORef a' are faceted 'IORef's data FIORef a = FIORef (IORef (Faceted a)) -- | Allocate a new 'FIORef' newFIORef :: Faceted a -> FIO (FIORef a) newFIORef init = FIO newFIORefForPC where newFIORefForPC pc = do var <- newIORef (pcF pc init undefined) return (FIORef var) -- | Read an 'FIORef' readFIORef :: FIORef a -> FIO (Faceted a) readFIORef (FIORef var) = FIO readFIORefForPC where readFIORefForPC pc = do faceted <- readIORef var return faceted -- | Write an 'FIORef' writeFIORef :: FIORef a -> Faceted a -> FIO () writeFIORef (FIORef var) newValue = FIO writeFIORefForPC where writeFIORefForPC pc = do oldValue <- readIORef var writeIORef var (pcF pc newValue oldValue)
haskell-faceted/haskell-faceted
Faceted/FIORef.hs
apache-2.0
986
0
12
257
277
137
140
21
1
#!/usr/bin/env stack {- stack --install-ghc runghc --package Command --package text --package hflags -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} import Control.Monad import Data.Version import HFlags import System.Command import Text.ParserCombinators.ReadP defineFlag "version" ("0.0.1" :: String) "version." defineFlag "name" ("Indiana Jones" :: String) "Who to greet." systemOrDie :: String -> IO () systemOrDie cmd = do result <- system cmd when (isFailure result) $ error $ "Failed: " ++ cmd return () packages :: [String] packages = [ "ethereum-analyzer" , "ethereum-analyzer-deps" , "ethereum-analyzer-webui" , "ethereum-analyzer-cli" ] main :: IO () main = do _ <- $initHFlags "release_to_hackage.hs" case reverse $ readP_to_S parseVersion flags_version of (Version v@[_, _, _] [], ""):_ -> do putStrLn $ "Updating to version " ++ show v systemOrDie "git checkout master" systemOrDie "git stash" _ <- mapM (\package -> do systemOrDie $ "sed -i'' " ++ "'s/^version:\\([[:blank:]]*\\)[[:digit:]]\\+.[[:digit:]]\\+.[[:digit:]]\\+" ++ "/version:\\1" ++ flags_version ++ "/' " ++ package ++ "/" ++ package ++ ".cabal" systemOrDie $ "sed -i'' " ++ "'s/^ tag:\\([[:blank:]]*\\)v[[:digit:]]\\+.[[:digit:]]\\+.[[:digit:]]\\+" ++ "/ tag:\\1v" ++ flags_version ++ "/' " ++ package ++ "/" ++ package ++ ".cabal" systemOrDie $ "stack upload --no-signature " ++ package) packages systemOrDie $ "git commit . -m 'tagging v" ++ flags_version ++ "'" systemOrDie $ "git tag v" ++ flags_version systemOrDie "git push origin --tags" other -> error $ "malformed version: " ++ flags_version ++ " " ++ show other return ()
zchn/ethereum-analyzer
scripts/release_to_hackage.hs
apache-2.0
1,919
0
26
514
427
211
216
48
2
{-# LANGUAGE OverloadedStrings #-} -- | NSIS (Nullsoft Scriptable Install System, <http://nsis.sourceforge.net/>) is a tool that allows programmers -- to create installers for Windows. -- This library provides an alternative syntax for NSIS scripts, as an embedded Haskell language, removing much -- of the hard work in developing an install script. Simple NSIS installers should look mostly the same, complex ones should -- be significantly more maintainable. -- -- As a simple example of using this library: -- -- @ --import "Development.NSIS" -- --main = writeFile \"example1.nsi\" $ 'nsis' $ do -- 'name' \"Example1\" -- The name of the installer -- 'outFile' \"example1.exe\" -- Where to produce the installer -- 'installDir' \"$DESKTOP/Example1\" -- The default installation directory -- 'requestExecutionLevel' 'User' -- Request application privileges for Windows Vista -- -- Pages to display -- 'page' 'Directory' -- Pick where to install -- 'page' 'InstFiles' -- Give a progress bar while installing -- -- Groups fo files to install -- 'section' \"\" [] $ do -- 'setOutPath' \"$INSTDIR\" -- Where to install files in this section -- 'file' [] \"Example1.hs\" -- File to put into this section -- @ -- -- The file @example1.nsi@ can now be processed with @makensis@ to produce the installer @example1.exe@. -- For more examples, see the @Examples@ source directory. -- -- Much of the documentation from the Installer section is taken from the NSIS documentation. module Development.NSIS ( -- * Core types nsis, nsisNoOptimise, Action, Exp, Value, -- * Scripting -- ** Variables share, scope, constant, constant_, mutable, mutable_, (@=), -- ** Typed variables mutableInt, constantInt, mutableInt_, constantInt_, mutableStr, constantStr, mutableStr_, constantStr_, -- ** Control Flow iff, iff_, while, loop, onError, (?), (%&&), (%||), Label, newLabel, label, goto, -- ** Expressions str, int, bool, (%==), (%/=), (%<=), (%<), (%>=), (%>), true, false, not_, strRead, strShow, (&), strConcat, strLength, strTake, strDrop, strReplace, strIsPrefixOf, strIsSuffixOf, strUnlines, strCheck, -- ** File system manipulation FileHandle, fileOpen, fileWrite, fileClose, withFile', writeFile', writeFileLines, rmdir, delete, copyFiles, getFileTime, fileExists, findEach, createDirectory, createShortcut, -- ** Registry manipulation readRegStr, deleteRegKey, deleteRegValue, writeRegStr, writeRegExpandStr, writeRegDWORD, -- ** Environment variables envVar, -- ** Process execution exec, execWait, execShell, sleep, abort, -- ** Windows HWND, hwndParent, findWindow, getDlgItem, sendMessage, -- ** Plugins plugin, push, pop, exp_, addPluginDir, -- * Installer -- ** Global installer options name, outFile, installDir, setCompressor, installIcon, uninstallIcon, headerImage, installDirRegKey, allowRootDirInstall, caption, showInstDetails, showUninstDetails, unicode, -- ** Sections SectionId, section, sectionGroup, newSectionId, sectionSetText, sectionGetText, sectionSet, sectionGet, uninstall, page, unpage, finishOptions, -- ** Events event, onSelChange, onPageShow, onPagePre, onPageLeave, -- ** Section commands file, alwaysNonFatal, writeUninstaller, alert, setOutPath, messageBox, requestExecutionLevel, hideProgress, detailPrint, setDetailsPrint, -- * Escape hatch unsafeInject, unsafeInjectGlobal, -- * Settings Compressor(..), HKEY(..), MessageBoxType(..), Attrib(..), Page(..), Level(..), Visibility(..), FileMode(..), SectionFlag(..), ShowWindow(..), FinishOptions(..), DetailsPrint(..) ) where import Control.Monad import Development.NSIS.Sugar import Development.NSIS.Show import Development.NSIS.Optimise import Development.NSIS.Library -- | Create the contents of an NSIS script from an installer specification. -- -- Beware, 'unsafeInject' and 'unsafeInjectGlobal' may break 'nsis'. The -- optimizer relies on invariants that may not hold when arbitrary lines are -- injected. Consider using 'nsisNoOptimise' if problems arise. nsis :: Action a -> String nsis = unlines . showNSIS . optimise . runAction . void -- | Like 'nsis', but don't try and optimise the resulting NSIS script. -- -- Useful to figure out how the underlying installer works, or if you believe -- the optimisations are introducing bugs. Please do report any such bugs, -- especially if you aren't using 'unsafeInject' or 'unsafeInjectGlobal'! nsisNoOptimise :: Action a -> String nsisNoOptimise = unlines . showNSIS . runAction . void
idleberg/NSIS
Development/NSIS.hs
apache-2.0
4,801
0
8
967
669
467
202
47
1
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} import Data.Monoid (mappend) import Hakyll type RenderingFunction = FeedConfiguration -> Context String -> [Item String] -> Compiler (Item String) myFeedConfiguration :: FeedConfiguration myFeedConfiguration = FeedConfiguration { feedTitle = "Haskell without remorse" , feedDescription = "Blog about Haskell development" , feedAuthorName = "Anton Gushcha" , feedAuthorEmail = "[email protected]" , feedRoot = "http://ncrashed.github.io/blog" } createFeed :: Identifier -> RenderingFunction -> Rules () createFeed name renderingFunction = create [name] $ do route idRoute compile $ do let feedCtx = postCtx `mappend` bodyField "description" posts <- fmap (take 10) . recentFirst =<< loadAllSnapshots "posts/*" "content" renderingFunction myFeedConfiguration feedCtx posts -------------------------------------------------------------------------------- main :: IO () main = hakyll $ do match "images/*" $ do route idRoute compile copyFileCompiler match "fonts/*" $ do route idRoute compile copyFileCompiler match "css/*" $ do route idRoute compile compressCssCompiler match (fromList ["about.markdown", "contact.markdown"]) $ do route $ setExtension "html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/default.html" defaultContext >>= relativizeUrls match "posts/*" $ do route $ setExtension "html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/post.html" postCtx >>= saveSnapshot "content" >>= loadAndApplyTemplate "templates/default.html" postCtx >>= relativizeUrls -- create ["archive.html"] $ do -- route idRoute -- compile $ do -- posts <- recentFirst =<< loadAll "posts/*" -- let archiveCtx = -- listField "posts" postCtx (return posts) `mappend` -- constField "title" "Archives" `mappend` -- defaultContext -- -- makeItem "" -- >>= loadAndApplyTemplate "templates/archive.html" archiveCtx -- >>= loadAndApplyTemplate "templates/default.html" archiveCtx -- >>= relativizeUrls match "index.html" $ do route idRoute compile $ do posts <- recentFirst =<< loadAll "posts/*" let indexCtx = listField "posts" postCtx (return posts) `mappend` constField "title" "Home" `mappend` defaultContext getResourceBody >>= applyAsTemplate indexCtx >>= loadAndApplyTemplate "templates/default.html" indexCtx >>= relativizeUrls match "templates/*" $ compile templateBodyCompiler createFeed "feed.xml" renderRss createFeed "atom.xml" renderAtom -------------------------------------------------------------------------------- postCtx :: Context String postCtx = dateField "date" "%B %e, %Y" `mappend` defaultContext
NCrashed/blog
src/site.hs
apache-2.0
3,002
0
21
647
562
271
291
64
1
-- 1 -- 2, 1 -- 6, 2, 1 -- 24, 9, 2, 1 -- 120, 44, 13, ?, 1 type Board = [(Int, Int)] -- patternAvoidingPermutations board n = ??? -- Not smart, since it doesn't use the results from (k-1) to help compute k. -- Also, not tail recursive. nonAttackingRookCount 0 _ = 1 nonAttackingRookCount _ [] = 0 nonAttackingRookCount k ((x,y):rs) = nonAttackingRookCount (k - 1) rs' + nonAttackingRookCount k rs where rs' = filter (\(a, b) -> a /= x && b /= y) rs
peterokagey/haskellOEIS
src/Sandbox/Richard/table.hs
apache-2.0
467
0
12
106
128
73
55
5
1
{-# LANGUAGE TemplateHaskell #-} module TH.HSCs where import Language.Haskell.TH import TH.API import TH.APIs import TH.HSC $(do runIO $ putStrLn "HSC generation" apis <- generateAPIs "apis" generateHSCs apis runIO $ putStrLn "..Done" return [] )
fabianbergmark/APIs
src/TH/HSCs.hs
bsd-2-clause
277
0
10
64
79
38
41
12
0
{-# LANGUAGE DeriveDataTypeable #-} module Application.DiagramDrawer.ProgType where import System.Console.CmdArgs data Diagdrawer = Test deriving (Show,Data,Typeable) test :: Diagdrawer test = Test mode = modes [test]
wavewave/diagdrawer
lib/Application/DiagramDrawer/ProgType.hs
bsd-2-clause
241
0
6
48
57
34
23
8
1
{-| Module : Idris.Elab.Interface Description : Code to elaborate interfaces. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards #-} {-# OPTIONS_GHC -fwarn-missing-signatures #-} module Idris.Elab.Interface(elabInterface) where import Idris.AbsSyntax import Idris.ASTUtils import Idris.DSL import Idris.Error import Idris.Delaborate import Idris.Imports import Idris.Elab.Term import Idris.Coverage import Idris.DataOpts import Idris.Providers import Idris.Primitives import Idris.Inliner import Idris.PartialEval import Idris.DeepSeq import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting) import IRTS.Lang import Idris.Elab.Type import Idris.Elab.Data import Idris.Elab.Utils import Idris.Core.TT import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.Typecheck import Idris.Core.CaseTree import Idris.Docstrings import Prelude hiding (id, (.)) import Control.Category import Control.Applicative hiding (Const) import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import Data.List import Data.Maybe import Debug.Trace import qualified Data.Map as Map import qualified Data.Set as S import qualified Data.Text as T import Data.Char(isLetter, toLower) import Data.List.Split (splitOn) import Data.Generics.Uniplate.Data (transform) import Util.Pretty(pretty, text) data MArgTy = IA Name | EA Name | CA deriving Show elabInterface :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) -> FC -> [(Name, PTerm)] -> Name -> FC -> [(Name, FC, PTerm)] -> [(Name, Docstring (Either Err PTerm))] -> [(Name, FC)] -- ^ determining params -> [PDecl] -- ^ interface body -> Maybe (Name, FC) -- ^ implementation ctor name and location -> Docstring (Either Err PTerm) -- ^ implementation ctor docs -> Idris () elabInterface info syn_in doc fc constraints tn tnfc ps pDocs fds ds mcn cd = do let cn = fromMaybe (SN (ImplementationCtorN tn)) (fst <$> mcn) let tty = pibind (map (\(n, _, ty) -> (n, ty)) ps) (PType fc) let constraint = PApp fc (PRef fc [] tn) (map (pexp . PRef fc []) (map (\(n, _, _) -> n) ps)) let syn = syn_in { using = addToUsing (using syn_in) [(pn, pt) | (pn, _, pt) <- ps] } -- build data declaration let mdecls = filter tydecl ds -- method declarations let idecls = filter impldecl ds -- default super interface implementation declarations mapM_ checkDefaultSuperInterfaceImplementation idecls let mnames = map getMName mdecls ist <- getIState let constraintNames = nub $ concatMap (namesIn [] ist) (map snd constraints) mapM_ (checkConstraintName (map (\(x, _, _) -> x) ps)) constraintNames logElab 2 $ "Building methods " ++ show mnames ims <- mapM (tdecl mnames) mdecls defs <- mapM (defdecl (map (\ (x,y,z) -> z) ims) constraint) (filter clause ds) let (methods, imethods) = unzip (map (\ (x, y, z) -> (x, y)) ims) let defaults = map (\ (x, (y, z)) -> (x,y)) defs -- build implementation constructor type let cty = impbind [(pn, pt) | (pn, _, pt) <- ps] $ conbind constraints $ pibind (map (\ (n, ty) -> (nsroot n, ty)) methods) constraint let cons = [(cd, pDocs ++ mapMaybe memberDocs ds, cn, NoFC, cty, fc, [])] let ddecl = PDatadecl tn NoFC tty cons logElab 5 $ "Interface data " ++ show (showDImp verbosePPOption ddecl) -- Elaborate the data declaration elabData info (syn { no_imp = no_imp syn ++ mnames, imp_methods = mnames }) doc pDocs fc [] ddecl dets <- findDets cn (map fst fds) addInterface tn (CI cn (map nodoc imethods) defaults idecls (map (\(n, _, _) -> n) ps) [] dets) -- for each constraint, build a top level function to chase it cfns <- mapM (cfun cn constraint syn (map fst imethods)) constraints mapM_ (rec_elabDecl info EAll info) (concat cfns) -- for each method, build a top level function fns <- mapM (tfun cn constraint (syn { imp_methods = mnames }) (map fst imethods)) imethods logElab 5 $ "Functions " ++ show fns -- Elaborate the the top level methods mapM_ (rec_elabDecl info EAll info) (concat fns) -- Flag all the top level data declarations as injective mapM_ (\n -> do setInjectivity n True addIBC (IBCInjective n True)) (map fst (filter (\(_, (inj, _, _, _, _)) -> inj) imethods)) -- add the default definitions mapM_ (rec_elabDecl info EAll info) (concatMap (snd.snd) defs) addIBC (IBCInterface tn) sendHighlighting $ [(tnfc, AnnName tn Nothing Nothing Nothing)] ++ [(pnfc, AnnBoundName pn False) | (pn, pnfc, _) <- ps] ++ [(fdfc, AnnBoundName fc False) | (fc, fdfc) <- fds] ++ maybe [] (\(conN, conNFC) -> [(conNFC, AnnName conN Nothing Nothing Nothing)]) mcn where nodoc (n, (inj, _, _, o, t)) = (n, (inj, o, t)) pibind [] x = x pibind ((n, ty): ns) x = PPi expl n NoFC ty (pibind ns (chkUniq ty x)) -- To make sure the type constructor of the interface is in the appropriate -- uniqueness hierarchy chkUniq u@(PUniverse _ _) (PType _) = u chkUniq (PUniverse _ l) (PUniverse _ r) = PUniverse NoFC (min l r) chkUniq (PPi _ _ _ _ sc) t = chkUniq sc t chkUniq _ t = t -- TODO: probably should normalise checkDefaultSuperInterfaceImplementation :: PDecl -> Idris () checkDefaultSuperInterfaceImplementation (PImplementation _ _ _ fc cs _ _ _ n _ ps _ _ _ _) = do when (not $ null cs) . tclift $ tfail (At fc (Msg "Default super interface implementations can't have constraints.")) i <- getIState let t = PApp fc (PRef fc [] n) (map pexp ps) let isConstrained = any (== t) (map snd constraints) when (not isConstrained) . tclift $ tfail (At fc (Msg "Default implementations must be for a super interface constraint on the containing interface.")) return () checkConstraintName :: [Name] -> Name -> Idris () checkConstraintName bound cname | cname `notElem` bound = tclift $ tfail (At fc (Msg $ "Name " ++ show cname ++ " is not bound in interface " ++ show tn ++ " " ++ showSep " " (map show bound))) | otherwise = return () impbind :: [(Name, PTerm)] -> PTerm -> PTerm impbind [] x = x impbind ((n, ty): ns) x = PPi impl n NoFC ty (impbind ns x) conbind :: [(Name, PTerm)] -> PTerm -> PTerm conbind ((c, ty) : ns) x = PPi constraint c NoFC ty (conbind ns x) conbind [] x = x getMName (PTy _ _ _ _ _ n nfc _) = nsroot n getMName (PData _ _ _ _ _ (PLaterdecl n nfc _)) = nsroot n tdecl allmeths (PTy doc _ syn _ o n nfc t) = do t' <- implicit' info syn (map (\(n, _, _) -> n) ps ++ allmeths) n t logElab 2 $ "Method " ++ show n ++ " : " ++ showTmImpls t' return ( (n, (toExp (map (\(pn, _, _) -> pn) ps) Exp t')), (n, (False, nfc, doc, o, (toExp (map (\(pn, _, _) -> pn) ps) (\ l s p -> Imp l s p Nothing True) t'))), (n, (nfc, syn, o, t) ) ) tdecl allmeths (PData doc _ syn _ _ (PLaterdecl n nfc t)) = do let o = [] t' <- implicit' info syn (map (\(n, _, _) -> n) ps ++ allmeths) n t logElab 2 $ "Data method " ++ show n ++ " : " ++ showTmImpls t' return ( (n, (toExp (map (\(pn, _, _) -> pn) ps) Exp t')), (n, (True, nfc, doc, o, (toExp (map (\(pn, _, _) -> pn) ps) (\ l s p -> Imp l s p Nothing True) t'))), (n, (nfc, syn, o, t) ) ) tdecl allmeths (PData doc _ syn _ _ _) = ierror $ At fc (Msg "Data definitions not allowed in an interface declaration") tdecl _ _ = ierror $ At fc (Msg "Not allowed in an interface declaration") -- Create default definitions defdecl mtys c d@(PClauses fc opts n cs) = case lookup n mtys of Just (nfc, syn, o, ty) -> do let ty' = insertConstraint c (map fst mtys) ty let ds = map (decorateid defaultdec) [PTy emptyDocstring [] syn fc [] n nfc ty', PClauses fc (o ++ opts) n cs] logElab 1 (show ds) return (n, ((defaultdec n, ds!!1), ds)) _ -> ierror $ At fc (Msg (show n ++ " is not a method")) defdecl _ _ _ = ifail "Can't happen (defdecl)" defaultdec (UN n) = sUN ("default#" ++ str n) defaultdec (NS n ns) = NS (defaultdec n) ns tydecl (PTy{}) = True tydecl (PData _ _ _ _ _ _) = True tydecl _ = False impldecl (PImplementation{}) = True impldecl _ = False clause (PClauses{}) = True clause _ = False -- Generate a function for chasing a dictionary constraint cfun :: Name -> PTerm -> SyntaxInfo -> [a] -> (Name, PTerm) -> Idris [PDecl' PTerm] cfun cn c syn all (cnm, con) = do let cfn = SN (ParentN cn (txt (show con))) let mnames = take (length all) $ map (\x -> sMN x "meth") [0..] let capp = PApp fc (PRef fc [] cn) (map (pexp . PRef fc []) mnames) let lhs = PApp fc (PRef fc [] cfn) [pconst capp] let rhs = PResolveTC (fileFC "HACK") let ty = PPi constraint cnm NoFC c con logElab 2 ("Dictionary constraint: " ++ showTmImpls ty) logElab 2 (showTmImpls lhs ++ " = " ++ showTmImpls rhs) i <- getIState let conn = case con of PRef _ _ n -> n PApp _ (PRef _ _ n) _ -> n let conn' = case lookupCtxtName conn (idris_interfaces i) of [(n, _)] -> n _ -> conn addImplementation False True conn' cfn addIBC (IBCImplementation False True conn' cfn) -- iputStrLn ("Added " ++ show (conn, cfn, ty)) return [PTy emptyDocstring [] syn fc [] cfn NoFC ty, PClauses fc [Inlinable, Dictionary] cfn [PClause fc cfn lhs [] rhs []]] -- | Generate a top level function which looks up a method in a given -- dictionary (this is inlinable, always) tfun :: Name -- ^ The name of the interface -> PTerm -- ^ A constraint for the interface, to be inserted under the implicit bindings -> SyntaxInfo -> [Name] -- ^ All the method names -> (Name, (Bool, FC, Docstring (Either Err PTerm), FnOpts, PTerm)) -- ^ The present declaration -> Idris [PDecl] tfun cn c syn all (m, (isdata, mfc, doc, o, ty)) = do let ty' = expandMethNS syn (insertConstraint c all ty) let mnames = take (length all) $ map (\x -> sMN x "meth") [0..] let capp = PApp fc (PRef fc [] cn) (map (pexp . PRef fc []) mnames) let margs = getMArgs ty let anames = map (\x -> sMN x "arg") [0..] let lhs = PApp fc (PRef fc [] m) (pconst capp : lhsArgs margs anames) let rhs = PApp fc (getMeth mnames all m) (rhsArgs margs anames) logElab 2 ("Top level type: " ++ showTmImpls ty') logElab 1 (show (m, ty', capp, margs)) logElab 2 ("Definition: " ++ showTmImpls lhs ++ " = " ++ showTmImpls rhs) return [PTy doc [] syn fc o m mfc ty', PClauses fc [Inlinable] m [PClause fc m lhs [] rhs []]] getMArgs (PPi (Imp _ _ _ _ _) n _ ty sc) = IA n : getMArgs sc getMArgs (PPi (Exp _ _ _) n _ ty sc) = EA n : getMArgs sc getMArgs (PPi (Constraint _ _) n _ ty sc) = CA : getMArgs sc getMArgs _ = [] getMeth :: [Name] -> [Name] -> Name -> PTerm getMeth (m:ms) (a:as) x | x == a = PRef fc [] m | otherwise = getMeth ms as x lhsArgs (EA _ : xs) (n : ns) = [] -- pexp (PRef fc n) : lhsArgs xs ns lhsArgs (IA n : xs) ns = pimp n (PRef fc [] n) False : lhsArgs xs ns lhsArgs (CA : xs) ns = lhsArgs xs ns lhsArgs [] _ = [] rhsArgs (EA _ : xs) (n : ns) = [] -- pexp (PRef fc n) : rhsArgs xs ns rhsArgs (IA n : xs) ns = pexp (PRef fc [] n) : rhsArgs xs ns rhsArgs (CA : xs) ns = pconst (PResolveTC fc) : rhsArgs xs ns rhsArgs [] _ = [] -- Add the top level constraint. Put it first - elaboration will resolve -- the order of the implicits if there are dependencies. -- Also ensure the dictionary is used for lookup of any methods that -- are used in the type insertConstraint :: PTerm -> [Name] -> PTerm -> PTerm insertConstraint c all sc = let dictN = sMN 0 "__interface" in PPi (constraint { pstatic = Static }) dictN NoFC c (constrainMeths (map basename all) dictN sc) where -- After we insert the constraint into the lookup, we need to -- ensure that the same dictionary is used to resolve lookups -- to the other methods in the interface constrainMeths :: [Name] -> Name -> PTerm -> PTerm constrainMeths allM dictN tm = transform (addC allM dictN) tm addC allM dictN m@(PRef fc hls n) | n `elem` allM = PApp NoFC m [pconst (PRef NoFC hls dictN)] | otherwise = m addC _ _ tm = tm -- make arguments explicit and don't bind interface parameters toExp ns e (PPi (Imp l s p _ _) n fc ty sc) | n `elem` ns = toExp ns e sc | otherwise = PPi (e l s p) n fc ty (toExp ns e sc) toExp ns e (PPi p n fc ty sc) = PPi p n fc ty (toExp ns e sc) toExp ns e sc = sc -- | Get the method declaration name corresponding to a user-provided name mdec :: Name -> Name mdec (UN n) = SN (MethodN (UN n)) mdec (NS x n) = NS (mdec x) n mdec x = x -- | Get the docstring corresponding to a member, if one exists memberDocs :: PDecl -> Maybe (Name, Docstring (Either Err PTerm)) memberDocs (PTy d _ _ _ _ n _ _) = Just (basename n, d) memberDocs (PPostulate _ d _ _ _ _ n _) = Just (basename n, d) memberDocs (PData d _ _ _ _ pdata) = Just (basename $ d_name pdata, d) memberDocs (PRecord d _ _ _ n _ _ _ _ _ _ _ ) = Just (basename n, d) memberDocs (PInterface d _ _ _ n _ _ _ _ _ _ _) = Just (basename n, d) memberDocs _ = Nothing -- | In a top level type for a method, expand all the method names' namespaces -- so that we don't have to disambiguate later expandMethNS :: SyntaxInfo -> PTerm -> PTerm expandMethNS syn = mapPT expand where expand (PRef fc hls n) | n `elem` imp_methods syn = PRef fc hls $ expandNS syn n expand t = t -- | Find the determining parameter locations findDets :: Name -> [Name] -> Idris [Int] findDets n ns = do i <- getIState return $ case lookupTyExact n (tt_ctxt i) of Just ty -> getDetPos 0 ns ty Nothing -> [] where getDetPos i ns (Bind n (Pi _ _ _) sc) | n `elem` ns = i : getDetPos (i + 1) ns sc | otherwise = getDetPos (i + 1) ns sc getDetPos _ _ _ = []
enolan/Idris-dev
src/Idris/Elab/Interface.hs
bsd-3-clause
15,877
0
20
5,269
5,921
3,065
2,856
277
32
-- | This module reexport everything which is needed for message -- definition in generated code. There is no need import this module -- in user code. module Data.Protobuf.Imports ( -- * Data types Word32 , Word64 , Int32 , Int64 , Bool , Double , Float , String , Maybe(..) , Seq , ByteString -- * Functions , singleton , undefined , comparing , ap , mapM , mapM_ -- ** Converwsion , checkMaybe , checkMaybeMsg , checkRequired , checkRequiredMsg -- * Classes , Show(..) , Eq(..) , Ord(..) , Enum(..) , Bounded(..) , Functor(..) , Monad(..) , Monoid(..) , Typeable(..) , Data(..) , LoopType -- * Modules , module P' , module Data.Serialize.VarInt ) where import Control.Monad (ap, liftM) import Data.Data (Data(..),Typeable(..)) import Data.Word (Word32, Word64) import Data.Int (Int32, Int64) import Data.Ord import Data.Monoid (Monoid(..)) import Data.Sequence (Seq,singleton) import Data.ByteString (ByteString) import Data.Foldable (mapM_) import Data.Traversable (mapM) import Data.Protobuf.Classes as P' import Data.Serialize as P' import Data.Serialize.Protobuf as P' import Data.Serialize.VarInt import Prelude hiding (mapM,mapM_) -- | Type of worker function in the generated code. type LoopType v = v Unchecked -> Get (v Unchecked) -- | Check optional value checkMaybe :: Monad m => a -> Maybe a -> m (Maybe a) checkMaybe x Nothing = return (Just x) checkMaybe _ x = return x {-# INLINE checkMaybe #-} -- | Check optional value checkMaybeMsg :: (Message a, Monad m) => Maybe (a Unchecked) -> m (Maybe (a Checked)) checkMaybeMsg Nothing = return Nothing checkMaybeMsg (Just x) = liftM Just (checkReq x) {-# INLINE checkMaybeMsg #-} -- | Check required value checkRequired :: Monad m => Required a -> m a checkRequired NotSet = fail "Field is not set!" checkRequired (Present x) = return x {-# INLINE checkRequired #-} -- | Check required message checkRequiredMsg :: (Message a, Monad m) => Required (a Unchecked) -> m (a Checked) checkRequiredMsg NotSet = fail "Field is not set!" checkRequiredMsg (Present x) = checkReq x {-# INLINE checkRequiredMsg #-}
Shimuuar/protobuf
protobuf-lib/Data/Protobuf/Imports.hs
bsd-3-clause
2,306
0
11
571
631
373
258
67
1
module Hackage.Twitter.Bot.Types where import Data.Time () import Data.Time.Clock data FullPost = FullPost { fullPostAuthor :: String, fullPostDescription :: String, fullPostTime :: UTCTime, fullPostTitle :: String, fullPostLink :: String} deriving (Show) data PartialPost = PartialPost {author :: String , description :: String, postTime :: UTCTime} deriving (Show)
KevinCotrone/hackage-twitter-bot
src/Hackage/Twitter/Bot/Types.hs
bsd-3-clause
396
0
8
75
102
65
37
5
0
module Main(main) where import System.Environment (getArgs, getProgName) import Web.Zenfolio.API import qualified Web.Zenfolio.Categories as Categories dumpCategories :: ZM () dumpCategories = do categories <- Categories.getCategories liftIO $ putStrLn ("Categories: " ++ show categories) main :: IO () main = do ls <- getArgs case ls of [] -> zenfolio $ dumpCategories _ -> do prg <- getProgName putStrLn ("Usage: " ++ prg)
md5/hs-zenfolio
examples/GetCategories.hs
bsd-3-clause
506
0
14
142
148
78
70
16
2
{-# LANGUAGE TupleSections, OverloadedStrings, QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric ,MultiParamTypeClasses ,FlexibleInstances #-} module Protocol.ROC.PointTypes.PointType121 where import GHC.Generics import qualified Data.ByteString as BS import Data.Word import Data.Binary import Data.Binary.Get data PointType121 = PointType121 { pointType121TagID :: !PointType121TagID ,pointType121SlaveAddress1 :: !PointType121SlaveAddress1 ,pointType121FunctionCode1 :: !PointType121FunctionCode1 ,pointType121SlaveRegister1 :: !PointType121SlaveRegister1 ,pointType121MasterRegister1 :: !PointType121MasterRegister1 ,pointType121NumOfRegisters1 :: !PointType121NumOfRegisters1 ,pointType121CommStatus1 :: !PointType121CommStatus1 ,pointType121SlaveAddress2 :: !PointType121SlaveAddress2 ,pointType121FunctionCode2 :: !PointType121FunctionCode2 ,pointType121SlaveRegister2 :: !PointType121SlaveRegister2 ,pointType121MasterRegister2 :: !PointType121MasterRegister2 ,pointType121NumOfRegisters2 :: !PointType121NumOfRegisters2 ,pointType121CommStatus2 :: !PointType121CommStatus2 ,pointType121SlaveAddress3 :: !PointType121SlaveAddress3 ,pointType121FunctionCode3 :: !PointType121FunctionCode3 ,pointType121SlaveRegister3 :: !PointType121SlaveRegister3 ,pointType121MasterRegister3 :: !PointType121MasterRegister3 ,pointType121NumOfRegisters3 :: !PointType121NumOfRegisters3 ,pointType121CommStatus3 :: !PointType121CommStatus3 ,pointType121SlaveAddress4 :: !PointType121SlaveAddress4 ,pointType121FunctionCode4 :: !PointType121FunctionCode4 ,pointType121SlaveRegister4 :: !PointType121SlaveRegister4 ,pointType121MasterRegister4 :: !PointType121MasterRegister4 ,pointType121NumOfRegisters4 :: !PointType121NumOfRegisters4 ,pointType121CommStatus4 :: !PointType121CommStatus4 ,pointType121SlaveAddress5 :: !PointType121SlaveAddress5 ,pointType121FunctionCode5 :: !PointType121FunctionCode5 ,pointType121SlaveRegister5 :: !PointType121SlaveRegister5 ,pointType121MasterRegister5 :: !PointType121MasterRegister5 ,pointType121NumOfRegisters5 :: !PointType121NumOfRegisters5 ,pointType121CommStatus5 :: !PointType121CommStatus5 ,pointType121SlaveAddress6 :: !PointType121SlaveAddress6 ,pointType121FunctionCode6 :: !PointType121FunctionCode6 ,pointType121SlaveRegister6 :: !PointType121SlaveRegister6 ,pointType121MasterRegister6 :: !PointType121MasterRegister6 ,pointType121NumOfRegisters6 :: !PointType121NumOfRegisters6 ,pointType121CommStatus6 :: !PointType121CommStatus6 ,pointType121SlaveAddress7 :: !PointType121SlaveAddress7 ,pointType121FunctionCode7 :: !PointType121FunctionCode7 ,pointType121SlaveRegister7 :: !PointType121SlaveRegister7 ,pointType121MasterRegister7 :: !PointType121MasterRegister7 ,pointType121NumOfRegisters7 :: !PointType121NumOfRegisters7 ,pointType121CommStatus7 :: !PointType121CommStatus7 ,pointType121SlaveAddress8 :: !PointType121SlaveAddress8 ,pointType121FunctionCode8 :: !PointType121FunctionCode8 ,pointType121SlaveRegister8 :: !PointType121SlaveRegister8 ,pointType121MasterRegister8 :: !PointType121MasterRegister8 ,pointType121NumOfRegisters8 :: !PointType121NumOfRegisters8 ,pointType121CommStatus8 :: !PointType121CommStatus8 ,pointType121SlaveAddress9 :: !PointType121SlaveAddress9 ,pointType121FunctionCode9 :: !PointType121FunctionCode9 ,pointType121SlaveRegister9 :: !PointType121SlaveRegister9 ,pointType121MasterRegister9 :: !PointType121MasterRegister9 ,pointType121NumOfRegisters9 :: !PointType121NumOfRegisters9 ,pointType121CommStatus9 :: !PointType121CommStatus9 ,pointType121SlaveAddress10 :: !PointType121SlaveAddress10 ,pointType121FunctionCode10 :: !PointType121FunctionCode10 ,pointType121SlaveRegister10 :: !PointType121SlaveRegister10 ,pointType121MasterRegister10 :: !PointType121MasterRegister10 ,pointType121NumOfRegisters10 :: !PointType121NumOfRegisters10 ,pointType121CommStatus10 :: !PointType121CommStatus10 ,pointType121SlaveAddress11 :: !PointType121SlaveAddress11 ,pointType121FunctionCode11 :: !PointType121FunctionCode11 ,pointType121SlaveRegister11 :: !PointType121SlaveRegister11 ,pointType121MasterRegister11 :: !PointType121MasterRegister11 ,pointType121NumOfRegisters11 :: !PointType121NumOfRegisters11 ,pointType121CommStatus11 :: !PointType121CommStatus11 ,pointType121SlaveAddress12 :: !PointType121SlaveAddress12 ,pointType121FunctionCode12 :: !PointType121FunctionCode12 ,pointType121SlaveRegister12 :: !PointType121SlaveRegister12 ,pointType121MasterRegister12 :: !PointType121MasterRegister12 ,pointType121NumOfRegisters12 :: !PointType121NumOfRegisters12 ,pointType121CommStatus12 :: !PointType121CommStatus12 ,pointType121SlaveAddress13 :: !PointType121SlaveAddress13 ,pointType121FunctionCode13 :: !PointType121FunctionCode13 ,pointType121SlaveRegister13 :: !PointType121SlaveRegister13 ,pointType121MasterRegister13 :: !PointType121MasterRegister13 ,pointType121NumOfRegisters13 :: !PointType121NumOfRegisters13 ,pointType121CommStatus13 :: !PointType121CommStatus13 ,pointType121SlaveAddress14 :: !PointType121SlaveAddress14 ,pointType121FunctionCode14 :: !PointType121FunctionCode14 ,pointType121SlaveRegister14 :: !PointType121SlaveRegister14 ,pointType121MasterRegister14 :: !PointType121MasterRegister14 ,pointType121NumOfRegisters14 :: !PointType121NumOfRegisters14 ,pointType121CommStatus14 :: !PointType121CommStatus14 ,pointType121SlaveAddress15 :: !PointType121SlaveAddress15 ,pointType121FunctionCode15 :: !PointType121FunctionCode15 ,pointType121SlaveRegister15 :: !PointType121SlaveRegister15 ,pointType121MasterRegister15 :: !PointType121MasterRegister15 ,pointType121NumOfRegisters15 :: !PointType121NumOfRegisters15 ,pointType121CommStatus15 :: !PointType121CommStatus15 ,pointType121SlaveAddress16 :: !PointType121SlaveAddress16 ,pointType121FunctionCode16 :: !PointType121FunctionCode16 ,pointType121SlaveRegister16 :: !PointType121SlaveRegister16 ,pointType121MasterRegister16 :: !PointType121MasterRegister16 ,pointType121NumOfRegisters16 :: !PointType121NumOfRegisters16 ,pointType121CommStatus16 :: !PointType121CommStatus16 ,pointType121SlaveAddress17 :: !PointType121SlaveAddress17 ,pointType121FunctionCode17 :: !PointType121FunctionCode17 ,pointType121SlaveRegister17 :: !PointType121SlaveRegister17 ,pointType121MasterRegister17 :: !PointType121MasterRegister17 ,pointType121NumOfRegisters17 :: !PointType121NumOfRegisters17 ,pointType121CommStatus17 :: !PointType121CommStatus17 ,pointType121SlaveAddress18 :: !PointType121SlaveAddress18 ,pointType121FunctionCode18 :: !PointType121FunctionCode18 ,pointType121SlaveRegister18 :: !PointType121SlaveRegister18 ,pointType121MasterRegister18 :: !PointType121MasterRegister18 ,pointType121NumOfRegisters18 :: !PointType121NumOfRegisters18 ,pointType121CommStatus18 :: !PointType121CommStatus18 ,pointType121SlaveAddress19 :: !PointType121SlaveAddress19 ,pointType121FunctionCode19 :: !PointType121FunctionCode19 ,pointType121SlaveRegister19 :: !PointType121SlaveRegister19 ,pointType121MasterRegister19 :: !PointType121MasterRegister19 ,pointType121NumOfRegisters19 :: !PointType121NumOfRegisters19 ,pointType121CommStatus19 :: !PointType121CommStatus19 ,pointType121SlaveAddress20 :: !PointType121SlaveAddress20 ,pointType121FunctionCode20 :: !PointType121FunctionCode20 ,pointType121SlaveRegister20 :: !PointType121SlaveRegister20 ,pointType121MasterRegister20 :: !PointType121MasterRegister20 ,pointType121NumOfRegisters20 :: !PointType121NumOfRegisters20 ,pointType121CommStatus20 :: !PointType121CommStatus20 ,pointType121SlaveAddress21 :: !PointType121SlaveAddress21 ,pointType121FunctionCode21 :: !PointType121FunctionCode21 ,pointType121SlaveRegister21 :: !PointType121SlaveRegister21 ,pointType121MasterRegister21 :: !PointType121MasterRegister21 ,pointType121NumOfRegisters21 :: !PointType121NumOfRegisters21 ,pointType121CommStatus21 :: !PointType121CommStatus21 ,pointType121SlaveAddress22 :: !PointType121SlaveAddress22 ,pointType121FunctionCode22 :: !PointType121FunctionCode22 ,pointType121SlaveRegister22 :: !PointType121SlaveRegister22 ,pointType121MasterRegister22 :: !PointType121MasterRegister22 ,pointType121NumOfRegisters22 :: !PointType121NumOfRegisters22 ,pointType121CommStatus22 :: !PointType121CommStatus22 ,pointType121SlaveAddress23 :: !PointType121SlaveAddress23 ,pointType121FunctionCode23 :: !PointType121FunctionCode23 ,pointType121SlaveRegister23 :: !PointType121SlaveRegister23 ,pointType121MasterRegister23 :: !PointType121MasterRegister23 ,pointType121NumOfRegisters23 :: !PointType121NumOfRegisters23 ,pointType121CommStatus23 :: !PointType121CommStatus23 ,pointType121SlaveAddress24 :: !PointType121SlaveAddress24 ,pointType121FunctionCode24 :: !PointType121FunctionCode24 ,pointType121SlaveRegister24 :: !PointType121SlaveRegister24 ,pointType121MasterRegister24 :: !PointType121MasterRegister24 ,pointType121NumOfRegisters24 :: !PointType121NumOfRegisters24 ,pointType121CommStatus24 :: !PointType121CommStatus24 ,pointType121SlaveAddress25 :: !PointType121SlaveAddress25 ,pointType121FunctionCode25 :: !PointType121FunctionCode25 ,pointType121SlaveRegister25 :: !PointType121SlaveRegister25 ,pointType121MasterRegister25 :: !PointType121MasterRegister25 ,pointType121NumOfRegisters25 :: !PointType121NumOfRegisters25 ,pointType121CommStatus25 :: !PointType121CommStatus25 } deriving (Read,Eq, Show, Generic) type PointType121TagID = BS.ByteString type PointType121SlaveAddress1 = Word8 type PointType121FunctionCode1 = Word8 type PointType121SlaveRegister1 = Word16 type PointType121MasterRegister1 = Word16 type PointType121NumOfRegisters1 = Word8 type PointType121CommStatus1 = Word8 type PointType121SlaveAddress2 = Word8 type PointType121FunctionCode2 = Word8 type PointType121SlaveRegister2 = Word16 type PointType121MasterRegister2 = Word16 type PointType121NumOfRegisters2 = Word8 type PointType121CommStatus2 = Word8 type PointType121SlaveAddress3 = Word8 type PointType121FunctionCode3 = Word8 type PointType121SlaveRegister3 = Word16 type PointType121MasterRegister3 = Word16 type PointType121NumOfRegisters3 = Word8 type PointType121CommStatus3 = Word8 type PointType121SlaveAddress4 = Word8 type PointType121FunctionCode4 = Word8 type PointType121SlaveRegister4 = Word16 type PointType121MasterRegister4 = Word16 type PointType121NumOfRegisters4 = Word8 type PointType121CommStatus4 = Word8 type PointType121SlaveAddress5 = Word8 type PointType121FunctionCode5 = Word8 type PointType121SlaveRegister5 = Word16 type PointType121MasterRegister5 = Word16 type PointType121NumOfRegisters5 = Word8 type PointType121CommStatus5 = Word8 type PointType121SlaveAddress6 = Word8 type PointType121FunctionCode6 = Word8 type PointType121SlaveRegister6 = Word16 type PointType121MasterRegister6 = Word16 type PointType121NumOfRegisters6 = Word8 type PointType121CommStatus6 = Word8 type PointType121SlaveAddress7 = Word8 type PointType121FunctionCode7 = Word8 type PointType121SlaveRegister7 = Word16 type PointType121MasterRegister7 = Word16 type PointType121NumOfRegisters7 = Word8 type PointType121CommStatus7 = Word8 type PointType121SlaveAddress8 = Word8 type PointType121FunctionCode8 = Word8 type PointType121SlaveRegister8 = Word16 type PointType121MasterRegister8 = Word16 type PointType121NumOfRegisters8 = Word8 type PointType121CommStatus8 = Word8 type PointType121SlaveAddress9 = Word8 type PointType121FunctionCode9 = Word8 type PointType121SlaveRegister9 = Word16 type PointType121MasterRegister9 = Word16 type PointType121NumOfRegisters9 = Word8 type PointType121CommStatus9 = Word8 type PointType121SlaveAddress10 = Word8 type PointType121FunctionCode10 = Word8 type PointType121SlaveRegister10 = Word16 type PointType121MasterRegister10 = Word16 type PointType121NumOfRegisters10 = Word8 type PointType121CommStatus10 = Word8 type PointType121SlaveAddress11 = Word8 type PointType121FunctionCode11 = Word8 type PointType121SlaveRegister11 = Word16 type PointType121MasterRegister11 = Word16 type PointType121NumOfRegisters11 = Word8 type PointType121CommStatus11 = Word8 type PointType121SlaveAddress12 = Word8 type PointType121FunctionCode12 = Word8 type PointType121SlaveRegister12 = Word16 type PointType121MasterRegister12 = Word16 type PointType121NumOfRegisters12 = Word8 type PointType121CommStatus12 = Word8 type PointType121SlaveAddress13 = Word8 type PointType121FunctionCode13 = Word8 type PointType121SlaveRegister13 = Word16 type PointType121MasterRegister13 = Word16 type PointType121NumOfRegisters13 = Word8 type PointType121CommStatus13 = Word8 type PointType121SlaveAddress14 = Word8 type PointType121FunctionCode14 = Word8 type PointType121SlaveRegister14 = Word16 type PointType121MasterRegister14 = Word16 type PointType121NumOfRegisters14 = Word8 type PointType121CommStatus14 = Word8 type PointType121SlaveAddress15 = Word8 type PointType121FunctionCode15 = Word8 type PointType121SlaveRegister15 = Word16 type PointType121MasterRegister15 = Word16 type PointType121NumOfRegisters15 = Word8 type PointType121CommStatus15 = Word8 type PointType121SlaveAddress16 = Word8 type PointType121FunctionCode16 = Word8 type PointType121SlaveRegister16 = Word16 type PointType121MasterRegister16 = Word16 type PointType121NumOfRegisters16 = Word8 type PointType121CommStatus16 = Word8 type PointType121SlaveAddress17 = Word8 type PointType121FunctionCode17 = Word8 type PointType121SlaveRegister17 = Word16 type PointType121MasterRegister17 = Word16 type PointType121NumOfRegisters17 = Word8 type PointType121CommStatus17 = Word8 type PointType121SlaveAddress18 = Word8 type PointType121FunctionCode18 = Word8 type PointType121SlaveRegister18 = Word16 type PointType121MasterRegister18 = Word16 type PointType121NumOfRegisters18 = Word8 type PointType121CommStatus18 = Word8 type PointType121SlaveAddress19 = Word8 type PointType121FunctionCode19 = Word8 type PointType121SlaveRegister19 = Word16 type PointType121MasterRegister19 = Word16 type PointType121NumOfRegisters19 = Word8 type PointType121CommStatus19 = Word8 type PointType121SlaveAddress20 = Word8 type PointType121FunctionCode20 = Word8 type PointType121SlaveRegister20 = Word16 type PointType121MasterRegister20 = Word16 type PointType121NumOfRegisters20 = Word8 type PointType121CommStatus20 = Word8 type PointType121SlaveAddress21 = Word8 type PointType121FunctionCode21 = Word8 type PointType121SlaveRegister21 = Word16 type PointType121MasterRegister21 = Word16 type PointType121NumOfRegisters21 = Word8 type PointType121CommStatus21 = Word8 type PointType121SlaveAddress22 = Word8 type PointType121FunctionCode22 = Word8 type PointType121SlaveRegister22 = Word16 type PointType121MasterRegister22 = Word16 type PointType121NumOfRegisters22 = Word8 type PointType121CommStatus22 = Word8 type PointType121SlaveAddress23 = Word8 type PointType121FunctionCode23 = Word8 type PointType121SlaveRegister23 = Word16 type PointType121MasterRegister23 = Word16 type PointType121NumOfRegisters23 = Word8 type PointType121CommStatus23 = Word8 type PointType121SlaveAddress24 = Word8 type PointType121FunctionCode24 = Word8 type PointType121SlaveRegister24 = Word16 type PointType121MasterRegister24 = Word16 type PointType121NumOfRegisters24 = Word8 type PointType121CommStatus24 = Word8 type PointType121SlaveAddress25 = Word8 type PointType121FunctionCode25 = Word8 type PointType121SlaveRegister25 = Word16 type PointType121MasterRegister25 = Word16 type PointType121NumOfRegisters25 = Word8 type PointType121CommStatus25 = Word8 pointType121Parser :: Get PointType121 pointType121Parser = do tagID <- getByteString 10 slaveAddress1 <- getWord8 functionCode1 <- getWord8 slaveRegister1 <- getWord16le masterRegister1 <- getWord16le numOfRegisters1 <- getWord8 commStatus1 <- getWord8 slaveAddress2 <- getWord8 functionCode2 <- getWord8 slaveRegister2 <- getWord16le masterRegister2 <- getWord16le numOfRegisters2 <- getWord8 commStatus2 <- getWord8 slaveAddress3 <- getWord8 functionCode3 <- getWord8 slaveRegister3 <- getWord16le masterRegister3 <- getWord16le numOfRegisters3 <- getWord8 commStatus3 <- getWord8 slaveAddress4 <- getWord8 functionCode4 <- getWord8 slaveRegister4 <- getWord16le masterRegister4 <- getWord16le numOfRegisters4 <- getWord8 commStatus4 <- getWord8 slaveAddress5 <- getWord8 functionCode5 <- getWord8 slaveRegister5 <- getWord16le masterRegister5 <- getWord16le numOfRegisters5 <- getWord8 commStatus5 <- getWord8 slaveAddress6 <- getWord8 functionCode6 <- getWord8 slaveRegister6 <- getWord16le masterRegister6 <- getWord16le numOfRegisters6 <- getWord8 commStatus6 <- getWord8 slaveAddress7 <- getWord8 functionCode7 <- getWord8 slaveRegister7 <- getWord16le masterRegister7 <- getWord16le numOfRegisters7 <- getWord8 commStatus7 <- getWord8 slaveAddress8 <- getWord8 functionCode8 <- getWord8 slaveRegister8 <- getWord16le masterRegister8 <- getWord16le numOfRegisters8 <- getWord8 commStatus8 <- getWord8 slaveAddress9 <- getWord8 functionCode9 <- getWord8 slaveRegister9 <- getWord16le masterRegister9 <- getWord16le numOfRegisters9 <- getWord8 commStatus9 <- getWord8 slaveAddress10 <- getWord8 functionCode10 <- getWord8 slaveRegister10 <- getWord16le masterRegister10 <- getWord16le numOfRegisters10 <- getWord8 commStatus10 <- getWord8 slaveAddress11 <- getWord8 functionCode11 <- getWord8 slaveRegister11 <- getWord16le masterRegister11 <- getWord16le numOfRegisters11 <- getWord8 commStatus11 <- getWord8 slaveAddress12 <- getWord8 functionCode12 <- getWord8 slaveRegister12 <- getWord16le masterRegister12 <- getWord16le numOfRegisters12 <- getWord8 commStatus12 <- getWord8 slaveAddress13 <- getWord8 functionCode13 <- getWord8 slaveRegister13 <- getWord16le masterRegister13 <- getWord16le numOfRegisters13 <- getWord8 commStatus13 <- getWord8 slaveAddress14 <- getWord8 functionCode14 <- getWord8 slaveRegister14 <- getWord16le masterRegister14 <- getWord16le numOfRegisters14 <- getWord8 commStatus14 <- getWord8 slaveAddress15 <- getWord8 functionCode15 <- getWord8 slaveRegister15 <- getWord16le masterRegister15 <- getWord16le numOfRegisters15 <- getWord8 commStatus15 <- getWord8 slaveAddress16 <- getWord8 functionCode16 <- getWord8 slaveRegister16 <- getWord16le masterRegister16 <- getWord16le numOfRegisters16 <- getWord8 commStatus16 <- getWord8 slaveAddress17 <- getWord8 functionCode17 <- getWord8 slaveRegister17 <- getWord16le masterRegister17 <- getWord16le numOfRegisters17 <- getWord8 commStatus17 <- getWord8 slaveAddress18 <- getWord8 functionCode18 <- getWord8 slaveRegister18 <- getWord16le masterRegister18 <- getWord16le numOfRegisters18 <- getWord8 commStatus18 <- getWord8 slaveAddress19 <- getWord8 functionCode19 <- getWord8 slaveRegister19 <- getWord16le masterRegister19 <- getWord16le numOfRegisters19 <- getWord8 commStatus19 <- getWord8 slaveAddress20 <- getWord8 functionCode20 <- getWord8 slaveRegister20 <- getWord16le masterRegister20 <- getWord16le numOfRegisters20 <- getWord8 commStatus20 <- getWord8 slaveAddress21 <- getWord8 functionCode21 <- getWord8 slaveRegister21 <- getWord16le masterRegister21 <- getWord16le numOfRegisters21 <- getWord8 commStatus21 <- getWord8 slaveAddress22 <- getWord8 functionCode22 <- getWord8 slaveRegister22 <- getWord16le masterRegister22 <- getWord16le numOfRegisters22 <- getWord8 commStatus22 <- getWord8 slaveAddress23 <- getWord8 functionCode23 <- getWord8 slaveRegister23 <- getWord16le masterRegister23 <- getWord16le numOfRegisters23 <- getWord8 commStatus23 <- getWord8 slaveAddress24 <- getWord8 functionCode24 <- getWord8 slaveRegister24 <- getWord16le masterRegister24 <- getWord16le numOfRegisters24 <- getWord8 commStatus24 <- getWord8 slaveAddress25 <- getWord8 functionCode25 <- getWord8 slaveRegister25 <- getWord16le masterRegister25 <- getWord16le numOfRegisters25 <- getWord8 commStatus25 <- getWord8 return $ PointType121 tagID slaveAddress1 functionCode1 slaveRegister1 masterRegister1 numOfRegisters1 commStatus1 slaveAddress2 functionCode2 slaveRegister2 masterRegister2 numOfRegisters2 commStatus2 slaveAddress3 functionCode3 slaveRegister3 masterRegister3 numOfRegisters3 commStatus3 slaveAddress4 functionCode4 slaveRegister4 masterRegister4 numOfRegisters4 commStatus4 slaveAddress5 functionCode5 slaveRegister5 masterRegister5 numOfRegisters5 commStatus5 slaveAddress6 functionCode6 slaveRegister6 masterRegister6 numOfRegisters6 commStatus6 slaveAddress7 functionCode7 slaveRegister7 masterRegister7 numOfRegisters7 commStatus7 slaveAddress8 functionCode8 slaveRegister8 masterRegister8 numOfRegisters8 commStatus8 slaveAddress9 functionCode9 slaveRegister9 masterRegister9 numOfRegisters9 commStatus9 slaveAddress10 functionCode10 slaveRegister10 masterRegister10 numOfRegisters10 commStatus10 slaveAddress11 functionCode11 slaveRegister11 masterRegister11 numOfRegisters11 commStatus11 slaveAddress12 functionCode12 slaveRegister12 masterRegister12 numOfRegisters12 commStatus12 slaveAddress13 functionCode13 slaveRegister13 masterRegister13 numOfRegisters13 commStatus13 slaveAddress14 functionCode14 slaveRegister14 masterRegister14 numOfRegisters14 commStatus14 slaveAddress15 functionCode15 slaveRegister15 masterRegister15 numOfRegisters15 commStatus15 slaveAddress16 functionCode16 slaveRegister16 masterRegister16 numOfRegisters16 commStatus16 slaveAddress17 functionCode17 slaveRegister17 masterRegister17 numOfRegisters17 commStatus17 slaveAddress18 functionCode18 slaveRegister18 masterRegister18 numOfRegisters18 commStatus18 slaveAddress19 functionCode19 slaveRegister19 masterRegister19 numOfRegisters19 commStatus19 slaveAddress20 functionCode20 slaveRegister20 masterRegister20 numOfRegisters20 commStatus20 slaveAddress21 functionCode21 slaveRegister21 masterRegister21 numOfRegisters21 commStatus21 slaveAddress22 functionCode22 slaveRegister22 masterRegister22 numOfRegisters22 commStatus22 slaveAddress23 functionCode23 slaveRegister23 masterRegister23 numOfRegisters23 commStatus23 slaveAddress24 functionCode24 slaveRegister24 masterRegister24 numOfRegisters24 commStatus24 slaveAddress25 functionCode25 slaveRegister25 masterRegister25 numOfRegisters25 commStatus25
jqpeterson/roc-translator
src/Protocol/ROC/PointTypes/PointType121.hs
bsd-3-clause
30,295
0
9
9,947
3,414
1,865
1,549
781
1
module UnionFind(UF, Replacement((:>)), newSym, (=:=), rep, frozen, runUF, S, isRep) where import Prelude hiding (min) import Control.Monad.State.Strict import Data.IntMap(IntMap) import qualified Data.IntMap as IntMap data S = S { links :: IntMap Int, sym :: Int } type UF = State S data Replacement = Int :> Int runUF :: Int -> UF a -> a runUF numSyms m = fst (runState m (S IntMap.empty numSyms)) modifyLinks f = modify (\s -> s { links = f (links s) }) modifySym f = modify (\s -> s { sym = f (sym s) }) putLinks l = modifyLinks (const l) newSym :: UF Int newSym = do s <- get modifySym (+1) return (sym s) (=:=) :: Int -> Int -> UF (Maybe Replacement) s =:= t | s == t = return Nothing s =:= t = do rs <- rep s rt <- rep t if (rs /= rt) then do modifyLinks (IntMap.insert rs rt) return (Just (rs :> rt)) else return Nothing rep :: Int -> UF Int rep t = do m <- fmap links get case IntMap.lookup t m of Nothing -> return t Just t' -> do r <- rep t' when (t' /= r) $ modifyLinks (IntMap.insert t r) return r isRep :: Int -> UF Bool isRep t = do t' <- frozen (rep t) return (t == t') frozen :: UF a -> UF a frozen x = fmap (evalState x) get
jystic/QuickSpec
qs1/UnionFind.hs
bsd-3-clause
1,225
0
16
323
625
317
308
46
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} module Sys.CreateProcess( CreateProcess(..) , AsCreateProcess(..) , AsWorkingDirectory(..) , AsEnvironment(..) , AsStdin(..) , AsStdout(..) , AsStderr(..) , AsCloseDescriptors(..) , AsCreateGroup(..) , AsDelegateCtrlC(..) ) where import Control.Applicative(Applicative) import Control.Category(Category(id, (.))) import Control.Lens(Optic', Profunctor, lens, from, iso, (#)) import Data.Bool(Bool) import Data.Eq(Eq) import Data.Functor(Functor) import Data.Maybe(Maybe) import Data.String(String) import Prelude(Show) import Sys.CmdSpec(CmdSpec, AsCmdSpec(_CmdSpec), AsExecutableName(_ExecutableName), AsExecutableArguments(_ExecutableArguments), AsShellCommand(_ShellCommand), AsRawCommand(_RawCommand)) import Sys.StdStream(StdStream, AsStdStream(_StdStream)) import System.FilePath(FilePath) import System.Posix.Types(GroupID, UserID) import qualified System.Process as Process -- | Data type representing a process. -- -- /see 'System.Process.CreateProcess'/. data CreateProcess = CreateProcess CmdSpec (Maybe FilePath) (Maybe [(String,String)]) StdStream StdStream StdStream Bool Bool Bool Bool Bool Bool (Maybe GroupID) (Maybe UserID) deriving (Eq, Show) -- | Types that related to @CreateProcess@. class AsCreateProcess p f s where _CreateProcess :: Optic' p f s CreateProcess instance AsCreateProcess p f CreateProcess where _CreateProcess = id instance (Profunctor p, Functor f) => AsCreateProcess p f Process.CreateProcess where _CreateProcess = iso (\(Process.CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) -> CreateProcess (from _CmdSpec # s) p e (from _StdStream # i) (from _StdStream # o) (from _StdStream # r) d g c x1 x2 x3 x4 x5) (\(CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) -> Process.CreateProcess (_CmdSpec # s) p e (_StdStream # i) (_StdStream # o) (_StdStream # r) d g c x1 x2 x3 x4 x5) instance Functor f => AsCmdSpec (->) f CreateProcess where _CmdSpec = lens (\(CreateProcess s _ _ _ _ _ _ _ _ _ _ _ _ _) -> s) (\(CreateProcess _ p e i o r d g c x1 x2 x3 x4 x5) s -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) instance Applicative f => AsExecutableName (->) f CreateProcess where _ExecutableName = _CmdSpec . _ExecutableName instance Applicative f => AsExecutableArguments (->) f CreateProcess where _ExecutableArguments = _CmdSpec . _ExecutableArguments instance Applicative f => AsShellCommand (->) f CreateProcess where _ShellCommand = _CmdSpec . _ShellCommand instance Applicative f => AsRawCommand (->) f CreateProcess where _RawCommand = _CmdSpec . _RawCommand -- | Types that relate to a (maybe) working directory. class AsWorkingDirectory p f s where _WorkingDirectory :: Optic' p f s (Maybe FilePath) instance AsWorkingDirectory p f (Maybe FilePath) where _WorkingDirectory = id instance Functor f => AsWorkingDirectory (->) f CreateProcess where _WorkingDirectory = lens (\(CreateProcess _ p _ _ _ _ _ _ _ _ _ _ _ _) -> p) (\(CreateProcess s _ e i o r d g c x1 x2 x3 x4 x5) p -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) -- | Types that relate to an environment. class AsEnvironment p f s where _Environment :: Optic' p f s (Maybe [(String, String)]) instance AsEnvironment p f (Maybe [(String, String)]) where _Environment = id instance Functor f => AsEnvironment (->) f CreateProcess where _Environment = lens (\(CreateProcess _ _ e _ _ _ _ _ _ _ _ _ _ _) -> e) (\(CreateProcess s p _ i o r d g c x1 x2 x3 x4 x5) e -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) -- | Types that relate to a standard input stream. class AsStdin p f s where _Stdin :: Optic' p f s StdStream instance AsStdin p f StdStream where _Stdin = id instance Functor f => AsStdin (->) f CreateProcess where _Stdin = lens (\(CreateProcess _ _ _ i _ _ _ _ _ _ _ _ _ _) -> i) (\(CreateProcess s p e _ o r d g c x1 x2 x3 x4 x5) i -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) -- | Types that relate to a standard output stream. class AsStdout p f s where _Stdout :: Optic' p f s StdStream instance AsStdout p f StdStream where _Stdout = id instance Functor f => AsStdout (->) f CreateProcess where _Stdout = lens (\(CreateProcess _ _ _ _ o _ _ _ _ _ _ _ _ _) -> o) (\(CreateProcess s p e i _ r d g c x1 x2 x3 x4 x5) o -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) -- | Types that relate to a standard error stream. class AsStderr p f s where _Stderr :: Optic' p f s StdStream instance AsStderr p f StdStream where _Stderr = id instance Functor f => AsStderr (->) f CreateProcess where _Stderr = lens (\(CreateProcess _ _ _ _ _ r _ _ _ _ _ _ _ _) -> r) (\(CreateProcess s p e i o _ d g c x1 x2 x3 x4 x5) r -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) -- | Types that relate to closing descriptors. class AsCloseDescriptors p f s where _CloseDescriptors :: Optic' p f s Bool instance AsCloseDescriptors p f Bool where _CloseDescriptors = id instance Functor f => AsCloseDescriptors (->) f CreateProcess where _CloseDescriptors = lens (\(CreateProcess _ _ _ _ _ _ d _ _ _ _ _ _ _) -> d) (\(CreateProcess s p e i o r _ g c x1 x2 x3 x4 x5) d -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) -- | Types that relate to creating groups. class AsCreateGroup p f s where _CreateGroup :: Optic' p f s Bool instance AsCreateGroup p f Bool where _CreateGroup = id instance Functor f => AsCreateGroup (->) f CreateProcess where _CreateGroup = lens (\(CreateProcess _ _ _ _ _ _ _ g _ _ _ _ _ _) -> g) (\(CreateProcess s p e i o r d _ c x1 x2 x3 x4 x5) g-> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) -- | Types that relate to delegating CTRL-C. class AsDelegateCtrlC p f s where _DelegateCtrlC :: Optic' p f s Bool instance AsDelegateCtrlC p f Bool where _DelegateCtrlC = id instance Functor f => AsDelegateCtrlC (->) f CreateProcess where _DelegateCtrlC = lens (\(CreateProcess _ _ _ _ _ _ _ _ c _ _ _ _ _) -> c) (\(CreateProcess s p e i o r d g _ x1 x2 x3 x4 x5) c -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5)
NICTA/sys-process
src/Sys/CreateProcess.hs
bsd-3-clause
6,412
0
12
1,549
2,477
1,318
1,159
163
0
----------------------------------------------------------------------------- -- | -- Module : Data.Digest.MD5 -- Copyright : (c) Dominic Steinitz 2004 -- License : BSD-style (see the file ReadMe.tex) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Takes the MD5 module supplied by Ian Lynagh and wraps it so it -- takes [Octet] and returns [Octet] where the length of the result -- is always 16. -- See <http://web.comlab.ox.ac.uk/oucl/work/ian.lynagh/> -- and <http://www.ietf.org/rfc/rfc1321.txt>. -- ----------------------------------------------------------------------------- module Network.HTTP.MD5 ( hash , Octet ) where import Data.List (unfoldr) import Data.Word (Word8) import Numeric (readHex) import Network.HTTP.MD5Aux (md5s, Str(Str)) type Octet = Word8 -- | Take [Octet] and return [Octet] according to the standard. -- The length of the result is always 16 octets or 128 bits as required -- by the standard. hash :: [Octet] -> [Octet] hash xs = unfoldr f $ md5s $ Str $ map (toEnum . fromIntegral) xs where f :: String -> Maybe (Octet,String) f [] = Nothing f [x] = f ['0',x] f (x:y:zs) = Just (a,zs) where [(a,_)] = readHex (x:y:[])
astro/HTTPbis
Network/HTTP/MD5.hs
bsd-3-clause
1,331
1
10
290
244
147
97
16
3
module ParserSpec where import qualified Data.Vector as Vec import Function import qualified Library as Lib import Parser import Test.Hspec import Text.Trifecta toEither :: Result a -> Either String a toEither (Success a) = Right a toEither (Failure e) = Left $ show e fSin = simpleFunc "sin" $ Right . sin fLog = simpleFunc "log" $ Right . log fExp = simpleFunc "exp" $ Right . exp suite :: SpecWith () suite = do describe "Ignore junk" $ do let parse p = toEither . parseString (parseInput p) mempty let value = some letter let twoValues = do v1 <- value skipJunk v2 <- value return (v1, v2) it "none" $ parse value "value" `shouldBe` Right "value" it "before" $ parse value "# junk\n\n\n# junk2\n\nvalue" `shouldBe` Right "value" it "after" $ parse value "value\n\n#junk\n\n#junk2\n\n" `shouldBe` Right "value" it "around" $ parse value "# junk\n\n\n# junk2\n\nvalue\n\n#junk\n\n#junk2\n\n" `shouldBe` Right "value" it "between" $ parse twoValues "value\n\n#junk\n\n#junk2\n\nvalued" `shouldBe` Right ("value", "valued") describe "Parsing decimal" $ do let parse = toEither . parseString parseDecimal mempty it "just int" $ parse "5" `shouldBe` Right 5 it "just real" $ parse "3.43" `shouldBe` Right 3.43 it "with preceding spaces" $ parse " \t 4" `shouldBe` Right 4 describe "Parse function" $ do let parse p s = toEither (parseString p mempty s) it "constant" $ parse parseFunction "345" `shouldBe` Right (Function "345" (const $ Right 345)) it "x" $ parse parseFunction "x" `shouldBe` Right (Function "x0" $ Right . (Vec.! 0)) it "x1" $ parse parseFunction "x1" `shouldBe` Right (Function "x1" $ Right . (Vec.! 1)) it "x3" $ parse parseFunction "x3" `shouldBe` Right (Function "x3" $ Right . (Vec.! 3)) it "sin" $ parse parseFunction "sin" `shouldBe` Right fSin it "log" $ parse parseFunction "log" `shouldBe` Right fLog it "exp" $ parse parseFunction "exp" `shouldBe` Right fExp it "power" $ parse parseExpression "cos(x0)^x1" `shouldBe` Right (Function "cos(x0)^x1" (\v -> Right $ cos (v Vec.! 0) ** (v Vec.! 1))) it "composition sin(x0)" $ parse parseExpression "sin(x0)" `shouldBe` Right fSin it "composition sin(log(x0))" $ parse parseExpression "sin(log(x0))" `shouldBe` Right (compose fSin fLog) it "of sum of funcs" $ parse parseExpression "sin(x0)+log(x0)" `shouldBe` Right (simpleFunc "sin(x0)+log(x0)" (\x -> Right $ sin x + log x)) it "of fraction of funcs" $ parse parseExpression "sin(x0)/exp(x0)" `shouldBe` Right (simpleFunc "sin(x0)/exp(x0)" (\x -> Right $ sin x / exp x)) it "with different vars" $ parse parseExpression "x0*x1*x2" `shouldBe` Right (Function "x0*x1*x2" (\v -> Right $ v Vec.! 0 * v Vec.! 1 * v Vec.! 2)) it "with multiple ( and )" $ do let expr = "(x0-(x1*x2))+sin((x0*x1)-(x0-x1))" parse parseExpression expr `shouldBe` Right (Function expr (\v -> let x0 = v Vec.! 0 x1 = v Vec.! 1 x2 = v Vec.! 2 in Right $ (x0 - (x1*x2)) + sin ((x0*x1) - (x0 - x1)) )) describe "Parsing list" $ do let parse p s = toEither (parseString (parseList p) mempty s) it "of ints" $ parse parseDecimal "1\n2\r3\n\r4\n" `shouldBe` Right [1, 2, 3, 4] describe "Parsing vector" $ do let parse p s = Vec.toList <$> toEither (parseString (parseVector p) mempty s) it "of ints" $ parse parseDecimal "1 2 3" `shouldBe` Right [1, 2, 3] it "of floats with tabs and trailing space" $ parse parseDecimal "4.9\t8.3\t9 10.5 \t" `shouldBe` Right [4.9, 8.3, 9, 10.5] it "of funcs" $ parse parseExpression "1 2 sin(x0) exp(x0)+sin(log(x0))" `shouldBe` Right [ Function "1" (const $ Right 1) , Function "2" (const $ Right 2) , fSin , simpleFunc "exp(x0)+sin(log(x0))" (\x -> Right $ exp x + sin (log x)) ] describe "Parsing matrix" $ do let parse p s = fmap Vec.toList <$> toEither (parseString (parseVectors p) mempty s) let testMatrix = Right [[1, 2, 3], [4, 5, 6], [7, 8, 9]] it "of ints" $ parse parseDecimal "1 2 3\n4 5 6\n7 8 9" `shouldBe` testMatrix it "with trailing eol" $ parse parseDecimal "1 2 3\n4 5 6\n7 8 9\n" `shouldBe` testMatrix it "of funcs" $ parse parseExpression "1 4 sin(x0)\n5 6 exp(sin(x0))\n9 10 x0/9" `shouldBe` Right [ [Function "1" (const $ Right 1), Function "4" (const $ Right 4), fSin] , [Function "5" (const $ Right 5), Function "6" (const $ Right 6), simpleFunc "exp(sin(x0))" (Right . exp . sin)] , [Function "9" (const $ Right 9), Function "10" (const $ Right 10), simpleFunc "x0/9" $ Right . (/9)] ] it "of funcs2" $ parse parseExpression "1 2 4 sin(x0)+log(x1)\n0 3 5 x2*x1\n2 1 9 0" `shouldBe` Right [ [Function "1" (const $ Right 1), Function "2" (const $ Right 2), Function "4" (const $ Right 4), Function "sin(x0)+log(x1)" (\v -> Right $ sin (v Vec.! 0) + log (v Vec.! 1))] , [Function "0" (const $ Right 0), Function "3" (const $ Right 3), Function "5" (const $ Right 5), Function "x2*x1" (\v -> Right $ (v Vec.! 2) * (v Vec.! 1))] , [Function "2" (const $ Right 2), Function "1" (const $ Right 1), Function "9" (const $ Right 9), Function "0" (const $ Right 0)] ]
hrsrashid/nummet
tests/ParserSpec.hs
bsd-3-clause
5,553
0
26
1,476
2,104
1,039
1,065
111
1
module Main (main) where import System.Environment import CAN main :: IO () main = do args <- getArgs case args of "-h" : _ -> help "--help" : _ -> help ["--std", id, payload] -> do initCAN bus <- openBus 0 Standard sendMsg bus $ Msg (read id) (toPayload $ read payload) closeBus bus [id, payload] -> do initCAN bus <- openBus 0 Extended sendMsg bus $ Msg (read id) (toPayload $ read payload) closeBus bus _ -> help help :: IO () help = putStrLn $ unlines [ "" , "NAME" , " cansend - puts a message on a CAN bus" , "" , "SYNOPSIS" , " cansend [--std] id payload" , "" , "ARGUMENTS" , " --std Set to standard CAN with 500K. Default is extended CAN with 250K." , "" ]
tomahawkins/ecu
src/CANSend.hs
bsd-3-clause
778
0
16
247
255
129
126
32
5
-- Copyright (c) 1998 Chris Okasaki. -- See COPYRIGHT file for terms and conditions. module AssocDefaults where import Prelude hiding (null,map,lookup,foldr,foldl,foldr1,foldl1,filter) import Assoc import qualified Sequence as S -- import qualified ListSeq as L fromSeqUsingInsertSeq :: (AssocX m k,S.Sequence seq) => seq (k,a) -> m k a fromSeqUsingInsertSeq kvs = insertSeq kvs empty insertSeqUsingFoldr :: (AssocX m k,S.Sequence seq) => seq (k,a) -> m k a -> m k a insertSeqUsingFoldr kvs m = S.foldr (uncurry insert) m kvs unionSeqUsingReduce :: (AssocX m k,S.Sequence seq) => seq (m k a) -> m k a unionSeqUsingReduce ms = S.reducel union empty ms deleteSeqUsingFoldr :: (AssocX m k,S.Sequence seq) => seq k -> m k a -> m k a deleteSeqUsingFoldr ks m = S.foldr delete m ks countUsingMember :: AssocX m k => m k a -> k -> Int countUsingMember m k = if member m k then 1 else 0 lookupAllUsingLookupM :: (AssocX m k,S.Sequence seq) => m k a -> k -> seq a lookupAllUsingLookupM m k = case lookupM m k of Just x -> S.single x Nothing -> S.empty lookupWithDefaultUsingLookupM :: AssocX m k => a -> m k a -> k -> a lookupWithDefaultUsingLookupM d m k = case lookupM m k of Just x -> x Nothing -> d partitionUsingFilter :: AssocX m k => (a -> Bool) -> m k a -> (m k a,m k a) partitionUsingFilter f m = (filter f m, filter (not . f) m) elementsUsingFold :: (AssocX m k,S.Sequence seq) => m k a -> seq a elementsUsingFold = fold S.cons S.empty insertWithUsingLookupM :: FiniteMapX m k => (a -> a -> a) -> k -> a -> m k a -> m k a insertWithUsingLookupM f k x m = case lookupM m k of Nothing -> insert k x m Just y -> insert k (f x y) m fromSeqWithUsingInsertSeqWith :: (FiniteMapX m k,S.Sequence seq) => (a -> a -> a) -> seq (k,a) -> m k a fromSeqWithUsingInsertSeqWith f kvs = insertSeqWith f kvs empty fromSeqWithKeyUsingInsertSeqWithKey :: (FiniteMapX m k,S.Sequence seq) => (k -> a -> a -> a) -> seq (k,a) -> m k a fromSeqWithKeyUsingInsertSeqWithKey f kvs = insertSeqWithKey f kvs empty insertWithKeyUsingInsertWith :: FiniteMapX m k => (k -> a -> a -> a) -> k -> a -> m k a -> m k a insertWithKeyUsingInsertWith f k = insertWith (f k) k insertSeqWithUsingInsertWith :: (FiniteMapX m k,S.Sequence seq) => (a -> a -> a) -> seq (k,a) -> m k a -> m k a insertSeqWithUsingInsertWith f kvs m = S.foldr (uncurry (insertWith f)) m kvs insertSeqWithKeyUsingInsertWithKey :: (FiniteMapX m k,S.Sequence seq) => (k -> a -> a -> a) -> seq (k,a) -> m k a -> m k a insertSeqWithKeyUsingInsertWithKey f kvs m = S.foldr (uncurry (insertWithKey f)) m kvs unionSeqWithUsingReduce :: (FiniteMapX m k,S.Sequence seq) => (a -> a -> a) -> seq (m k a) -> m k a unionSeqWithUsingReduce f ms = S.reducel (unionWith f) empty ms unionSeqWithUsingFoldr :: (FiniteMapX m k,S.Sequence seq) => (a -> a -> a) -> seq (m k a) -> m k a unionSeqWithUsingFoldr f ms = S.foldr (unionWith f) empty ms toSeqUsingFoldWithKey :: (Assoc m k,S.Sequence seq) => m k a -> seq (k,a) toSeqUsingFoldWithKey = foldWithKey conspair S.empty where conspair k v kvs = S.cons (k,v) kvs keysUsingFoldWithKey :: (Assoc m k,S.Sequence seq) => m k a -> seq k keysUsingFoldWithKey = foldWithKey conskey S.empty where conskey k v ks = S.cons k ks unionWithUsingInsertWith :: FiniteMap m k => (a -> a -> a) -> m k a -> m k a -> m k a unionWithUsingInsertWith f m1 m2 = foldWithKey (insertWith f) m2 m1 unionWithKeyUsingInsertWithKey :: FiniteMap m k => (k -> a -> a -> a) -> m k a -> m k a -> m k a unionWithKeyUsingInsertWithKey f m1 m2 = foldWithKey (insertWithKey f) m2 m1 unionSeqWithKeyUsingReduce :: (FiniteMap m k,S.Sequence seq) => (k -> a -> a -> a) -> seq (m k a) -> m k a unionSeqWithKeyUsingReduce f ms = S.reducel (unionWithKey f) empty ms unionSeqWithKeyUsingFoldr :: (FiniteMap m k,S.Sequence seq) => (k -> a -> a -> a) -> seq (m k a) -> m k a unionSeqWithKeyUsingFoldr f ms = S.foldr (unionWithKey f) empty ms intersectWithUsingLookupM :: FiniteMap m k => (a -> b -> c) -> m k a -> m k b -> m k c intersectWithUsingLookupM f m1 m2 = foldWithKey ins empty m1 where ins k x m = case lookupM m2 k of Nothing -> m Just y -> insert k (f x y) m intersectWithKeyUsingLookupM :: FiniteMap m k => (k -> a -> b -> c) -> m k a -> m k b -> m k c intersectWithKeyUsingLookupM f m1 m2 = foldWithKey ins empty m1 where ins k x m = case lookupM m2 k of Nothing -> m Just y -> insert k (f k x y) m differenceUsingDelete :: FiniteMap m k => m k a -> m k b -> m k a differenceUsingDelete m1 m2 = foldWithKey del m1 m2 where del k _ m = delete k m subsetUsingSubsetEq :: FiniteMapX m k => m k a -> m k b -> Bool subsetUsingSubsetEq m1 m2 = subsetEq m1 m2 && size m1 < size m2 subsetEqUsingMember :: FiniteMap m k => m k a -> m k b -> Bool subsetEqUsingMember m1 m2 = foldWithKey mem True m1 where mem k _ b = member m2 k && b
OS2World/DEV-UTIL-HUGS
oldlib/AssocDefaults.hs
bsd-3-clause
5,161
0
12
1,330
2,286
1,134
1,152
99
2
{-# LANGUAGE BangPatterns #-} module Language.Hakaru.Tests.ImportanceSampler where import Data.Dynamic import Language.Hakaru.Distribution import Test.QuickCheck.Monadic testBeta = undefined mu a b = a / (a + b) var a b = a*b / ((sqr $ a + b) * (a + b + 1)) where sqr x = x * x
zaxtax/hakaru-old
Language/Hakaru/Tests/Distribution.hs
bsd-3-clause
284
0
10
55
113
64
49
9
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ViewPatterns #-} module Cgs ( main ) where import Cgs.Args (runParseArgsIO, CgsOptions(..)) import Control.Exception (assert) import Control.Monad ((<=<)) import Control.Monad.Identity (runIdentity) import Control.Monad.ListM (takeWhileM) import Control.Monad.State.Lazy (evalState, modify, gets) import Data.List (isPrefixOf) import Data.Tagged (untag) import Hoops.Lex (runLexer) import Hoops.Match import Hoops.SyntaxToken import Language.Cpp.Pretty (pretty) import System.Directory (getCurrentDirectory, createDirectoryIfMissing) import System.Exit (exitFailure) import System.FilePath ((</>)) import System.IO (stderr, hPutStrLn) import Text.Indent (indent, IndentMode(DropOldTabs), Tagged, CodeGen) import Text.Parsec (ParseError) import Transform.Expand (expand) import Transform.Extract (extract, ExtractOptions) import Transform.Flatten (flatten) import Transform.Merge (merge) import Transform.Nop (removeNopPairs, removeUnusedDefines) main :: IO () main = do mCgsOpts <- runParseArgsIO case mCgsOpts of Left err -> badArgs err Right cgsOpts -> do let getOpt f = runIdentity $ f cgsOpts tokss <- mapM (lexCode <=< readFile) $ getOpt cgsFiles let content = catMainContent tokss content' <- runExtract (cgsExtractOpts cgsOpts) content let cgsContent = cgs content' cgsContents = chunkStmts (cgsChunkSize cgsOpts) cgsContent tus = zipWith compileTranslationUnit [0 ..] cgsContents mapM_ (putStrLn . reindent . pretty expandHoops) tus badArgs :: ParseError -> IO () badArgs err = hPutStrLn stderr $ show err compileTranslationUnit :: Int -> [SyntaxToken Hoops] -> [SyntaxToken Hoops] compileTranslationUnit unitId tokens = prelude ++ tokens ++ prologue where code = either (const $ assert False undefined) id . runLexer codeChain = "code_chain_" ++ show unitId prelude = code $ unlines $ [ "#include \"cgs.h\"\n", "int " ++ codeChain ++ " () {\n" ] prologue = code $ unlines [ "return 0;", "}\n" ] data ChunkState = ChunkState { consumedStmts :: Int, braceBalance :: Int } chunkByM :: (Monad m) => (a -> m Bool) -> [a] -> m [[a]] chunkByM _ [] = return [] chunkByM p (x:xs) = do keep <- p x xss <- chunkByM p xs let xss' = case xss of ys : yss -> (x:ys) : yss [] -> [[x]] return $ if keep then xss' else [] : xss' chunkStmts :: Int -> [SyntaxToken Hoops] -> [[SyntaxToken Hoops]] chunkStmts chunkSize = flip evalState baseSt . chunkByM chunker where baseSt = ChunkState { consumedStmts = 0, braceBalance = 0 } chunker token = do balance <- gets braceBalance numConsumed <- gets consumedStmts placeInCurrChunk <- if balance == 0 && numConsumed >= chunkSize then do modify $ \st -> st { consumedStmts = 0 } return False else return True case token of Punctuation (unpunc -> ";") -> do modify $ \st -> st { consumedStmts = consumedStmts st + 1 } Punctuation (unpunc -> "{") -> do modify $ \st -> st { braceBalance = braceBalance st + 1 } Punctuation (unpunc -> "}") -> do modify $ \st -> st { braceBalance = braceBalance st - 1 } _ -> return () return placeInCurrChunk reindent :: String -> String reindent = untag . (indent DropOldTabs :: String -> Tagged CodeGen String) runExtract :: ExtractOptions -> [SyntaxToken Hoops] -> IO [SyntaxToken Hoops] runExtract opts toks = do cwd <- getCurrentDirectory let extractDir = cwd </> "extract" createDirectoryIfMissing True extractDir extract opts extractDir toks cgs :: [SyntaxToken Hoops] -> [SyntaxToken Hoops] cgs = id . iterateMaybe (fmap merge . removeNopPairs) . merge . flatten . removeUnusedDefines . iterateMaybe removeNopPairs . expand iterateMaybe :: (a -> Maybe a) -> a -> a iterateMaybe f x = case f x of Nothing -> x Just y -> iterateMaybe f y lexCode :: Code -> IO [SyntaxToken Hoops] lexCode code = case runLexer code of Left err -> print err >> exitFailure Right ts -> return ts catMainContent :: [[SyntaxToken Hoops]] -> [SyntaxToken Hoops] catMainContent = concatMap extractMainContent extractMainContent :: [SyntaxToken Hoops] -> [SyntaxToken Hoops] extractMainContent = let mainFunc = match "int main ($!args) {" codeChainSig = match "int $var ($!args) {" codeChainVar = isPrefixOf "code_chain_" codeChainFunc tokens = case tokens of (codeChainSig -> CapturesRest [Identifier (codeChainVar -> True)] rest) -> Rest rest _ -> NoRest dropBoringDecls = match $ concat [ "char string_buffer[256];", "float ff;", "int ii;", "long ll;", "HC_KEY key;", "float matrix[16];" ] go tokens = case extractBody tokens of (dropBoringDecls -> Rest rest) -> rest ts -> ts in \tokens -> case tokens of (mainFunc -> Rest rest) -> go rest (codeChainFunc -> Rest rest) -> go rest _ : rest -> extractMainContent rest [] -> [] extractBody :: [SyntaxToken Hoops] -> [SyntaxToken Hoops] extractBody = flip evalState (0 :: Int) . takeWhileM f where f token = case token of Punctuation (unpunc -> sym) -> case sym of "{" -> modify (+ 1) >> return True "}" -> modify (subtract 1) >> gets (>= 0) _ -> return True Keyword (unkw -> name) -> return $ case name of "return" -> False _ -> True Identifier name -> return $ not $ "code_chain_" `isPrefixOf` name _ -> return True
thomaseding/cgs
src/Cgs.hs
bsd-3-clause
6,013
0
19
1,740
1,900
982
918
150
7
{-# LANGUAGE FlexibleInstances #-} module Language.Haskell.GhcMod.Types where -- | Output style. data OutputStyle = LispStyle -- ^ S expression style. | PlainStyle -- ^ Plain textstyle. -- | The type for line separator. Historically, a Null string is used. newtype LineSeparator = LineSeparator String data Options = Options { outputStyle :: OutputStyle , hlintOpts :: [String] , ghcOpts :: [String] -- | If 'True', 'browse' also returns operators. , operators :: Bool -- | If 'True', 'browse' also returns types. , detailed :: Bool -- | If 'True', 'browse' will return fully qualified name , qualified :: Bool -- | Whether or not Template Haskell should be expanded. , expandSplice :: Bool -- | Line separator string. , lineSeparator :: LineSeparator -- | Package id of module , packageId :: Maybe String } -- | A default 'Options'. defaultOptions :: Options defaultOptions = Options { outputStyle = PlainStyle , hlintOpts = [] , ghcOpts = [] , operators = False , detailed = False , qualified = False , expandSplice = False , lineSeparator = LineSeparator "\0" , packageId = Nothing } ---------------------------------------------------------------- convert :: ToString a => Options -> a -> String convert Options{ outputStyle = LispStyle } = toLisp convert Options{ outputStyle = PlainStyle } = toPlain class ToString a where toLisp :: a -> String toPlain :: a -> String instance ToString [String] where toLisp = addNewLine . toSexp True toPlain = unlines instance ToString [((Int,Int,Int,Int),String)] where toLisp = addNewLine . toSexp False . map toS where toS x = "(" ++ tupToString x ++ ")" toPlain = unlines . map tupToString toSexp :: Bool -> [String] -> String toSexp False ss = "(" ++ unwords ss ++ ")" toSexp True ss = "(" ++ unwords (map quote ss) ++ ")" tupToString :: ((Int,Int,Int,Int),String) -> String tupToString ((a,b,c,d),s) = show a ++ " " ++ show b ++ " " ++ show c ++ " " ++ show d ++ " " ++ quote s quote :: String -> String quote x = "\"" ++ x ++ "\"" addNewLine :: String -> String addNewLine = (++ "\n") ---------------------------------------------------------------- -- | The environment where this library is used. data Cradle = Cradle { -- | The directory where this library is executed. cradleCurrentDir :: FilePath -- | The directory where a cabal file is found. , cradleCabalDir :: Maybe FilePath -- | The file name of the found cabal file. , cradleCabalFile :: Maybe FilePath -- | The package db options. ([\"-no-user-package-db\",\"-package-db\",\"\/foo\/bar\/i386-osx-ghc-7.6.3-packages.conf.d\"]) , cradlePackageDbOpts :: [GHCOption] , cradlePackages :: [Package] } deriving (Eq, Show) ---------------------------------------------------------------- -- | A single GHC command line option. type GHCOption = String -- | An include directory for modules. type IncludeDir = FilePath -- | A package name. type PackageBaseName = String -- | A package name and its ID. type Package = (PackageBaseName, Maybe String) -- | Haskell expression. type Expression = String -- | Module name. type ModuleString = String data CheckSpeed = Slow | Fast -- | Option information for GHC data CompilerOptions = CompilerOptions { ghcOptions :: [GHCOption] -- ^ Command line options , includeDirs :: [IncludeDir] -- ^ Include directories for modules , depPackages :: [Package] -- ^ Dependent package names } deriving (Eq, Show)
vikraman/ghc-mod
Language/Haskell/GhcMod/Types.hs
bsd-3-clause
3,690
0
13
882
764
451
313
71
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. module Duckling.Distance.CS.Tests ( tests ) where import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Distance.CS.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "CS Tests" [ makeCorpusTest [This Distance] corpus ]
rfranek/duckling
tests/Duckling/Distance/CS/Tests.hs
bsd-3-clause
588
0
9
94
77
49
28
10
1
import ConllReader import Control.Monad import Data.List.Split (splitOn) import Data.Maybe import System.Console.ParseArgs import System.Exit import System.IO import Text.Printf arg = [ Arg 0 Nothing Nothing (argDataRequired "corpus" ArgtypeString) "corpus in CoNLL format" ] main :: IO () main = do args <- parseArgsIO ArgsComplete arg case getArg args 0 of Nothing -> do usageError args "Missing input file." exitFailure Just f -> readCorpus f >>= putStr . showCorpus
jsnajder/conll-corpus
src/conll-filter.hs
bsd-3-clause
508
1
12
105
157
77
80
19
2
-- | Changes to alex's grammar: -- -- * All sets include their unicode equivalents by default -- -- * @%language MultiParamTypeClasses@ to allow language extensions in code fragments -- -- * The @%wrapper@ directive doesn\'t make sense any more and so is removed -- -- * Since it is parsed by TH, some fixities in code fragments may not work -- -- * TODO: %infixl 4 -, etc. to introduce fixities -- -- * TODO: allow the end user to supply an %encoding directive to get -- ascii, latin1, utf-8, ucs-2, or ucs-4 lexers -- -- * TODO: add a directive to allow "." to match "\n" -- -- * @\u{...}@ as an alias for @\x{...}@ (char escape) -- -- * optional braces on @\x{...}@, @\o{...}@ and @\u{....}@ -- -- * Haskell escape codes be used @\STX@ (these do not conflict with @\X@, or @\P@) -- -- * @\p{....}@ for unicode block, category and posix classes (set escape) -- -- * @\P{....}@ for the negation of the same (set escape) -- -- * @\s@, posix space shorthand (set escape) -- -- * @\w@, posix word shorthand (set escape) -- -- * @\d@, posix digit shorthand (set escape) -- -- * @\X@, grapheme recognition to recognize (an entire character with its modifiers) -- works like a unicode . except that it matches "\n" (regexp escape) -- -- * @\&@ is added as a Haskell-like synonym for () (regexp escape) module Text.Luthor.Parser ( P , MacroState , initialMacroState , scanner ) where import Data.Char import Data.CharSet (CharSet) import qualified Data.CharSet.Posix.Unicode as Posix import Data.Map (Map) import qualified Data.Map as Map import Text.ParserCombinators.Parsec.Char import Text.ParserCombinators.Parsec.Language import qualified Text.ParserCombinators.Parsec.Token as T import Control.Applicative import Language.Haskell.Exts.Extension as Haskell import Language.Haskell.Exts.Parser as Haskell import Language.Haskell.Meta.Syntax.Translate as Meta data Code = Code String TH.Exp data MacroState = MacroState { setMacroDefs :: Map String CharSet , regExpMacroDefs :: Map String RegExp , haskellExtensions :: [Extension] } defaultMacroState = MacroState { setMacroDefs = , regExpMacroDefs = Map/empty , haskellExtensions = [ QuasiQuotes, TemplateHaskell ] } type P = CharParser MacroState -- | lexical scanner scanner :: P (Scanner Code String) scanner = do whitespace many directive many macroDef name <- optional identifier operator ":-" rules <- many rule return $ Scanner name rules -- directives directive :: P () directive = do operator "%" directiveBody <?> "directive" directiveBody :: P () directiveBody = languageDirectiveBody <?> "directive body" languageDirectiveBody :: P () languageDirectiveBody = do try $ identifier "language" ext <- languageExtension modify $ \s -> s { haskellExtensions = ext : haskellExtensions s } languageExtension :: P Haskell.Extension languageExtension = do st <- getParserState ident <- identifier case [ x | (x,"") <- reads ident ] of (x:_) -> return x [] -> do setParserState st fail $ "Unknown language extension: " ++ ident <?> "language extension" -- macro definitions macroDef :: P () macroDef = setMacroDef <|> regExpMacroDef <?> "macro definition" setMacroDef :: P () setMacroDef = do m <- setMacroId operator '=' s <- set modify (\st-> st { setMacroDefs = insert m s (setMacroDefs st) } regExpMacroDef :: P () regExpMacroDef = do m <- regExpMacro operator '=' r <- regExp modify (\st-> st { regExpMacroDefs = insert m r (regExpMacroDefs st) } -- set parsing set :: P CharSet set = set0 `sepBy` lexeme (char "#") <?> "set" set0 :: P CharSet set0 = complementedSet0 <|> bracketedSet -- '[' <|> setMacro -- $... <|> dot -- . <|> (char '\\' >> setEscapeCode) -- \p{...} \P{...} <|> rangeSet -- a \u{1234} xor :: Bool -> Bool -> Bool xor True False = True xor False True = True xor _ _ = False setEscape = do char '\\' setEscapeCode -- uses look-ahead on '\\' setEscapeCode :: P CharSet setEscapeCode = do code <- oneOf "pP" st <- getParserState clazz <- ident <|> braces $ noneOf "}" <?> "character class" let (careted, cs) = case clazz of '^' : rest -> (True, rest) rest -> (False, rest) case lookupCategoryCharSet cs `mplus` lookupBlockCharSet cs `mplus` lookupPosixUnicodeCharSet cs of Just c -> return $ if careted `xor` code == 'P' then complement c else c Nothing -> do setParserState st fail $ "Unknown character class: " ++ clazz <|> do char "d"; return Posix.digit <|> do char "s"; return Posix.space <|> do char "w"; return Posix.word <|> do ch <- charEscape rangeSetK ch <?> "set escape code" dot :: P CharSet dot = do char '.' return $ complement (CharSet.singleton '\n') rangeSet :: P CharSet rangeSet = do lower <- character rangeSet0 lower rangeSetK :: Char -> P CharSet rangeSetK lower = do r <- optional $ do lexeme (char '-') character case r of Just upper -> return $ range lower upper _ -> return $ singleton lower setMacroId :: P String setMacroId = do char '$' bracedIdent <?> "character set macro" setMacro :: P CharSet setMacro = do st <- getParserState macro <- setMacroId smacs <- gets setMacroDefs case lookup macro smacs of Just s -> return s _ -> do setParserState st fail $ "Unknown set macro: " ++ macro bracketedSet :: P CharSet bracketedSet = do brackets $ do caret <- optional (lexeme (char '^')) ss <- many set let s = mconcat ss case caret of Just _ -> complement s _ -> s complementedSet0 :: P CharSet complementedSet0 = do lexeme (char '~') -- allow this to be part of a larger operator complement <$> set0 nonspecialCharSet :: CharSet nonspecialCharSet = CharSet.delete '%' (graphicCharSet \\ specialCharSet) -- Rule parsing startCodes = P [String] startCodes = angles (startCode `sepBy` comma) <?> "start codes" startCode :: P String startCode = identifier <|> lexeme (char '0') >> return "0" tokenDef :: P [Rule Code String] tokenDef = do cs <- startCodes rule cs <|> do t <- token rule [] tokens :: P [Token] tokens = braces (many token) <|> fmap return token data LeftContext = LeftNone | LeftSet CharSet data Token = Token LeftContext RegExp RightContext Action token :: P Token token = do l <- optional pre b <- regExp r <- optional post rh <- rhs return (Token l b r rh) alt :: P RegExp alt = foldr1 (:%%) <$> many1 term term :: P RegExp term = do re <- regExp0 reps <- optional rep case reps of Just f -> f re Nothing -> re regExp :: P RegExp regExp = alt `sepBy1` lexeme (char '|') rep :: P (RegExp -> RegExp) rep = lexeme (char '*') >> return Star <|> lexeme (char '+') >> return Plus <|> lexeme (char '?') >> return Ques <|> braces $ do d <- decimal opt <- optional (lexeme (char ',') >> optional decimal) return $ repeat_rng d opt where repeat_rng :: Int -> Maybe (Maybe Int) -> RegExp -> RegExp repeat_rng n (Nothing) re = foldr (:%%) Eps (replicate n re) repeat_rng n (Just Nothing) re = foldr (:%%) (Star re) (replicate n re) repeat_rng n (Just (Just m)) re = intl :%% rst where intl = repeat_rng n Nothing re rst = foldr (\re re' -> Ques (re :%% re')) Eps (replicate (m-n) re) regExp0 :: P RegExp regExp0 = fromMaybe Eps <$> parens (optional regExp) <|> foldr (\x y -> x :%% Ch (singleton y)) Eps <$> stringLiteral <|> regExpMacro <|> regExpEscape -- have to try this before set below consumes '\\' <|> Ch <$> set -- thought: this could be expressed as a built-in regexp @X instead regExpEscape :: P RegExp regExpEscape = do char '\\' regExpEscapeCode regExpEscapeCode = regExpGraphemeEscapeCode <|> regExpEmptyEscapeCode <|> Ch <$> setEscapeCode <?> "regexp escape code" regExpGraphemeEscapeCode :: RegExp regExpGraphemeEscapeCode = do lexeme (char 'X') return $ Ch (complement mark) :%% Star (Ch mark) regExpEmptyEscapeCode = do lexeme (char '&') return Eps customParseMode :: [Haskell.Extension] -> Haskell.ParseMode customParseMode exts = Haskell.defaultParseMode { parseFileNae = "" , extensions = exts , ignoreLanguagePragmas = False , fixities = baseFixities } data Code = Code String TH.Exp -- TODO: more gracefully handle nested '{'s -- TODO: fix haskell-src-exts to give tighter location reporting code :: P Code code = do st <- getParserState fragment <- braces $ many $ noneOf "}" exts <- get haskellExtensions result <- Haskell.parseExpWithMode (customParseMode exts) fragment case result of Haskell.ParseOk a -> return $ Code fragment (Meta.toExp a) Haskell.ParseFailed _loc reason -> do setParserState st fail reason rule :: [startCodes] -> P (Rule Code startCodes) rule startCodes = Rule `fmap` optional pre `ap` regExp `ap` (fromMaybe NoPost <$> optional post) `ap` ruleMaybeCode <?> "rule" pre :: P CharSet pre = try $ do p <- optional set lexeme (char '^') case p of Just x -> return x Nothing -> return newLineSet post :: P (Post Code RegExp) post = do lexeme (char '$') return $ PostRegExp (Ch newLineSet) <|> do lexeme (char '/') postRegExp <|> postCode ruleMaybeCode :: P (Maybe Code) ruleMaybeCode = Just <$> code <|> do lexeme (char ';') return Nothing -- | character lexeme -- Unfortunately, we have to replicate much of this from Text.ParserCombinators.Parsec.Token because the parsers there do not export enough of the interim combinators used character :: P Char character = charEscape <|> charLetter <?> "character" charLetter :: P Char charLetter = satisfy (\x -> x `member` (graphicCharSet \\ specialCharSet)) charEscape :: P Char charEscape = char '\\' >> charEscapeCode charEscapeCode :: P Char charEscapeCode = charEsc <|> charNum <|> charAscii <|> charControl <|> charQuote <?> "character escape code" charQuote :: P Char charQuote = satisfy (`CharSet.member` (specialCharSet `union` Category.separator)) charControl :: P Char charControl = do char '^' code <- upper return $! toEnum (fromEnum code - fromEnum 'A') charNum :: P Char charNum = do code <- decimal -- cannot be braced, or it will conflict with \{ <|> do char 'o'; maybeBraces $ number 8 octDigit <|> do oneOf "xu"; maybeBraces $ number 16 hexDigit return $! toEnum code foldDigits :: Int -> String -> Int foldDigits base digits = foldl (\x d -> base * x + toInteger (digitToInt d)) 0 number :: Int -> P Char -> P Int number base baseDigit = do digits <- many1 baseDigit return $! foldDigits base digits charEsc :: P Char charEsc = choice $ map parseEsc escMap where parseEsc (c,code) = do char c return code charAscii :: CharParser st Char charAscii = choice (map parseAscii asciiMap) where parseAscii (asc,code) = try $ do string asc; return code escMap :: [(Char,Char)] escMap = zip ("abfnrtv\\\"\'") ("\a\b\f\n\r\t\v\\\"\'") asciiMap :: [(String,Char)] asciiMap = zip (ascii3codes ++ ascii2codes) (ascii3 ++ ascii2) ascii2codes = ["BS","HT","LF","VT","FF","CR","SO","SI","EM", "FS","GS","RS","US","SP"] ascii3codes = ["NUL","SOH","STX","ETX","EOT","ENQ","ACK","BEL", "DLE","DC1","DC2","DC3","DC4","NAK","SYN","ETB", "CAN","SUB","ESC","DEL"] ascii2 = ['\BS','\HT','\LF','\VT','\FF','\CR','\SO','\SI', '\EM','\FS','\GS','\RS','\US','\SP'] ascii3 = ['\NUL','\SOH','\STX','\ETX','\EOT','\ENQ','\ACK', '\BEL','\DLE','\DC1','\DC2','\DC3','\DC4','\NAK', '\SYN','\ETB','\CAN','\SUB','\ESC','\DEL'] -- * Utility 'Charset's newlineCharSet :: CharSet newlineCharSet = CharSet.singleton '\n' specialCharSet :: CharSet specialCharSet = CharSet.fromList ".;,$|*+?#~-{}()[]^/" spaceCharSet :: CharSet spaceCharSet = Posix.space printableCharSet :: CharSet printableCharSet = Posix.print graphicCharSet :: CharSet graphicCharSet = printableCharSet \\ spaceCharSet -- * "Free" TokenParser parsers language = makeTokenParser haskellStyle identifier = T.identifier language reserved = T.reserved language stringLiteral = T.stringLiteral language natural = T.natural language integer = T.integer language lexeme = T.lexeme language whiteSpace = T.whiteSpace language parens = T.parens language braces = T.braces language angles = T.angles language -- * Useful combinators bracedIdentifier :: P String bracedIdentifier = identifier <|> braces identifier <?> "braced identifier"
ekmett/luthor
Text/Luthor/Parser.hs
bsd-3-clause
13,475
221
17
3,572
2,324
1,481
843
-1
-1
module SpatulaStart where import Rumpus start :: Start start entityID = do chan <- traverseM (use (wldComponents . myPdPatch . at entityID)) $ \patch -> do pd <- view wlsPd toDyn <$> makeReceiveChan pd (local patch "freq") return chan
lukexi/rumpus
util/DevScenes/scenes-old/spatula/SpatulaStart.hs
bsd-3-clause
260
0
15
64
95
46
49
8
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.Semigroup ((<>)) import qualified Data.Text as Text import qualified Data.Text.IO as Text import Options.Applicative import System.Environment (getEnvironment) import qualified Web.JWT as JWT import qualified Data.Time.Clock.POSIX as Clock import AccessControl import JwtAuth data Config = Config { configJwtSecret :: Maybe JWT.Signer , configExpiresSeconds :: Maybe Integer , configWhitelist :: [AuthPath] } type EnvironmentConfig = [(String, String)] main :: IO () main = do env <- getEnvironment config <- execParser (configInfo env) now <- Clock.getPOSIXTime let joseHeader = JWT.JOSEHeader { JWT.typ = Just "JWT" , JWT.cty = Nothing , JWT.alg = Just JWT.HS256 , JWT.kid = Nothing } let access = IcepeakClaim (configWhitelist config) claims = addIcepeakClaim access $ JWT.JWTClaimsSet { JWT.iss = Nothing , JWT.sub = Nothing , JWT.aud = Nothing , JWT.exp = fmap (\secs -> realToFrac secs + now) (configExpiresSeconds config) >>= JWT.numericDate , JWT.nbf = Nothing , JWT.iat = Nothing , JWT.jti = Nothing , JWT.unregisteredClaims = mempty } token = case configJwtSecret config of Nothing -> JWT.encodeUnsigned claims joseHeader Just key -> JWT.encodeSigned key joseHeader claims Text.putStrLn token configParser :: EnvironmentConfig -> Parser Config configParser environment = Config <$> optional ( secretOption (long "jwt-secret" <> metavar "JWT_SECRET" <> environ "JWT_SECRET" <> short 's' <> help "Secret used for signing the JWT, defaults to the value of the JWT_SECRET environment variable if present. If no secret is passed, JWT tokens are not signed.")) <*> optional( option auto (long "expires" <> short 'e' <> metavar "EXPIRES_SECONDS" <> help "Generate a token that expires in EXPIRES_SECONDS seconds from now.")) <*> many (option authPathReader (long "path" <> short 'p' <> metavar "PATH:MODES" <> help "Adds the PATH to the whitelist, allowing the access modes MODES. MODES can be 'r' (read), 'w' (write) or 'rw' (read/write). This option may be used more than once." )) where environ var = foldMap value (lookup var environment) secretOption m = JWT.hmacSecret . Text.pack <$> strOption m configInfo :: EnvironmentConfig -> ParserInfo Config configInfo environment = info parser description where parser = helper <*> configParser environment description = fullDesc <> header "Icepeak Token Generator - Generates and signs JSON Web Tokens for authentication and authorization in Icepeak." authPathReader :: ReadM AuthPath authPathReader = eitherReader (go . Text.pack) where go input = let (pathtxt, modetxt) = Text.breakOn ":" input modeEither | modetxt == ":r" = Right [ModeRead] | modetxt == ":w" = Right [ModeWrite] | modetxt == ":rw" = Right [ModeRead, ModeWrite] | otherwise = Left $ "Invalid mode: " ++ Text.unpack modetxt pathComponents = filter (not . Text.null) $ Text.splitOn "/" pathtxt in AuthPath pathComponents <$> modeEither
channable/icepeak
server/app/IcepeakTokenGen/Main.hs
bsd-3-clause
3,623
0
18
1,130
834
433
401
74
2
-- | Provides definitions of associated Legendre functions used in spherical harmonic models. module Math.SphericalHarmonics.AssociatedLegendre ( associatedLegendreFunction , schmidtSemiNormalizedAssociatedLegendreFunction ) where import Data.Poly (VPoly, eval, deriv) import Data.Poly.Orthogonal (legendre) import Data.Euclidean (Field, WrappedFractional(..)) -- definition from http://www.mathworks.com/help/matlab/ref/legendre.html#f89-998354 -- | Computes the associated Legendre function of degree 'n' and order 'm'. -- Note that the resulting function may not be a polynomial, as when `m` is odd it involves a fractional power of `x`. -- As used in the geodesy and magnetics literature, these functions do not include the Condon-Shortley phase. associatedLegendreFunction :: (Floating a, Ord a) => Int -- ^ Degree 'n' of the desired associated Legendre function. -> Int -- ^ Order 'm' of the desired associated Legendre function. -> a -> a associatedLegendreFunction n m = f where f x = nonPolyTerm x * unwrapFractional (eval p' (WrapFractional x)) nonPolyTerm x = (1 - x * x) ** (fromIntegral m / 2) p' = iterate deriv p !! m p :: (Eq t, Field t) => VPoly t p = legendre !! n -- definition from http://www.mathworks.com/help/matlab/ref/legendre.html#f89-998354 -- | Computes the Schmidt semi-normalized associated Legendre function of degree 'n' and order 'm'. -- As used in the geodesy and magnetics literature, these functions do not include the Condon-Shortley phase. schmidtSemiNormalizedAssociatedLegendreFunction :: (Floating a, Ord a) => Int -- ^ Degree 'n' of the desired function. -> Int -- ^ Order 'm' of the desired function. -> a -> a schmidtSemiNormalizedAssociatedLegendreFunction n 0 = associatedLegendreFunction n 0 schmidtSemiNormalizedAssociatedLegendreFunction n m = (* factor) . associatedLegendreFunction n m where factor = (sqrt $ 2 / rawFactor) rawFactor = fromIntegral $ rawFactor' (fromIntegral n) (fromIntegral m) rawFactor' :: Integer -> Integer -> Integer rawFactor' n m = product . map (max 1) $ enumFromTo (n - m + 1) (n + m)
dmcclean/igrf
src/Math/SphericalHarmonics/AssociatedLegendre.hs
bsd-3-clause
2,251
0
12
489
403
220
183
25
1
module Main where import Data.Sequence as S import Data.List import Data.Foldable import System.IO import Prelude as P import qualified Data.Text as T import Control.Lens import Types import MeshGenerator import Linear import FractalSurface import MarchingCubes sphere :: V3 Double -> Double sphere v = norm v - 1.0 boxAxis :: Double -> V3 Double -> Double boxAxis lim v | maxAxis v > lim && minAxis v < (-lim) = max (maxAxis v - lim) (-(minAxis v + lim)) boxAxis lim v | minAxis v < (-lim) = (-(minAxis v + lim)) boxAxis lim v | maxAxis v > lim = maxAxis v - lim boxAxis lim v | otherwise = max (maxAxis v - lim) (-(minAxis v + lim)) minAxis :: V3 Double -> Double minAxis v = min (min (v ^._x) (v ^._y)) (v ^._z) maxAxis :: V3 Double -> Double maxAxis v = max (max (v ^._x) (v ^._y)) (v ^._z) mandelBulb8 :: V3 Double -> Double --mandelBulb8 = mandelBulb 7 3.0 (V3 (-0.20) (-0.80) (-0.4)) mandelBulb8 = mandelBulb 7 9.0 (V3 (-0.9) (0.1) (-0.2)) --many saturn discs --mandelBulb8 = mandelBulb 15 2.0 (V3 0.7 (-0.7) 0.45) --chalice main :: IO () main = do --meshToObj testSquare "testSquare.obj" --print testSquare --print $ squareGrid 3 --print $ radialGrid 4 let maxTriNum = 65534 {- let meshListRadial = splitMeshAt maxTriNum (radialGrid 250) :: [Mesh Double] print $ P.length meshListRadial print $ "Radial number of vertices: " ++ show (P.map meshVertLength meshListRadial) print $ "Radial number of triangles: " ++ show (P.map meshTrisLength meshListRadial) P.mapM_ (\(index, mesh) -> meshToObj mesh ("radialGrid250_" ++ show index ++ ".obj")) (P.zip [0, 1..] meshListRadial) let meshListSquare = splitMeshAt maxTriNum (squareGrid 500) :: [Mesh Double] print $ P.length meshListSquare print $ "Square number of vertices: " ++ show (P.map meshVertLength meshListSquare) print $ "Square number of triangles: " ++ show (P.map meshTrisLength meshListSquare) P.mapM_ (\(index, mesh) -> meshToObj mesh ("squareGrid500_" ++ show index ++ ".obj")) (P.zip [0, 1..] meshListSquare) -} let minNum = -2.0 let maxNum = 2.0 let minCorner = V3 minNum minNum minNum :: V3 Double let maxCorner = V3 maxNum maxNum maxNum :: V3 Double --let sphereIndepMesh = marchingCubesGrid sphere 0.0 200 minCorner maxCorner --let sphereIndepMesh = marchingCubesGrid sphere 0.0 50 minCorner maxCorner --let sphereMesh = independentTriangleMeshToMeshUnCompressed sphereIndepMesh --let meshListSphere = splitMeshAt maxTriNum sphereMesh :: [Mesh Double] --P.mapM_ (\(index, mesh) -> meshToObj mesh ("sphereMesh_" ++ show index ++ ".obj")) (P.zip [0, 1..] meshListSphere) --meshToObj sphereMesh "sphereMesh.obj" --let boxIndepMesh = marchingCubesGrid (boxAxis 0.8) 0.0 50 minCorner maxCorner --let boxMesh = independentTriangleMeshToMeshUnCompressed boxIndepMesh --meshToObj boxMesh "boxMesh.obj" let mandelIndepMesh = marchingCubesGrid mandelBulb8 0.0 200 minCorner maxCorner let mandelMesh = independentTriangleMeshToMeshUnCompressed mandelIndepMesh meshToObj mandelMesh "mandel8Mesh.obj"
zobot/MeshGenerator
src/Main.hs
bsd-3-clause
3,113
0
11
590
590
306
284
36
1
----------------------------------------------------------------------------- -- | -- Module : TestSuite.Puzzles.Euler185 -- Copyright : (c) Levent Erkok -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- -- Test suite for Data.SBV.Examples.Puzzles.Euler185 ----------------------------------------------------------------------------- module TestSuite.Puzzles.Euler185(tests) where import Data.SBV.Examples.Puzzles.Euler185 import Utils.SBVTestFramework -- Test suite tests :: TestTree tests = testGroup "Puzzles.Euler185" [ goldenVsStringShow "euler185" (allSat euler185) ]
josefs/sbv
SBVTestSuite/TestSuite/Puzzles/Euler185.hs
bsd-3-clause
640
0
9
88
65
43
22
7
1
module FizzBuzzKata.Day2 (fizzbuzz) where fizzbuzz :: [Int] -> [String] fizzbuzz [] = [] fizzbuzz (n:ns) | isFizz n && isBuzz n = "fizz!buzz!" : fizzbuzz ns | isFizz n = "fizz!" : fizzbuzz ns | isBuzz n = "buzz!" : fizzbuzz ns | otherwise = show n : fizzbuzz ns where isFizz :: Int -> Bool isFizz num = num `isDivisible` 3 || elem '3' (show num) isBuzz :: Int -> Bool isBuzz num = num `isDivisible` 5 || elem '5' (show num) isDivisible :: Int -> Int -> Bool isDivisible num m = num `mod` m == 0
Alex-Diez/haskell-tdd-kata
old-katas/src/FizzBuzzKata/Day2.hs
bsd-3-clause
648
0
10
252
244
122
122
15
1
module Wholemeal where fun1 :: [Integer] -> Integer fun1 = product . map (\x -> x - 2) . filter even fun2 :: Integer -> Integer fun2 1 = 0 fun2 n | even n = n + fun2 (n `div` 2) | otherwise = fun2 (3 * n + 1) fun3 :: Integer -> Integer fun3 = sum . filter even . takeWhile (>1) . iterate (\x -> if even x then x `div` 2 else 3 * x + 1) data Tree a = Leaf | Node Integer (Tree a) a (Tree a) --foldTree :: [a] -> Tree a
richard12511/bobs-orders
app/Wholemeal.hs
bsd-3-clause
466
0
11
149
224
119
105
12
2
{-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} module Finance.Exchange.OrderBook ( OrderBook -- , BookedOrder (..) , MatchedOrder (..) , emptyBook , bookOrder , drain ) where import Data.Heap as H import Finance.Exchange.Types class MarketPrice offerPrice where -- | Adjust order price based on available offer. Returns Nothing if offer price can not be matched. matchPrice :: offerPrice -> OrderPrice (Market offerPrice) -> Maybe (OrderPrice (Market offerPrice)) -- | Price asked by seller newtype AskPrice market = AskPrice (OrderPrice market) type instance Market (AskPrice market) = market deriving instance Show (OrderPrice market) => Show (AskPrice market) deriving instance (Eq (OrderPrice market)) => Eq (AskPrice market) -- | Ask price is ordered from lower to higher value with market price on the bottom (indicating that market will always match first) instance (Ord (Money market)) => Ord (AskPrice market) where (AskPrice Market) `compare` (AskPrice Market) = EQ (AskPrice Market) `compare` _ = LT _ `compare` (AskPrice Market) = GT (AskPrice (Limit a)) `compare` (AskPrice (Limit b)) = a `compare` b -- | Matching ask price against order will return ask price if it lower or Nothing if ask price is higher than limit. instance (Ord (Money market)) => MarketPrice (AskPrice market) where (AskPrice Market) `matchPrice` Market = Just Market (AskPrice ask) `matchPrice` Market = Just ask (AskPrice Market) `matchPrice` lim = Just lim (AskPrice (Limit ask)) `matchPrice` (Limit lim) = if ask <= lim then Just (Limit ask) else Nothing -- | Price offered by buyer newtype BidPrice market = BidPrice (OrderPrice market) type instance Market (BidPrice market) = market deriving instance Show (OrderPrice market) => Show (BidPrice market) deriving instance (Eq (OrderPrice market)) => Eq (BidPrice market) -- | Big is ordered from lower to higher value with market price on the top (indicating that market will always match first) instance (Ord (Money market)) => Ord (BidPrice market) where (BidPrice Market) `compare` (BidPrice Market) = EQ (BidPrice Market) `compare` _ = GT _ `compare` (BidPrice Market) = LT (BidPrice (Limit a)) `compare` (BidPrice (Limit b)) = a `compare` b -- | Matching bid price against order will return bid price if it higher or Nothing if bid price is lower than limit. instance (Ord (Money market)) => MarketPrice (BidPrice market) where -- | Calculate execution price if favor to seller (BidPrice Market) `matchPrice` Market = Just Market (BidPrice bid) `matchPrice` Market = Just bid (BidPrice Market) `matchPrice` lim = Just lim (BidPrice (Limit bid)) `matchPrice` (Limit lim) = if bid >= lim then Just (Limit bid) else Nothing -- | Booked order parametrized by price (can be either buing or selling order depending on price type) data BookedOrder price = BookedOrder { _bookedId :: OrderId (Market price) , _bookedAmount :: Amount (Market price) , _bookedPrice :: price } deriving instance (Eq (OrderId (Market price)), Eq (Amount (Market price)), Eq price) => Eq (BookedOrder price) deriving instance (Show (OrderId (Market price)), Show (Amount (Market price)), Show price) => Show (BookedOrder price) instance (Eq (BookedOrder (AskPrice market)), Ord (OrderId market), Ord (Money market)) => Ord (BookedOrder (AskPrice market)) where a `compare` b = case _bookedPrice a `compare` _bookedPrice b of EQ -> (_bookedId a) `compare` (_bookedId b) other -> other instance (Eq (BookedOrder (BidPrice market)), Ord (OrderId market), Ord (Money market)) => Ord (BookedOrder (BidPrice market)) where -- price comparison reversed to place order with highest bid price on a top of priority queue a `compare` b = case _bookedPrice b `compare` _bookedPrice a of EQ -> (_bookedId a) `compare` (_bookedId b) other -> other data MatchedOrder market = MatchedOrder { _matchedId1 :: OrderId market , _matchedId2 :: OrderId market , _matchedAmount :: Amount market , _matchedPrice :: OrderPrice market } deriving instance (Show (OrderId market), Show (Amount market), Show (OrderPrice market)) => Show (MatchedOrder market) data OrderBook market = OrderBook { _asking :: Heap (BookedOrder (AskPrice market)) -- TODO: rename to _bying/_selling , _bidding :: Heap (BookedOrder (BidPrice market)) } emptyBook :: OrderBook market emptyBook = OrderBook { _asking = H.empty , _bidding = H.empty } deriving instance (Show (OrderId market), Show (Money market), Show (Amount market), Show (InstrumentId market)) => Show (OrderBook market) -- | Provide generic interface for booking bid and ask ordres -- TODO: needs better name -- основное назначение: -- 1. разобрать deal book на orders offers -- 2. конвертировать OrderPrice в OrderPriceOf book (чтобы добавлять его в нужную кучу) -- 3. собрать deal book из orders offers (вот это пока не очень получается) class ( -- FuckingProlog (OrderPriceOf book) (OfferPriceOf book) ~ book -- , DealBookOf (OrderPriceOf book) ~ book -- , Market (OrderPriceOf book) ~ Market book -- , Market (OfferPriceOf book) ~ Market book Market orderPrice ~ Market book , Market offerPrice ~ Market book --, DealBookOf (orderPrice) ~ book ) => DealBook book orderPrice offerPrice | book -> orderPrice, book -> offerPrice, orderPrice -> book, offerPrice -> book where -- | Order price (Bid for buyind Ask for selling) -- type OrderPriceOf book :: * -- | Offer price (Ask for buyind Bid for selling) -- type OfferPriceOf book :: * -- | Construct order book from offers and orders halves (depending on order type can be either buy/sell or sell/buy) -- эта штука не тайпчекается на ghc 7.10 потому что параметры не определяют тип буки -- хотя он нам и не нужен, нам market нужен -- короче на фундепах работает, но надо будет потом переделать этот ёбаный ужас orderBook :: Heap (BookedOrder orderPrice) -> Heap (BookedOrder offerPrice) -> OrderBook (Market book) -- | Get offers from book (sell offers when buying or buy offers when selling) offers :: book -> Heap (BookedOrder offerPrice) -- | Get orders from book (buy orderd when buying of sell orders when selling) orders :: book -> Heap (BookedOrder orderPrice) -- | Wrap order price to Bid or Ask price depending on deal dealPrice :: OrderPrice (Market book) -> orderPrice type family DealBookOf orderPrice :: * type family FuckingProlog orderPrice offerPrice :: * newtype Buying market = Buying { unBuying :: OrderBook market } type instance Market (Buying market) = market instance DealBook (Buying market) (BidPrice market) (AskPrice market) where -- type OrderPriceOf (Buying market) = BidPrice market -- type OfferPriceOf (Buying market) = AskPrice market orderBook bidding asking = OrderBook { _asking = asking, _bidding = bidding } offers = _asking . unBuying orders = _bidding . unBuying dealPrice = BidPrice type instance DealBookOf (BidPrice market) = Buying market type instance FuckingProlog (BidPrice market) (AskPrice market) = Buying market newtype Selling market = Selling { unSelling :: OrderBook market } type instance Market (Selling market) = market instance DealBook (Selling market) (AskPrice market) (BidPrice market) where -- type OrderPriceOf (Selling market) = AskPrice market -- type OfferPriceOf (Selling market) = BidPrice market orderBook asking bidding = OrderBook { _asking = asking, _bidding = bidding } offers = _bidding . unSelling orders = _asking . unSelling dealPrice = AskPrice type instance DealBookOf (AskPrice market) = Selling market type instance FuckingProlog (AskPrice market) (BidPrice market) = Selling market bookOrder :: (Num (Amount market), Ord (Amount market), Ord (Money market), Ord (OrderId market)) => OrderId market -- replace with order tag (market agnostic depends on upstream engine) -> BuyOrSell -> OrderPrice market -> Amount market -> OrderBook market -> ([MatchedOrder market], OrderBook market) bookOrder orderId buyOrSell price amount = case buyOrSell of Buy -> bookOrder' orderId price amount . Buying Sell -> bookOrder' orderId price amount . Selling bookOrder' :: forall book orderPrice offerPrice . ( DealBook book orderPrice offerPrice , Num (Amount (Market book)) , Ord (Amount (Market book)) --, Ord (BookedOrder (OrderPriceOf book)) --, Ord (BookedOrder (OfferPriceOf book)) --, MarketPrice (OfferPriceOf book) , Ord (BookedOrder (orderPrice)) , Ord (BookedOrder (offerPrice)) , MarketPrice (offerPrice) ) => OrderId (Market book) -> OrderPrice (Market book) -> Amount (Market book) -> book -> ([MatchedOrder (Market book)], OrderBook (Market book)) bookOrder' orderId price amount book = go [] amount (offers book) where --go :: [MatchedOrder (Market (OfferPriceOf book))] -- -> Amount (Market (OfferPriceOf book)) -- -> Heap (BookedOrder (OfferPriceOf book)) -- -> ([MatchedOrder (Market (OfferPriceOf book))], OrderBook (Market book)) go matchedOrders 0 xs = (matchedOrders, orderBook (orders book) xs) go matchedOrders remain xs = case tryGetPrice price xs of Just (execPrice, offer, otherOffers) -> let matchedOrder matchedamount = MatchedOrder { _matchedId1 = orderId , _matchedId2 = _bookedId offer , _matchedAmount = matchedamount , _matchedPrice = execPrice } orderAmount = _bookedAmount offer in case remain - orderAmount of shortage | shortage > 0 -> go (matchedOrder orderAmount : matchedOrders) shortage otherOffers | otherwise -> ( matchedOrder remain : matchedOrders , orderBook (orders book) (H.insert offer { _bookedAmount = -shortage } otherOffers) ) Nothing -> let newOrder = BookedOrder { _bookedId = orderId , _bookedAmount = remain , _bookedPrice = dealPrice price } in (matchedOrders, orderBook (H.insert newOrder $ orders book) xs) tryGetPrice :: ( Ord (BookedOrder offerPrice) , MarketPrice offerPrice ) => OrderPrice (Market offerPrice) -> Heap (BookedOrder offerPrice) -> Maybe (OrderPrice (Market offerPrice), BookedOrder offerPrice, Heap (BookedOrder offerPrice)) tryGetPrice lim xs = do (offer, heap) <- H.uncons xs execPrice <- matchPrice (_bookedPrice offer) lim return (execPrice, offer, heap) drain :: (Num (Amount market), Ord (Amount market), Ord (Money market), Ord (OrderId market)) => OrderId market -- replace with order tag (market agnostic depends on upstream engine) -> BuyOrSell -> OrderPrice market -> OrderBook market -> ([MatchedOrder market], OrderBook market) drain orderId buyOrSell price = case buyOrSell of Buy -> drain' orderId price . Buying Sell -> drain' orderId price . Selling drain' :: ( DealBook book orderPrice offerPrice --, Ord (BookedOrder (OrderPriceOf book)) --, Ord (BookedOrder (OfferPriceOf book)) --, MarketPrice (OfferPriceOf book ) , Ord (BookedOrder (orderPrice)) , Ord (BookedOrder (offerPrice)) , MarketPrice (offerPrice ) ) => OrderId (Market book) -> OrderPrice (Market book) -> book -> ([MatchedOrder (Market book)], OrderBook (Market book)) drain' orderId price book = go [] (offers book) where go matchedOrders xs = case tryGetPrice price xs of Just (execPrice, offer, otherOffers) -> let matchedOrder = MatchedOrder { _matchedId1 = orderId , _matchedId2 = _bookedId offer , _matchedAmount = _bookedAmount offer , _matchedPrice = execPrice } in go (matchedOrder : matchedOrders) otherOffers Nothing -> (matchedOrders, orderBook (orders book) xs)
schernichkin/exchange
src/Finance/Exchange/OrderBook.hs
bsd-3-clause
13,633
23
17
3,778
3,117
1,673
1,444
-1
-1
{-# LANGUAGE TemplateHaskell #-} module RRTTest (tests) where import Test.Framework import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.Framework.TH (testGroupGenerator) import Test.QuickCheck.Property ((==>)) import Data.MetricSpace import Data.RRT tests :: Test tests = $(testGroupGenerator) prop_num_streams_eq_num_nodes stream = length tree == length stream where config = Config (controlEdgeProp (+)) [0] distance tree = maybeSearch config stream types = (stream :: [(Integer, [Integer])]) prop_failed_means_empty_tree stream = null tree where config = Config (const $ const Nothing) [0] distance tree = search config stream types = (stream :: [(Integer, [Integer])])
jdmarble/rrt
test/RRTTest.hs
bsd-3-clause
749
0
10
139
222
129
93
18
1
{-# LANGUAGE OverloadedStrings #-} module TW.CodeGen.Flow ( makeFileName, makeModule ) where import TW.Ast import TW.BuiltIn import TW.JsonRepr import Data.Monoid import System.FilePath import qualified Data.List as L import qualified Data.Text as T makeFileName :: ModuleName -> FilePath makeFileName (ModuleName parts) = (L.foldl' (</>) "" $ map T.unpack parts) ++ ".js" makeModule :: Module -> T.Text makeModule m = T.unlines [ "/* @flow */" , "// This file was auto generated by typed-wire. Do not modify by hand" , "// Module Name: " <> printModuleName (m_name m) <> "" , "" , T.intercalate "\n" (map makeImport $ m_imports m) , "" , T.intercalate "\n" (map makeTypeDef $ m_typeDefs m) , "" ] makeImport :: ModuleName -> T.Text makeImport m = "import " <> printModuleName m <> ";" makeTypeDef :: TypeDef -> T.Text makeTypeDef td = case td of TypeDefEnum ed -> makeEnumDef ed TypeDefStruct sd -> makeStructDef sd makeStructDef :: StructDef -> T.Text makeStructDef sd = T.unlines [ "export type " <> makeTypeName (sd_name sd) (sd_args sd) <> " =" , " {| " <> T.intercalate "\n , " (map makeStructField $ sd_fields sd) , " |}" , "" ] makeStructField :: StructField -> T.Text makeStructField sf = (unFieldName $ sf_name sf) <> " : " <> (makeType $ sf_type sf) makeEnumDef :: EnumDef -> T.Text makeEnumDef ed = T.unlines [ "export type " <> makeTypeName (ed_name ed) (ed_args ed) , " = " <> T.intercalate "\n | " (map makeEnumChoice $ ed_choices ed) , "" ] makeEnumChoice :: EnumChoice -> T.Text makeEnumChoice ec = let constr = unChoiceName $ ec_name ec tag = camelTo2 '_' $ T.unpack constr fieldVal = case ec_arg ec of Nothing -> "true" Just arg -> makeType arg in "{|" <> T.pack tag <> ": " <> fieldVal <> "|}" makeTypeName :: TypeName -> [TypeVar] -> T.Text makeTypeName tname targs = let types = T.intercalate ", " (map unTypeVar targs) in unTypeName tname <> (if null targs then types else ("<" <> types <> ">")) makeType :: Type -> T.Text makeType t = case isBuiltIn t of Nothing -> case t of TyVar (TypeVar x) -> x TyCon qt args -> let ty = makeQualTypeName qt in case args of [] -> ty _ -> ty <> "<" <> T.intercalate ", " (map makeType args) <> ">" Just (bi, tvars) | bi == tyString -> "string" | bi == tyInt -> "number" | bi == tyBool -> "boolean" | bi == tyFloat -> "number" | bi == tyDateTime -> "Date" | bi == tyTime -> "Date" | bi == tyDate -> "Date" | bi == tyMaybe -> "(? " <> T.intercalate " " (map makeType tvars) <> ")" | bi == tyList -> "Array<" <> T.intercalate " " (map makeType tvars) <> ">" | bi == tyBytes -> "UInt8Array" -- TODO: CHECK | otherwise -> error $ "Flow: Unimplemented built in type: " ++ show t makeQualTypeName :: QualTypeName -> T.Text makeQualTypeName qtn = case unModuleName $ qtn_module qtn of [] -> ty _ -> printModuleName (qtn_module qtn) <> "." <> ty where ty = unTypeName $ qtn_type qtn
agrafix/typed-wire
src/TW/CodeGen/Flow.hs
mit
3,368
0
20
1,046
1,095
548
547
93
4
square :: (Num a) => a -> a square n = n * n isDivisor :: (Integral a) => a -> a -> Bool isDivisor a b = b `mod` a == 0 findDivisor :: (Integral a) => a -> a -> a findDivisor divisor n | square divisor > n = n | isDivisor divisor n = divisor | otherwise = findDivisor (divisor + 1) n smallestDivisor :: (Integral a) => a -> a smallestDivisor = findDivisor 2 prime :: (Integral a) => a -> Bool prime n = n == smallestDivisor n no = prime 4 yes = prime 3
slideclick/sicp-examples
chapters/1/1.2.6/smallest-divisor.hs
mit
486
0
9
135
228
116
112
15
1
factorial :: Integer -> Integer factorial 0 = 1 factorial n = n * factorial (n - 1)
Sergey-Pravdyukov/Homeworks
term4/hw1/1/1.hs
mit
83
0
8
17
40
20
20
3
1
{-# LANGUAGE ViewPatterns #-} -- | Specification of Pos.Chain.Lrc.OBFT (which is basically a pure -- version of 'Pos.DB.Lrc.OBFT'). module Test.Pos.Chain.Lrc.ObftRoundRobinSpec ( spec ) where import Universum hiding (sort) import Data.List.NonEmpty (sort, (!!)) import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) import Test.QuickCheck (Property, (===)) import Pos.Chain.Lrc (getEpochSlotLeaderScheduleObftPure, getSlotLeaderObftPure) import Pos.Core (EpochIndex, SlotCount, SlotId, flattenEpochOrSlot) import Test.Pos.Chain.Lrc.StakeAndHolder (StakeAndHolder (..)) import Test.Pos.Core.Arbitrary (genPositiveSlotCount) spec :: Spec spec = do describe "Pos.Chain.Lrc.OBFT" $ do describe "Round-robin" $ do modifyMaxSuccess (const 10000) $ do prop description_rrListLength (rrListLength <$> genPositiveSlotCount) prop description_rrCorrectSlotLeader (rrCorrectSlotLeader <$> genPositiveSlotCount) where description_rrListLength = "the amount of stakeholders is the same as the number of slots in an epoch" description_rrCorrectSlotLeader = "the correct slot leader is chosen given any epoch and slot" rrListLength :: SlotCount -> EpochIndex -> StakeAndHolder -> Property rrListLength epochSlotCount epochIndex (getNoStake -> (_, stakes)) = do length (getEpochSlotLeaderScheduleObftPure epochIndex epochSlotCount stakeholders) === fromIntegral epochSlotCount where stakeholders = case nonEmpty (map fst stakes) of Just s -> s Nothing -> error "rrListLength: Empty list of stakeholders" rrCorrectSlotLeader :: SlotCount -> SlotId -> StakeAndHolder -> Property rrCorrectSlotLeader epochSlotCount slotId (getNoStake -> (_, stakes)) = do actualSlotLeader === expectedSlotLeader where stakeholders = case nonEmpty (map fst stakes) of Just s -> s Nothing -> error "rrCorrectSlotLeader: Empty list of stakeholders" flatSlotId = flattenEpochOrSlot epochSlotCount slotId expectedSlotLeaderIndex = (fromIntegral flatSlotId :: Int) `mod` (length stakeholders) expectedSlotLeader = (sort stakeholders) !! expectedSlotLeaderIndex actualSlotLeader = getSlotLeaderObftPure slotId epochSlotCount stakeholders
input-output-hk/pos-haskell-prototype
chain/test/Test/Pos/Chain/Lrc/ObftRoundRobinSpec.hs
mit
2,466
0
18
573
491
271
220
52
2
-- -- -- ----------------- -- Exercise 4.23. ----------------- -- -- -- module E'4'23 where import Test.QuickCheck ( quickCheck ) -- Subsection 4.5 (extended definition) ... regions' :: Integer -> Integer regions' n | n < 0 = 0 | n == 0 = 1 | otherwise = regions' ( n - 1 ) + n -- Subsection 4.5 ... sumFun :: (Integer -> Integer) -> Integer -> Integer sumFun f n | n == 0 = f 0 | otherwise = sumFun f ( n - 1 ) + f n -- ... regionsFun :: Integer -> Integer regionsFun n = n regions :: Integer -> Integer regions n | n < 0 = 0 | otherwise = ( sumFun regionsFun n ) + 1 -- Other solution: regions2 :: Integer -> Integer regions2 n | n < 0 = 0 | otherwise = ( sumFun id n ) + 1 prop_regions :: Integer -> Bool prop_regions n = ( regions n ) == ( regions' n ) -- GHCi> quickCheck prop_regions -- +++ OK, passed 100 tests.
pascal-knodel/haskell-craft
_/links/E'4'23.hs
mit
924
0
9
283
309
160
149
25
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} -- Module : Khan.CLI.Ansible -- Copyright : (c) 2013 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Khan.CLI.Ansible ( commands -- * Convenience exports for the Image CLI , Ansible (..) , playbook ) where import Control.Monad (mplus) import qualified Data.Aeson.Encode.Pretty as Aeson import qualified Data.ByteString.Lazy.Char8 as LBS import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Text as Text import qualified Data.Text.Format as Format import qualified Data.Text.Lazy as LText import Data.Time.Clock.POSIX import qualified Filesystem as FS import qualified Filesystem.Path.CurrentOS as Path import Khan.Internal import Khan.Model.Ansible import qualified Khan.Model.EC2.Instance as Instance import qualified Khan.Model.Key as Key import qualified Khan.Model.Tag as Tag import Khan.Prelude import Network.AWS import Network.AWS.EC2 hiding (Failed, Image) import qualified System.Posix.Files as Posix import System.Process (callCommand) data Inventory = Inventory { iEnv :: !Env , iSilent :: !Bool , iList :: !Bool , iHost :: Maybe Text } inventoryParser :: EnvMap -> Parser Inventory inventoryParser env = Inventory <$> envOption env <*> switchOption "silent" False "Don't output inventory results to stdout." <*> switchOption "list" True "List." <*> optional (textOption "host" mempty "Host.") instance Options Inventory where validate Inventory{..} = check iEnv "--env must be specified." data Ansible = Ansible { aEnv :: !Env , aRKeys :: !RKeysBucket , aKey :: Maybe FilePath , aBin :: Maybe Text , aRetain :: !Int , aForce :: !Bool , aArgs :: [String] } ansibleParser :: EnvMap -> Parser Ansible ansibleParser env = Ansible <$> envOption env <*> rKeysOption env <*> keyOption <*> optional (textOption "bin" (short 'b') "Ansible binary name to exec.") <*> readOption "retention" "SECONDS" (value 360) "Number of seconds to cache inventory results for." <*> switchOption "force" False "Force update of any previously cached results." <*> argsOption str (action "file") "Pass through arguments to ansible." instance Options Ansible where validate Ansible{..} = do check aEnv "--env must be specified." check aArgs "Pass ansible options through using the -- delimiter.\n\ \Usage: khan ansible [KHAN OPTIONS] -- [ANSIBLE OPTIONS]." instance Naming Ansible where names Ansible{..} = unversioned "base" aEnv commands :: EnvMap -> Mod CommandFields Command commands env = mconcat [ command "ansible" ansible (ansibleParser env) "Run 'ansible' supplying it with khan_* facts and inventory." , command "playbook" playbook (ansibleParser env) "Run 'ansible-playbook' supplying it with khan_* facts and inventory." , command "inventory" inventory (inventoryParser env) "Output ansible compatible inventory in JSON format." ] inventory :: Common -> Inventory -> AWS () inventory Common{..} Inventory{..} = do j <- Aeson.encodePretty . JS <$> maybe list (const $ return Map.empty) iHost i <- inventoryPath cCache iEnv debug "Writing inventory to {}" [i] liftIO $ LBS.writeFile (Path.encodeString i) (j <> "\n") debug_ "Writing inventory to stdout" unless iSilent . liftIO $ LBS.putStrLn j where list = localhost . foldl' hosts Map.empty <$> instances instances = Instance.findAll [] [Tag.filter Tag.env [_env iEnv]] localhost = Map.insert "localhost" (Set.singleton $ Localhost cRegion) hosts m i@RunningInstancesItemType{..} = case Instance.address cVPN i of Nothing -> m Just (fqdn, addr) -> fromMaybe m $ do t@Tags{..} <- hush (Tag.parse riitTagSet) let n@Names{..} = names t host = Host addr tagDomain n cRegion update k = Map.insertWith (<>) k (Set.singleton host) return $! foldl' (flip update) m [ roleName , envName , regionToText cRegion , "khan" , tagDomain , fqdn ] playbook :: Common -> Ansible -> AWS () playbook c a@Ansible{..} = ansible c $ a { aBin = aBin `mplus` Just "ansible-playbook" , aArgs = overrides a aArgs } ansible :: Common -> Ansible -> AWS () ansible c@Common{..} a@Ansible{..} = do liftEitherT (which bin) k <- maybe (Key.path aRKeys a cLKeys) return aKey i <- inventoryPath cCache aEnv let script = i <.> "sh" p <- (|| aForce) <$> exceeds i when p $ do log "Limit of {}s exceeded for {}, refreshing..." [P aRetain, B i] inventory c $ Inventory aEnv True True Nothing debug "Writing inventory script to {}" [B script] liftIO . FS.writeTextFile script . LText.toStrict $ Format.format "#!/usr/bin/env bash\nset -e\nexec cat {}\n" [i] debug "Setting +rwx on {}" [B script] liftIO $ Posix.setFileMode (Path.encodeString script) Posix.ownerModes let cmd = unwords ["ANSIBLE_FORCE_COLOR=1", unwords (bin : args k script)] log "{}" [cmd] liftEitherT . sync $ callCommand cmd where bin = Text.unpack (fromMaybe "ansible" aBin) args k s = aArgs +$+ [ ("-i", Path.encodeString s) , ("--private-key", Path.encodeString k) ] exceeds i = liftIO $ do p <- FS.isFile i if not p then return True else do s <- Posix.getFileStatus (Path.encodeString i) ts <- getPOSIXTime return $ ts - Posix.modificationTimeHiRes s > fromIntegral aRetain
zinfra/khan
khan-cli/src/Khan/CLI/Ansible.hs
mpl-2.0
6,636
0
19
1,974
1,625
846
779
155
2
{-# LANGUAGE NoImplicitPrelude #-} module Stack.Options.DockerParser where import Data.Char import Data.List (intercalate) import qualified Data.Text as T import Distribution.Version (anyVersion) import Options.Applicative import Options.Applicative.Args import Options.Applicative.Builder.Extra import Stack.Constants import Stack.Docker import qualified Stack.Docker as Docker import Stack.Prelude import Stack.Options.Utils import Stack.Types.Version import Stack.Types.Docker -- | Options parser configuration for Docker. dockerOptsParser :: Bool -> Parser DockerOptsMonoid dockerOptsParser hide0 = DockerOptsMonoid <$> pure (Any False) <*> firstBoolFlags dockerCmdName "using a Docker container. --docker implies 'system-ghc: true'" hide <*> fmap First ((Just . DockerMonoidRepo) <$> option str (long (dockerOptName dockerRepoArgName) <> hide <> metavar "NAME" <> help "Docker repository name") <|> (Just . DockerMonoidImage) <$> option str (long (dockerOptName dockerImageArgName) <> hide <> metavar "IMAGE" <> help "Exact Docker image ID (overrides docker-repo)") <|> pure Nothing) <*> firstBoolFlags (dockerOptName dockerRegistryLoginArgName) "registry requires login" hide <*> firstStrOption (long (dockerOptName dockerRegistryUsernameArgName) <> hide <> metavar "USERNAME" <> help "Docker registry username") <*> firstStrOption (long (dockerOptName dockerRegistryPasswordArgName) <> hide <> metavar "PASSWORD" <> help "Docker registry password") <*> firstBoolFlags (dockerOptName dockerAutoPullArgName) "automatic pulling latest version of image" hide <*> firstBoolFlags (dockerOptName dockerDetachArgName) "running a detached Docker container" hide <*> firstBoolFlags (dockerOptName dockerPersistArgName) "not deleting container after it exits" hide <*> firstStrOption (long (dockerOptName dockerContainerNameArgName) <> hide <> metavar "NAME" <> help "Docker container name") <*> argsOption (long (dockerOptName dockerRunArgsArgName) <> hide <> value [] <> metavar "'ARG1 [ARG2 ...]'" <> help "Additional options to pass to 'docker run'") <*> many (option auto (long (dockerOptName dockerMountArgName) <> hide <> metavar "(PATH | HOST-PATH:CONTAINER-PATH)" <> completer dirCompleter <> help ("Mount volumes from host in container " ++ "(may specify multiple times)"))) <*> many (option str (long (dockerOptName dockerEnvArgName) <> hide <> metavar "NAME=VALUE" <> help ("Set environment variable in container " ++ "(may specify multiple times)"))) <*> optionalFirst (absFileOption (long (dockerOptName dockerDatabasePathArgName) <> hide <> metavar "PATH" <> help "Location of image usage tracking database")) <*> optionalFirst (option (eitherReader' parseDockerStackExe) (let specialOpts = [ dockerStackExeDownloadVal , dockerStackExeHostVal , dockerStackExeImageVal ] in long(dockerOptName dockerStackExeArgName) <> hide <> metavar (intercalate "|" (specialOpts ++ ["PATH"])) <> completer (listCompleter specialOpts <> fileCompleter) <> help (concat [ "Location of " , stackProgName , " executable used in container" ]))) <*> firstBoolFlags (dockerOptName dockerSetUserArgName) "setting user in container to match host" hide <*> pure (IntersectingVersionRange anyVersion) where dockerOptName optName = dockerCmdName ++ "-" ++ T.unpack optName firstStrOption = optionalFirst . option str hide = hideMods hide0 -- | Parser for docker cleanup arguments. dockerCleanupOptsParser :: Parser Docker.CleanupOpts dockerCleanupOptsParser = Docker.CleanupOpts <$> (flag' Docker.CleanupInteractive (short 'i' <> long "interactive" <> help "Show cleanup plan in editor and allow changes (default)") <|> flag' Docker.CleanupImmediate (short 'y' <> long "immediate" <> help "Immediately execute cleanup plan") <|> flag' Docker.CleanupDryRun (short 'n' <> long "dry-run" <> help "Display cleanup plan but do not execute") <|> pure Docker.CleanupInteractive) <*> opt (Just 14) "known-images" "LAST-USED" <*> opt Nothing "unknown-images" "CREATED" <*> opt (Just 0) "dangling-images" "CREATED" <*> opt Nothing "stopped-containers" "CREATED" <*> opt Nothing "running-containers" "CREATED" where opt def' name mv = fmap Just (option auto (long name <> metavar (mv ++ "-DAYS-AGO") <> help ("Remove " ++ toDescr name ++ " " ++ map toLower (toDescr mv) ++ " N days ago" ++ case def' of Just n -> " (default " ++ show n ++ ")" Nothing -> ""))) <|> flag' Nothing (long ("no-" ++ name) <> help ("Do not remove " ++ toDescr name ++ case def' of Just _ -> "" Nothing -> " (default)")) <|> pure def' toDescr = map (\c -> if c == '-' then ' ' else c)
MichielDerhaeg/stack
src/Stack/Options/DockerParser.hs
bsd-3-clause
6,868
0
33
2,922
1,241
613
628
140
4
{-# LANGUAGE Haskell2010, OverloadedStrings #-} {-# LINE 1 "Network/Wai/EventSource.hs" #-} {-| A WAI adapter to the HTML5 Server-Sent Events API. -} module Network.Wai.EventSource ( ServerEvent(..), eventSourceAppChan, eventSourceAppIO ) where import Data.Function (fix) import Control.Concurrent.Chan (Chan, dupChan, readChan) import Control.Monad.IO.Class (liftIO) import Network.HTTP.Types (status200, hContentType) import Network.Wai (Application, responseStream) import Network.Wai.EventSource.EventStream -- | Make a new WAI EventSource application reading events from -- the given channel. eventSourceAppChan :: Chan ServerEvent -> Application eventSourceAppChan chan req sendResponse = do chan' <- liftIO $ dupChan chan eventSourceAppIO (readChan chan') req sendResponse -- | Make a new WAI EventSource application reading events from -- the given IO action. eventSourceAppIO :: IO ServerEvent -> Application eventSourceAppIO src _ sendResponse = sendResponse $ responseStream status200 [(hContentType, "text/event-stream")] $ \sendChunk flush -> fix $ \loop -> do se <- src case eventToBuilder se of Nothing -> return () Just b -> sendChunk b >> flush >> loop
phischu/fragnix
tests/packages/scotty/Network.Wai.EventSource.hs
bsd-3-clause
1,337
0
16
317
266
148
118
26
2
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ro-RO"> <title>Requester</title> <maps> <homeID>requester</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/requester/src/main/javahelp/help_ro_RO/helpset_ro_RO.hs
apache-2.0
960
77
66
155
404
205
199
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Mode.Interactive -- License : GPL-2 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Collection of 'Mode's for working with Haskell. module Yi.Mode.Interactive where import Control.Concurrent (threadDelay) import Lens.Micro.Platform (use, (%~), (.=)) import Data.Monoid ((<>)) import qualified Data.Text as T (Text) import Yi.Buffer import Yi.Core (sendToProcess, startSubprocess, withSyntax) import Yi.Editor import Yi.History (historyFinishGen, historyMoveGen, historyStartGen) import Yi.Keymap (YiM, topKeymapA) import Yi.Keymap.Keys (Key (KEnter, KHome), char, choice, meta, spec, (<||), (?>>!)) import Yi.Lexer.Alex (Tok) import Yi.Lexer.Compilation (Token) import qualified Yi.Mode.Compilation as Compilation (mode) import Yi.Mode.Common (lookupMode) import Yi.Monad (gets) import qualified Yi.Rope as R (YiString, fromText, toString, toText) import qualified Yi.Syntax.OnlineTree as OnlineTree (Tree) import Yi.Utils (io) mode :: Mode (OnlineTree.Tree (Tok Token)) mode = Compilation.mode { modeApplies = modeNeverApplies, modeName = "interactive", modeKeymap = topKeymapA %~ (<||) (choice [spec KHome ?>>! moveToSol, spec KEnter ?>>! do eof <- withCurrentBuffer atLastLine if eof then feedCommand else withSyntax modeFollow, meta (char 'p') ?>>! interactHistoryMove 1, meta (char 'n') ?>>! interactHistoryMove (-1) ]) } interactId :: T.Text interactId = "Interact" -- | TODO: we're just converting back and forth here, 'historyMoveGen' -- and friends need to migrate to YiString it seems. interactHistoryMove :: Int -> EditorM () interactHistoryMove delta = historyMoveGen interactId delta (R.toText <$> withCurrentBuffer getInput) >>= inp where inp = withCurrentBuffer . setInput . R.fromText interactHistoryFinish :: EditorM () interactHistoryFinish = historyFinishGen interactId (R.toText <$> withCurrentBuffer getInput) interactHistoryStart :: EditorM () interactHistoryStart = historyStartGen interactId getInputRegion :: BufferM Region getInputRegion = do mo <- getMarkB (Just "StdOUT") p <- pointAt botB q <- use $ markPointA mo return $ mkRegion p q getInput :: BufferM R.YiString getInput = readRegionB =<< getInputRegion setInput :: R.YiString -> BufferM () setInput val = flip replaceRegionB val =<< getInputRegion -- | Open a new buffer for interaction with a process. spawnProcess :: String -> [String] -> YiM BufferRef spawnProcess = spawnProcessMode mode -- | open a new buffer for interaction with a process, using any -- interactive-derived mode spawnProcessMode :: Mode syntax -> FilePath -> [String] -> YiM BufferRef spawnProcessMode interMode cmd args = do b <- startSubprocess cmd args (const $ return ()) withEditor interactHistoryStart mode' <- lookupMode $ AnyMode interMode withCurrentBuffer $ do m1 <- getMarkB (Just "StdERR") m2 <- getMarkB (Just "StdOUT") modifyMarkB m1 (\v -> v {markGravity = Backward}) modifyMarkB m2 (\v -> v {markGravity = Backward}) setAnyMode mode' return b -- | Send the type command to the process feedCommand :: YiM () feedCommand = do b <- gets currentBuffer withEditor interactHistoryFinish cmd <- withCurrentBuffer $ do botB newlineB me <- getMarkB (Just "StdERR") mo <- getMarkB (Just "StdOUT") p <- pointB q <- use $ markPointA mo cmd <- readRegionB $ mkRegion p q markPointA me .= p markPointA mo .= p return $ R.toString cmd withEditor interactHistoryStart sendToProcess b cmd -- | Send command, recieve reply queryReply :: BufferRef -> String -> YiM R.YiString queryReply buf cmd = do start <- withGivenBuffer buf (botB >> pointB) sendToProcess buf (cmd <> "\n") io $ threadDelay 50000 -- Hack to let ghci finish writing its output. withGivenBuffer buf $ do botB moveToSol leftB -- There is probably a much better way to do this moving around, but it works end <- pointB result <- readRegionB (mkRegion start end) botB return result
siddhanathan/yi
yi-core/src/Yi/Mode/Interactive.hs
gpl-2.0
4,603
0
16
1,210
1,169
612
557
99
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} -- | Versions for packages. module Stack.Types.Version (Version ,Cabal.VersionRange -- TODO in the future should have a newtype wrapper ,MajorVersion (..) ,getMajorVersion ,fromMajorVersion ,parseMajorVersionFromString ,versionParser ,parseVersion ,parseVersionFromString ,versionString ,versionText ,toCabalVersion ,fromCabalVersion ,mkVersion ,versionRangeText ,withinRange) where import Control.Applicative import Control.DeepSeq import Control.Monad.Catch import Data.Aeson.Extended import Data.Attoparsec.ByteString.Char8 import Data.Binary (Binary) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Data import Data.Hashable import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Text (Text) import qualified Data.Text as T import Data.Vector.Binary () import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V import Data.Word import Distribution.Text (disp) import qualified Distribution.Version as Cabal import GHC.Generics import Language.Haskell.TH import Language.Haskell.TH.Syntax import Prelude -- Fix warning: Word in Prelude from base-4.8. import Text.PrettyPrint (render) -- | A parse fail. data VersionParseFail = VersionParseFail ByteString | NotAMajorVersion Version deriving (Typeable) instance Exception VersionParseFail instance Show VersionParseFail where show (VersionParseFail bs) = "Invalid version: " ++ show bs show (NotAMajorVersion v) = concat [ "Not a major version: " , versionString v , ", expecting exactly two numbers (e.g. 7.10)" ] -- | A package version. newtype Version = Version {unVersion :: Vector Word} deriving (Eq,Ord,Typeable,Data,Generic,Binary,NFData) -- | The first two components of a version. data MajorVersion = MajorVersion !Word !Word deriving (Typeable, Eq, Ord) instance Show MajorVersion where show (MajorVersion x y) = concat [show x, ".", show y] instance ToJSON MajorVersion where toJSON = toJSON . fromMajorVersion -- | Parse major version from @String@ parseMajorVersionFromString :: MonadThrow m => String -> m MajorVersion parseMajorVersionFromString s = do Version v <- parseVersionFromString s if V.length v == 2 then return $ getMajorVersion (Version v) else throwM $ NotAMajorVersion (Version v) instance FromJSON MajorVersion where parseJSON = withText "MajorVersion" $ either (fail . show) return . parseMajorVersionFromString . T.unpack instance FromJSON a => FromJSON (Map MajorVersion a) where parseJSON val = do m <- parseJSON val fmap Map.fromList $ mapM go $ Map.toList m where go (k, v) = do k' <- either (fail . show) return $ parseMajorVersionFromString k return (k', v) -- | Returns the first two components, defaulting to 0 if not present getMajorVersion :: Version -> MajorVersion getMajorVersion (Version v) = case V.length v of 0 -> MajorVersion 0 0 1 -> MajorVersion (V.head v) 0 _ -> MajorVersion (V.head v) (v V.! 1) -- | Convert a two-component version into a @Version@ fromMajorVersion :: MajorVersion -> Version fromMajorVersion (MajorVersion x y) = Version $ V.fromList [x, y] instance Hashable Version where hashWithSalt i = hashWithSalt i . V.toList . unVersion instance Lift Version where lift (Version n) = appE (conE 'Version) (appE (varE 'V.fromList) (listE (map (litE . IntegerL . fromIntegral) (V.toList n)))) instance Show Version where show (Version v) = intercalate "." (map show (V.toList v)) instance ToJSON Version where toJSON = toJSON . versionText instance FromJSON Version where parseJSON j = do s <- parseJSON j case parseVersionFromString s of Nothing -> fail ("Couldn't parse package version: " ++ s) Just ver -> return ver -- | Attoparsec parser for a package version from bytestring. versionParser :: Parser Version versionParser = do ls <- ((:) <$> num <*> many num') let !v = V.fromList ls return (Version v) where num = decimal num' = point *> num point = satisfy (== '.') -- | Convenient way to parse a package version from a bytestring. parseVersion :: MonadThrow m => ByteString -> m Version parseVersion x = go x where go = either (const (throwM (VersionParseFail x))) return . parseOnly (versionParser <* endOfInput) -- | Migration function. parseVersionFromString :: MonadThrow m => String -> m Version parseVersionFromString = parseVersion . S8.pack -- | Get a string representation of a package version. versionString :: Version -> String versionString (Version v) = intercalate "." (map show (V.toList v)) -- | Get a string representation of a package version. versionText :: Version -> Text versionText (Version v) = T.intercalate "." (map (T.pack . show) (V.toList v)) -- | Convert to a Cabal version. toCabalVersion :: Version -> Cabal.Version toCabalVersion (Version v) = Cabal.Version (map fromIntegral (V.toList v)) [] -- | Convert from a Cabal version. fromCabalVersion :: Cabal.Version -> Version fromCabalVersion (Cabal.Version vs _) = let !v = V.fromList (map fromIntegral vs) in Version v -- | Make a package version. mkVersion :: String -> Q Exp mkVersion s = case parseVersionFromString s of Nothing -> error ("Invalid package version: " ++ show s) Just pn -> [|pn|] -- | Display a version range versionRangeText :: Cabal.VersionRange -> Text versionRangeText = T.pack . render . disp -- | Check if a version is within a version range. withinRange :: Version -> Cabal.VersionRange -> Bool withinRange v r = toCabalVersion v `Cabal.withinRange` r
CRogers/stack
src/Stack/Types/Version.hs
bsd-3-clause
6,337
0
15
1,521
1,638
867
771
163
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module Stack.FileWatch ( fileWatch , printExceptionStderr ) where import Blaze.ByteString.Builder (toLazyByteString, copyByteString) import Blaze.ByteString.Builder.Char.Utf8 (fromShow) import Control.Concurrent.Async (race_) import Control.Concurrent.STM import Control.Exception (Exception) import Control.Exception.Enclosed (tryAny) import Control.Monad (forever, unless) import qualified Data.ByteString.Lazy as L import qualified Data.Map.Strict as Map import Data.Monoid ((<>)) import Data.Set (Set) import qualified Data.Set as Set import Data.String (fromString) import Data.Traversable (forM) import Path import System.FSNotify import System.IO (stderr) -- | Print an exception to stderr printExceptionStderr :: Exception e => e -> IO () printExceptionStderr e = L.hPut stderr $ toLazyByteString $ fromShow e <> copyByteString "\n" -- | Run an action, watching for file changes -- -- The action provided takes a callback that is used to set the files to be -- watched. When any of those files are changed, we rerun the action again. fileWatch :: ((Set (Path Abs File) -> IO ()) -> IO ()) -> IO () fileWatch inner = withManager $ \manager -> do dirtyVar <- newTVarIO True watchVar <- newTVarIO Map.empty let onChange = atomically $ writeTVar dirtyVar True setWatched :: Set (Path Abs File) -> IO () setWatched files = do watch0 <- readTVarIO watchVar let actions = Map.mergeWithKey keepListening stopListening startListening watch0 newDirs watch1 <- forM (Map.toList actions) $ \(k, mmv) -> do mv <- mmv return $ case mv of Nothing -> Map.empty Just v -> Map.singleton k v atomically $ writeTVar watchVar $ Map.unions watch1 where newDirs = Map.fromList $ map (, ()) $ Set.toList $ Set.map parent files keepListening _dir listen () = Just $ return $ Just listen stopListening = Map.map $ \f -> do () <- f return Nothing startListening = Map.mapWithKey $ \dir () -> do let dir' = fromString $ toFilePath dir listen <- watchDir manager dir' (const True) (const onChange) return $ Just listen let watchInput = do line <- getLine unless (line == "quit") $ do case line of "help" -> do putStrLn "" putStrLn "help: display this help" putStrLn "quit: exit" putStrLn "build: force a rebuild" putStrLn "watched: display watched directories" "build" -> onChange "watched" -> do watch <- readTVarIO watchVar mapM_ (putStrLn . toFilePath) (Map.keys watch) _ -> putStrLn $ "Unknown command: " ++ show line watchInput race_ watchInput $ forever $ do atomically $ do dirty <- readTVar dirtyVar check dirty writeTVar dirtyVar False eres <- tryAny $ inner setWatched case eres of Left e -> printExceptionStderr e Right () -> putStrLn "Success! Waiting for next file change." putStrLn "Type help for available commands"
CRogers/stack
src/Stack/FileWatch.hs
bsd-3-clause
3,671
0
25
1,314
910
454
456
84
6
import Control.Concurrent import Control.Exception -- check that async exceptions are restored to their previous -- state after an exception is raised and handled. main = do main_thread <- myThreadId m1 <- newEmptyMVar m2 <- newEmptyMVar m3 <- newEmptyMVar forkIO (do takeMVar m1 throwTo main_thread (ErrorCall "foo") takeMVar m2 throwTo main_thread (ErrorCall "bar") putMVar m3 () ) (do mask $ \restore -> do (do putMVar m1 () restore ( -- unblocked, "foo" delivered to "caught1" myDelay 100000 ) ) `Control.Exception.catch` \e -> putStrLn ("caught1: " ++ show (e::SomeException)) putMVar m2 () -- blocked here, "bar" can't be delivered (sum [1..10000] `seq` return ()) `Control.Exception.catch` \e -> putStrLn ("caught2: " ++ show (e::SomeException)) -- unblocked here, "bar" delivered to "caught3" takeMVar m3 ) `Control.Exception.catch` \e -> putStrLn ("caught3: " ++ show (e::SomeException)) -- compensate for the fact that threadDelay is non-interruptible -- on Windows with the threaded RTS in 6.6. myDelay usec = do m <- newEmptyMVar forkIO $ do threadDelay usec; putMVar m () takeMVar m
urbanslug/ghc
testsuite/tests/concurrent/should_run/conc017a.hs
bsd-3-clause
1,238
6
21
307
345
171
174
31
1
{-# LANGUAGE ForeignFunctionInterface #-} module Main where -- Test for #1648 import Foreign import Data.Int import Data.Word f :: Int64 -> IO Int64 f x = return $ x + 1 g :: Word64 -> IO Word64 g x = return $ x + 2 type WCall = Word64 -> IO Word64 foreign import ccall "wrapper" mkWCall :: WCall -> IO (FunPtr WCall) foreign import ccall "dynamic" call_w :: FunPtr WCall -> WCall type ICall = Int64 -> IO Int64 foreign import ccall "wrapper" mkICall :: ICall -> IO (FunPtr ICall) foreign import ccall "dynamic" call_i :: FunPtr ICall -> ICall main = do fp <- mkICall f call_i fp 3 >>= print fp <- mkWCall g call_w fp 4 >>= print
tibbe/ghc
testsuite/tests/ffi/should_run/ffi019.hs
bsd-3-clause
645
0
9
137
238
122
116
20
1
{-# OPTIONS_GHC -fdefer-type-errors #-} module Main where data Foo = MkFoo data Bar = MkBar Foo deriving Show main = do { print True; print (MkBar MkFoo) }
siddhanathan/ghc
testsuite/tests/deriving/should_run/T9576.hs
bsd-3-clause
160
0
9
32
50
28
22
5
1
module Main where import System.Environment import Text.ParserCombinators.Parsec hiding (spaces) main :: IO () main = do args <- getArgs putStrLn (readExpr (args !! 0)) symbol :: Parser Char symbol = oneOf "!$%&|*+-/:<=>?@^_~#" readExpr :: String -> String readExpr input = case parse symbol "lisp" input of Left err -> "No match: " ++ show err Right val -> "Found value"
tismith/tlisp
write-yourself-a-scheme/listings/listing3.1.hs
mit
394
0
11
82
131
67
64
12
2
{-# LANGUAGE OverloadedStrings #-} module WordProblem (answer) where import Data.Text (pack) import Data.List (foldl') import Control.Applicative -- (pure, (<|>), (<$>), (<*>), (<*), (*>)) import Data.Attoparsec.Text ( Parser, signed, decimal, space, maybeResult, parse, many' ) import Prelude answerParser :: Parser Int answerParser = do n <- "What is " *> signed decimal ops <- many' (space *> operation) "?" *> pure (foldl' (flip ($)) n ops) answer :: String -> Maybe Int answer = maybeResult . parse answerParser . pack operation :: Parser (Int -> Int) operation = (flip <$> operator) <* space <*> signed decimal operator :: Parser (Int -> Int -> Int) operator = "plus" *> pure (+) <|> "minus" *> pure (-) <|> "multiplied by" *> pure (*) <|> "divided by" *> pure div
stevejb71/xhaskell
wordy/example.hs
mit
836
0
12
191
276
150
126
22
1
-- Copyright 2017 Maximilian Huber <[email protected]> -- SPDX-License-Identifier: MIT {-# OPTIONS_GHC -W -fwarn-unused-imports -fno-warn-missing-signatures #-} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} module XMonad.MyConfig ( runMyConfig , composeMyConfig ) where import System.Environment ( getExecutablePath, getArgs, ) import Control.Monad ( when ) import XMonad import XMonad.Util.Replace ( replace ) -------------------------------------------------------------------------------- -- MyConfig import XMonad.MyConfig.Core ( coreConfig, applyMyRestartKBs ) import XMonad.MyConfig.MyManageHookLayer ( applyMyManageHook ) import XMonad.MyConfig.Scratchpads ( applyMyScratchpads ) import XMonad.MyConfig.ToggleFollowFocus ( applyMyFollowFocus ) import XMonad.MyConfig.Notify ( applyMyUrgencyHook ) import XMonad.MyConfig.MyLayoutLayer ( applyMyLayoutModifications ) import XMonad.MyConfig.MyLogHookLayer ( getXMProcs, applyMyLogHook ) -- runMyConfig :: IO () -- runMyConfig = do -- xmprocs <-getXMProcs -- executablePath <- getExecutablePath -- xmonad $ composeMyConfig xmprocs executablePath runMyConfig :: IO () runMyConfig = do args <- getArgs when ("--myreplace" `elem` args) $ do putStrLn "try to replace current window manager ..." replace xmprocs <- getXMProcs executablePath <- getExecutablePath putStrLn ("try to launch: " ++ executablePath) launch $ composeMyConfig xmprocs executablePath composeMyConfig xmprocs executablePath = let layers :: (LayoutClass a Window) => [XConfig a -> XConfig a] layers = [ applyMyLayoutModifications , applyMyRestartKBs executablePath , applyMyManageHook , applyMyUrgencyHook , applyMyScratchpads , applyMyFollowFocus , applyMyLogHook xmprocs ] in foldl (\ c f -> f c) coreConfig layers
maximilianhuber/myconfig
xmonad/lib/XMonad/MyConfig.hs
mit
1,920
0
12
368
333
190
143
37
1
module Symmath.Functiontable where import Text.Printf import Text.PrettyPrint import qualified Data.Map.Strict as M import Symmath.Terms import Symmath.Eval data FuncValue = Value Double | Undefined instance Show FuncValue where show (Value n) = show n show Undefined = "undef" -- Use show on the returned Docs to format (render) them. ---- Simple number lists. functionEval :: Double -> Double -> SymTerm -> Char -> [FuncValue] functionEval from ival term indep = map evalForX [from,from+ival..] where evalForX x = case evalTermP term (M.insert indep x M.empty) of Left _ -> Undefined Right y -> Value y ------------ Functions using defaults -------------------- -- Uses default values for field width, accuracy and the independent variable defaultFunctionTable :: Double -> Double -> Double -> SymTerm -> Doc defaultFunctionTable from to ival term = multipleFunctionsDefault from to ival [term] multipleFunctionsDefault :: Double -> Double -> Double -> [SymTerm] -> Doc multipleFunctionsDefault from to ival terms = multipleFunctions from to ival width acc terms indep where width = 15 acc = 4 indep = 'x' ----------- non-default-using functions ------------------- functionTable :: Double -> Double -> Double -> Int -> Int -> SymTerm -> Char -> Doc functionTable from to ival width acc term indep = multipleFunctions from to ival width acc [term] indep multipleFunctions :: Double -> Double -> Double -> Int -> Int -> [SymTerm] -> Char -> Doc multipleFunctions from to ival width acc terms indep = foldr1 ($$) . (header:) . map (foldr1 (<+>) . calcLine) $ [from,(from+ival)..to] where header = colHeads $$ headSepLine colHeads = foldr1 (<+>) . map (text . printf ('%':show width++"s") . show) $ terms' headSepLine = foldr1 (<+>) $ replicate (length terms') (text . replicate width $ '-') calcLine x = map (calcFunc x) terms' calcFunc x term = case evalTermP term (M.insert indep x M.empty) of Right y -> printfFuncValue width acc $ Value y Left _ -> printfFuncValue width acc Undefined terms' = (Variable indep):terms -- Util printfFuncValue :: Int -> Int -> FuncValue -> Doc printfFuncValue width _ Undefined = text $ printf ('%':show width++"s") "undef" printfFuncValue width acc (Value n) = text $ printf ('%':show width++"."++show acc++"f") n
Spheniscida/symmath
Symmath/Functiontable.hs
mit
2,477
0
17
579
795
411
384
37
2
-- Countdown example from chapter 11 of Programming in Haskell, -- Graham Hutton, Cambridge University Press, 2007. With help -- from chapter 20 of Pearls of Functional Algorithm Design, -- Richard Bird, Cambridge University Press, 2010. import System.CPUTime import Numeric import System.IO -- Expressions -- ----------- data Op = Add | Sub | Mul | Div valid :: Op -> Int -> Int -> Bool valid Add _ _ = True valid Sub x y = x > y valid Mul _ _ = True valid Div x y = x `mod` y == 0 apply :: Op -> Int -> Int -> Int apply Add x y = x + y apply Sub x y = x - y apply Mul x y = x * y apply Div x y = x `div` y data Expr = Val Int | App Op Expr Expr values :: Expr -> [Int] values (Val n) = [n] values (App _ l r) = values l ++ values r eval :: Expr -> [Int] eval (Val n) = [n | n > 0] eval (App o l r) = [apply o x y | x <- eval l , y <- eval r , valid o x y] -- Combinatorial functions -- ----------------------- subs :: [a] -> [[a]] subs [] = [[]] subs (x:xs) = yss ++ map (x:) yss where yss = subs xs interleave :: a -> [a] -> [[a]] interleave x [] = [[x]] interleave x (y:ys) = (x:y:ys) : map (y:) (interleave x ys) perms :: [a] -> [[a]] perms [] = [[]] perms (x:xs) = concat (map (interleave x) (perms xs)) -- Exercise 0 -- choices :: [a] -> [[a]] choices xs = [zs | ys <- subs xs, zs <- perms ys] -- Exercise 1 -- removeone :: Eq a => a -> [a] -> [a] removeone x [] = [] removeone x (y:ys) | x == y = ys | otherwise = y : removeone x ys -- Exercise 2 -- isChoice :: Eq a => [a] -> [a] -> Bool isChoice [] _ = True isChoice (x:xs) [] = False isChoice (x:xs) ys = elem x ys && isChoice xs (removeone x ys) -- Formalising the problem -- ----------------------- solution :: Expr -> [Int] -> Int -> Bool solution e ns n = elem (values e) (choices ns) && eval e == [n] -- Brute force solution -- -------------------- -- Exercise 3 -- split :: [a] -> [([a],[a])] split [] = [] split [_] = [] split (x:xs) = ([x], xs) : [(x : ls, rs) | (ls, rs) <- split xs] -- import Test.QuickCheck -- quickCheck ((\xs -> let ys = split xs in all (\t -> fst t ++ snd t == xs) ys) :: [Int] -> Bool) exprs :: [Int] -> [Expr] exprs [] = [] exprs [n] = [Val n] exprs ns = [e | (ls,rs) <- split ns , l <- exprs ls , r <- exprs rs , e <- combine l r] combine :: Expr -> Expr -> [Expr] combine l r = [App o l r | o <- ops] ops :: [Op] ops = [Add,Sub,Mul,Div] solutions :: [Int] -> Int -> [Expr] solutions ns n = [e | ns' <- choices ns , e <- exprs ns' , eval e == [n]] -- Combining generation and evaluation -- ----------------------------------- type Result = (Expr,Int) results :: [Int] -> [Result] results [] = [] results [n] = [(Val n,n) | n > 0] results ns = [res | (ls,rs) <- split ns , lx <- results ls , ry <- results rs , res <- combine' lx ry] combine' :: Result -> Result -> [Result] combine' (l,x) (r,y) = [(App o l r, apply o x y) | o <- ops , valid o x y] solutions' :: [Int] -> Int -> [Expr] solutions' ns n = [e | ns' <- choices ns , (e,m) <- results ns' , m == n] -- Exploiting numeric properties -- ----------------------------- valid' :: Op -> Int -> Int -> Bool valid' Add x y = x <= y valid' Sub x y = x > y valid' Mul x y = x /= 1 && y /= 1 && x <= y valid' Div x y = y /= 1 && x `mod` y == 0 results' :: [Int] -> [Result] results' [] = [] results' [n] = [(Val n,n) | n > 0] results' ns = [res | (ls,rs) <- split ns , lx <- results' ls , ry <- results' rs , res <- combine'' lx ry] combine'' :: Result -> Result -> [Result] combine'' (l,x) (r,y) = [(App o l r, apply o x y) | o <- ops , valid' o x y] solutions'' :: [Int] -> Int -> [Expr] solutions'' ns n = [e | ns' <- choices ns , (e,m) <- results' ns' , m == n] -- Interactive version for testing -- ------------------------------- instance Show Op where show Add = "+" show Sub = "-" show Mul = "*" show Div = "/" instance Show Expr where show (Val n) = show n show (App o l r) = bracket l ++ show o ++ bracket r where bracket (Val n) = show n bracket e = "(" ++ show e ++ ")" showtime :: Integer -> String showtime t = showFFloat (Just 3) (fromIntegral t / (10^12)) " seconds" display :: [Expr] -> IO () display es = do t0 <- getCPUTime if null es then do t1 <- getCPUTime putStr "\nThere are no solutions, verified in " putStr (showtime (t1 - t0)) else do t1 <- getCPUTime putStr "\nOne possible solution is " putStr (show (head es)) putStr ", found in " putStr (showtime (t1 - t0)) putStr "\n\nPress return to continue searching..." getLine putStr "\n" t2 <- getCPUTime if null (tail es) then putStr "There are no more solutions" else do sequence [print e | e <- tail es] putStr "\nThere were " putStr (show (length es)) putStr " solutions in total, found in " t3 <- getCPUTime putStr (showtime ((t1 - t0) + (t3 - t2))) putStr ".\n\n" main :: IO () main = do hSetBuffering stdout NoBuffering putStrLn "\nCOUNTDOWN NUMBERS GAME SOLVER" putStrLn "-----------------------------\n" putStr "Enter the given numbers : " ns <- readLn putStr "Enter the target number : " n <- readLn display (solutions'' ns n)
anwb/fp-one-on-one
lecture-10-hw.hs
mit
8,958
0
19
5,073
2,472
1,280
1,192
144
3
module Data.DirectoryTreeSpec where import qualified Data.Aeson as AE import qualified Data.Aeson.Encode.Pretty as AE import qualified Data.ByteString.Lazy.Char8 as BS import Data.Tree import Data.DirectoryTree import Data.Either (isRight) import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "JSON (de)serialization" $ it "can be encoded and decoded from JSON" $ do let encodedJson = BS.unpack . prettyEncode $ testTree let decodedJson = AE.eitherDecode (BS.pack encodedJson) :: Either String DirectoryTree {- putStrLn encodedJson -} {- case decodedJson of -} {- (Left err) -> putStrLn err -} {- (Right val) -> putStr $ show decodedJson -} isRight decodedJson `shouldBe` True testTree :: DirectoryTree testTree = DirectoryTree rootNode rootNode = Node (FileDescription "features" "features") [creatures] creatures = Node (FileDescription "creatures" "features/creatures") [swampThing, wolfman] swampThing = Node (FileDescription "swamp-thing" "features/creatures/swamp-thing") [ Node (FileDescription "vegetable-mind-control.feature" "features/creatures/swamp-thing/vegetable-mind-control.feature") [], Node (FileDescription "limb-regeneration.feature" "features/creatures/swamp-thing/limb-regeneration.feature") [] ] wolfman = Node (FileDescription "wolfman" "features/creatures/wolfman") [ Node (FileDescription "shape-shifting.feature" "features/creatures/wolfman/shape-shifting.feature") [], Node (FileDescription "animal-instincts.feature" "features/creatures/wolfman/animal-instincts.feature") [] ] prettyEncode :: AE.ToJSON a => a -> BS.ByteString prettyEncode = AE.encodePretty' prettyConfig prettyConfig :: AE.Config prettyConfig = AE.Config { AE.confIndent = 2, AE.confCompare = mempty }
gust/feature-creature
legacy/lib/test/Data/DirectoryTreeSpec.hs
mit
1,802
0
16
260
397
215
182
31
1
{-# htermination intersect :: [Ordering] -> [Ordering] -> [Ordering] #-} import List
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/List_intersect_7.hs
mit
85
0
3
12
5
3
2
1
0
{-# LANGUAGE OverloadedStrings #-} import SMTLib1.QF_AUFBV as BV import System.Process import System.IO main :: IO () main = do let txt = show (pp script) putStrLn txt putStrLn (replicate 80 '-') -- putStrLn =<< readProcess "yices" ["-smt", "-tc"] txt putStrLn =<< readProcess "yices" ["-f"] txt script :: Script script = Script "Test" [ logic "QF_AUFBV" , constDef "a" (tBitVec 8) , goal (BV.concat (bv 1 8) (bv 3 8) === bv 259 16) ] script1 :: Script script1 = Script "Test" [ logic "QF_BV" , constDef "x" (tBitVec 8) , assume (c "x" === bv 0 8) , goal (c "x" === bv 256 8) ] c x = App x []
yav/smtLib
test/Test1.hs
mit
641
0
12
160
258
128
130
22
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} module Json.UserSpec (spec) where import Data.Aeson.Lens import Lastfm import Lastfm.User import Test.Hspec import SpecHelper spec :: Spec spec = do it "getRecentStations" $ privately (getRecentStations <*> user "liblastfm" <* limit 10) `shouldHaveJson` key "recentstations".key "station".values.key "name"._String it "getRecommendedArtists" $ privately (getRecommendedArtists <* limit 10) `shouldHaveJson` key "recommendations".key "artist".values.key "name"._String it "getRecommendedEvents" $ privately (getRecommendedEvents <* limit 10) `shouldHaveJson` key "events".key "event".key "url"._String it "shout" $ shouldHaveJson_ . privately $ shout <*> user "liblastfm" <*> message "test message" it "getArtistTracks" $ publicly (getArtistTracks <*> user "smpcln" <*> artist "Dvar") `shouldHaveJson` key "artisttracks".key "track".values.key "name"._String it "getBannedTracks" $ publicly (getBannedTracks <*> user "smpcln" <* limit 10) `shouldHaveJson` key "bannedtracks".key "track".values.key "name"._String it "getEvents" $ publicly (getEvents <*> user "chansonnier" <* limit 5) `shouldHaveJson` key "events".key "event".values.key "venue".key "url"._String it "getFriends" $ publicly (getFriends <*> user "smpcln" <* limit 10) `shouldHaveJson` key "friends".key "user".values.key "name"._String it "getPlayCount" $ publicly (getInfo <*> user "smpcln") `shouldHaveJson` key "user".key "playcount"._String it "getGetLovedTracks" $ publicly (getLovedTracks <*> user "smpcln" <* limit 10) `shouldHaveJson` key "lovedtracks".key "track".values.key "name"._String it "getNeighbours" $ publicly (getNeighbours <*> user "smpcln" <* limit 10) `shouldHaveJson` key "neighbours".key "user".values.key "name"._String it "getNewReleases" $ publicly (getNewReleases <*> user "rj") `shouldHaveJson` key "albums".key "album".values.key "url"._String it "getPastEvents" $ publicly (getPastEvents <*> user "mokele" <* limit 5) `shouldHaveJson` key "events".key "event".values.key "url"._String it "getPersonalTags" $ publicly (getPersonalTags <*> user "crackedcore" <*> tag "rhythmic noise" <*> taggingType "artist" <* limit 10) `shouldHaveJson` key "taggings".key "artists".key "artist".values.key "name"._String it "getPlaylists" $ publicly (getPlaylists <*> user "mokele") `shouldHaveJson` key "playlists".key "playlist".values.key "title"._String it "getRecentTracks" $ publicly (getRecentTracks <*> user "smpcln" <* limit 10) `shouldHaveJson` key "recenttracks".key "track".values.key "name"._String it "getShouts" $ publicly (getShouts <*> user "smpcln" <* limit 2) `shouldHaveJson` key "shouts".key "shout".values.key "body"._String it "getTopAlbums" $ publicly (getTopAlbums <*> user "smpcln" <* limit 5) `shouldHaveJson` key "topalbums".key "album".values.key "artist".key "name"._String it "getTopArtists" $ publicly (getTopArtists <*> user "smpcln" <* limit 5) `shouldHaveJson` key "topartists".key "artist".values.key "name"._String it "getTopTags" $ publicly (getTopTags <*> user "smpcln" <* limit 10) `shouldHaveJson` key "toptags".key "tag".values.key "name"._String it "getTopTracks" $ publicly (getTopTracks <*> user "smpcln" <* limit 10) `shouldHaveJson` key "toptracks".key "track".values.key "url"._String it "getWeeklyAlbumChart" $ publicly (getWeeklyAlbumChart <*> user "smpcln") `shouldHaveJson` key "weeklyalbumchart".key "album".values.key "url"._String it "getWeeklyArtistChart" $ publicly (getWeeklyArtistChart <*> user "smpcln") `shouldHaveJson` key "weeklyartistchart".key "artist".values.key "url"._String it "getWeeklyChartList" $ publicly (getWeeklyChartList <*> user "smpcln") `shouldHaveJson` key "weeklychartlist".key "chart".values.key "from"._String it "getWeeklyTrackChart" $ publicly (getWeeklyTrackChart <*> user "smpcln") `shouldHaveJson` key "weeklytrackchart".key "track".values.key "url"._String
supki/liblastfm
test/api/Json/UserSpec.hs
mit
4,242
0
15
761
1,256
600
656
-1
-1
{-| Module : Database.Orville.PostgreSQL.Internal.Expr.NameExpr Copyright : Flipstone Technology Partners 2016-2018 License : MIT -} {-# LANGUAGE OverloadedStrings #-} module Database.Orville.PostgreSQL.Internal.Expr.NameExpr where import Data.String import Database.Orville.PostgreSQL.Internal.MappendCompat ((<>)) import Database.Orville.PostgreSQL.Internal.Expr.Expr import Database.Orville.PostgreSQL.Internal.QueryKey type NameExpr = Expr NameForm data NameForm = NameForm { nameFormTable :: Maybe String , nameFormName :: String } deriving (Eq, Ord) instance IsString NameForm where fromString str = NameForm {nameFormTable = Nothing, nameFormName = str} instance QualifySql NameForm where qualified form table = form {nameFormTable = Just table} instance QueryKeyable NameForm where queryKey = QKField . unescapedName instance GenerateSql NameForm where generateSql (NameForm Nothing name) = "\"" <> rawSql name <> "\"" generateSql (NameForm (Just table) name) = "\"" <> rawSql table <> "\".\"" <> rawSql name <> "\"" unescapedName :: NameForm -> String unescapedName (NameForm Nothing name) = name unescapedName (NameForm (Just table) name) = table <> "." <> name
flipstone/orville
orville-postgresql/src/Database/Orville/PostgreSQL/Internal/Expr/NameExpr.hs
mit
1,208
0
10
178
303
169
134
24
1
{-# LANGUAGE NoMonomorphismRestriction, OverloadedStrings #-} import Text.XML.HXT.Core import Data.List import Text.HandsomeSoup import System.Random import System.Environment import Network.HTTP.Base import System.Process import Network.HTTP.Enumerator import Network.HTTP.Types (methodPost) import qualified Data.ByteString.Lazy.Char8 as L main :: IO () main = do args <- getArgs case length args of 0 -> putStrLn help _ -> do gen <- newStdGen wpList <- wallpapers (args !! 0) (args !! 1) wp <- wallpaper $ wpList !! head (randomRs (0, length wpList) gen) createProcess $ shell ("feh --bg-scale " ++ head wp) putStrLn $ wp !! 1 help :: String help = "Usage: randwp tag resolution" wallpapers :: String -> String -> IO [String] wallpapers q res = do html <- request q res let doc = parseHtml $ L.unpack html contents <- runX $ doc >>> css "a" ! "href" return $ filter ("wallpaper" `isInfixOf`) contents wallpaper :: String -> IO [String] wallpaper url = do doc <- fromUrl url runX $ getWp doc getWp doc = doc >>> css "div" >>> hasAttrValue "id" (== "bigwall") >>> css "img" ! "src" <+> css "img" ! "alt" request q res = do req0 <- parseUrl "http://wallbase.cc/search/" let req = req0 { method = methodPost , requestHeaders = [("Content-Type", "application/x-www-form-urlencoded")] , requestBody = RequestBodyLBS $ mkPost q res } res <- withManager $ httpLbs req return $ responseBody res mkPost :: String -> String -> L.ByteString mkPost q res = L.pack $ "query=" ++ urlEncode q ++ "&res=" ++ res ++ "&res_opt=gteq"
Okasu/randwp
RandWP.hs
mit
1,923
0
18
648
556
282
274
41
2
{- | Description : logic for Maude (rewriting logic) Copyright : (c) Otto-von-Guericke University of Magdeburg License : GPLv2 or higher, see LICENSE.txt The "Maude" folder contains the skeleton of an instance of "Logic.Logic" for Maude, see <https://en.wikipedia.org/wiki/Maude_system> M. Codescu, T. Mossakowski, A. Riesco, and C. Maeder. Integrating Maude into Hets In M. Johnson and D. Pavlovic, editors, Proceedings of the 13th International Conference on Algebraic Methodology and Software Technology (AMAST 2010). <http://maude.sip.ucm.es/~adrian/files/hetsAMAST.pdf> Adrián Riesco Rodríguez: Declarative Debugging and Heterogeneous Specification in Maude, PhD thesis <http://maude.sip.ucm.es/~adrian/files/thesis.pdf> -} module Maude where
spechub/Hets
Maude.hs
gpl-2.0
765
0
2
105
5
4
1
1
0