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
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sqlinjectionmatchset-fieldtomatch.html module Stratosphere.ResourceProperties.WAFRegionalSqlInjectionMatchSetFieldToMatch where import Stratosphere.ResourceImports -- | Full data type definition for -- WAFRegionalSqlInjectionMatchSetFieldToMatch. See -- 'wafRegionalSqlInjectionMatchSetFieldToMatch' for a more convenient -- constructor. data WAFRegionalSqlInjectionMatchSetFieldToMatch = WAFRegionalSqlInjectionMatchSetFieldToMatch { _wAFRegionalSqlInjectionMatchSetFieldToMatchData :: Maybe (Val Text) , _wAFRegionalSqlInjectionMatchSetFieldToMatchType :: Val Text } deriving (Show, Eq) instance ToJSON WAFRegionalSqlInjectionMatchSetFieldToMatch where toJSON WAFRegionalSqlInjectionMatchSetFieldToMatch{..} = object $ catMaybes [ fmap (("Data",) . toJSON) _wAFRegionalSqlInjectionMatchSetFieldToMatchData , (Just . ("Type",) . toJSON) _wAFRegionalSqlInjectionMatchSetFieldToMatchType ] -- | Constructor for 'WAFRegionalSqlInjectionMatchSetFieldToMatch' containing -- required fields as arguments. wafRegionalSqlInjectionMatchSetFieldToMatch :: Val Text -- ^ 'wafrsimsftmType' -> WAFRegionalSqlInjectionMatchSetFieldToMatch wafRegionalSqlInjectionMatchSetFieldToMatch typearg = WAFRegionalSqlInjectionMatchSetFieldToMatch { _wAFRegionalSqlInjectionMatchSetFieldToMatchData = Nothing , _wAFRegionalSqlInjectionMatchSetFieldToMatchType = typearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sqlinjectionmatchset-fieldtomatch.html#cfn-wafregional-sqlinjectionmatchset-fieldtomatch-data wafrsimsftmData :: Lens' WAFRegionalSqlInjectionMatchSetFieldToMatch (Maybe (Val Text)) wafrsimsftmData = lens _wAFRegionalSqlInjectionMatchSetFieldToMatchData (\s a -> s { _wAFRegionalSqlInjectionMatchSetFieldToMatchData = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sqlinjectionmatchset-fieldtomatch.html#cfn-wafregional-sqlinjectionmatchset-fieldtomatch-type wafrsimsftmType :: Lens' WAFRegionalSqlInjectionMatchSetFieldToMatch (Val Text) wafrsimsftmType = lens _wAFRegionalSqlInjectionMatchSetFieldToMatchType (\s a -> s { _wAFRegionalSqlInjectionMatchSetFieldToMatchType = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/WAFRegionalSqlInjectionMatchSetFieldToMatch.hs
mit
2,446
0
13
214
267
153
114
28
1
module HLint.Default where import Control.Arrow import Control.Exception import Control.Monad import Data.Function import Data.Int import Data.List as X import Data.Maybe import Data.Monoid import System.IO import IO as System.IO import List as Data.List import Maybe as Data.Maybe import Monad as Control.Monad -- I/O error = putStrLn (show x) ==> print x error = mapM_ putChar ==> putStr error = hGetChar stdin ==> getChar error = hGetLine stdin ==> getLine error = hGetContents stdin ==> getContents error = hPutChar stdout ==> putChar error = hPutStr stdout ==> putStr error = hPutStrLn stdout ==> putStrLn error = hPrint stdout ==> print -- ORD error = not (a == b) ==> a /= b where note = "incorrect if either value is NaN" error = not (a /= b) ==> a == b where note = "incorrect if either value is NaN" error = not (a > b) ==> a <= b where note = "incorrect if either value is NaN" error = not (a >= b) ==> a < b where note = "incorrect if either value is NaN" error = not (a < b) ==> a >= b where note = "incorrect if either value is NaN" error = not (a <= b) ==> a > b where note = "incorrect if either value is NaN" error = compare x y /= GT ==> x <= y error = compare x y == LT ==> x < y error = compare x y /= LT ==> x >= y error = compare x y == GT ==> x > y error = x == a || x == b || x == c ==> x `elem` [a,b,c] error = x /= a && x /= b && x /= c ==> x `notElem` [a,b,c] --error = compare (f x) (f y) ==> Data.Ord.comparing f x y -- not that great --error = on compare f ==> Data.Ord.comparing f -- not that great -- READ/SHOW error = showsPrec 0 x "" ==> show x error = readsPrec 0 ==> reads error = showsPrec 0 ==> shows -- LIST error = concat (map f x) ==> concatMap f x warn = concat [a,b] ==> a ++ b warn "Use map once" = map f (map g x) ==> map (f . g) x warn = x !! 0 ==> head x error = take n (repeat x) ==> replicate n x error = head (reverse x) ==> last x error = head (drop n x) ==> x !! n error = reverse (tail (reverse x)) ==> init x error = take (length x - 1) x ==> init x error = isPrefixOf (reverse x) (reverse y) ==> isSuffixOf x y error = foldr (++) [] ==> concat error = span (not . p) ==> break p error = break (not . p) ==> span p error = concatMap (++ "\n") ==> unlines error = or (map p x) ==> any p x error = and (map p x) ==> all p x error = zipWith (,) ==> zip error = zipWith3 (,,) ==> zip3 warn = length x == 0 ==> null x where note = "increases laziness" warn "Use null" = length x /= 0 ==> not (null x) error "Use :" = (\x -> [x]) ==> (:[]) error = map (uncurry f) (zip x y) ==> zipWith f x y warn = map f (zip x y) ==> zipWith (curry f) x y where _ = isVar f error = not (elem x y) ==> notElem x y warn = foldr f z (map g x) ==> foldr (f . g) z x error = x ++ concatMap (' ':) y ==> unwords (x:y) error = intercalate " " ==> unwords warn = concat (intersperse x y) ==> intercalate x y where _ = notEq x " " warn = concat (intersperse " " x) ==> unwords x error "Use any" = null (filter f x) ==> not (any f x) error "Use any" = filter f x == [] ==> not (any f x) error = filter f x /= [] ==> any f x -- FOLDS error = foldr (>>) (return ()) ==> sequence_ error = foldr (&&) True ==> and error = foldl (&&) True ==> and error = foldr1 (&&) ==> and error = foldl1 (&&) ==> and error = foldr (||) False ==> or error = foldl (||) False ==> or error = foldr1 (||) ==> or error = foldl1 (||) ==> or error = foldl (+) 0 ==> sum error = foldr (+) 0 ==> sum error = foldl1 (+) ==> sum error = foldr1 (+) ==> sum error = foldl (*) 1 ==> product error = foldr (*) 1 ==> product error = foldl1 (*) ==> product error = foldr1 (*) ==> product error = foldl1 max ==> maximum error = foldr1 max ==> maximum error = foldl1 min ==> minimum error = foldr1 min ==> minimum -- FUNCTION error = (\x -> x) ==> id error = (\x y -> x) ==> const error = (\(_,y) -> y) ==> snd error = (\(x,_) -> x) ==> fst warn "Use curry" = (\x y-> f (x,y)) ==> curry f where _ = notIn [x,y] f warn "Use uncurry" = (\(x,y) -> f x y) ==> uncurry f where _ = notIn [x,y] f error "Redundant $" = (($) . f) ==> f error "Redundant $" = (f $) ==> f warn = (\x -> y) ==> const y where _ = isAtom y && notIn x y error "Redundant flip" = flip f x y ==> f y x where _ = isApp original warn = (\a b -> o (f a) (f b)) ==> o `Data.Function.on` f -- BOOL error "Redundant ==" = a == True ==> a warn "Redundant ==" = a == False ==> not a error "Redundant if" = (if a then x else x) ==> x where note = "reduces strictness" error "Redundant if" = (if a then True else False) ==> a error "Redundant if" = (if a then False else True) ==> not a error "Redundant if" = (if a then t else (if b then t else f)) ==> if a || b then t else f error "Redundant if" = (if a then (if b then t else f) else f) ==> if a && b then t else f error "Redundant if" = (if x then True else y) ==> x || y where _ = notEq y False error "Redundant if" = (if x then y else False) ==> x && y where _ = notEq y True warn "Use if" = case a of {True -> t; False -> f} ==> if a then t else f warn "Use if" = case a of {False -> f; True -> t} ==> if a then t else f warn "Use if" = case a of {True -> t; _ -> f} ==> if a then t else f warn "Use if" = case a of {False -> f; _ -> t} ==> if a then t else f warn "Redundant if" = (if c then (True, x) else (False, x)) ==> (c, x) where note = "reduces strictness" warn "Redundant if" = (if c then (False, x) else (True, x)) ==> (not c, x) where note = "reduces strictness" warn = or [x,y] ==> x || y warn = or [x,y,z] ==> x || y || z warn = and [x,y] ==> x && y warn = and [x,y,z] ==> x && y && z -- ARROW error = id *** g ==> second g error = f *** id ==> first f error = zip (map f x) (map g x) ==> map (f Control.Arrow.&&& g) x warn = (\(x,y) -> (f x, g y)) ==> f Control.Arrow.*** g where _ = notIn [x,y] [f,g] warn = (\x -> (f x, g x)) ==> f Control.Arrow.&&& g where _ = notIn x [f,g] warn = (\(x,y) -> (f x,y)) ==> Control.Arrow.first f where _ = notIn [x,y] f warn = (\(x,y) -> (x,f y)) ==> Control.Arrow.second f where _ = notIn [x,y] f warn = (f (fst x), g (snd x)) ==> (f Control.Arrow.*** g) x warn "Redundant pair" = (fst x, snd x) ==> x -- FUNCTOR error "Functor law" = fmap f (fmap g x) ==> fmap (f . g) x error "Functor law" = fmap id ==> id -- MONAD error "Monad law, left identity" = return a >>= f ==> f a error "Monad law, right identity" = m >>= return ==> m warn = m >>= return . f ==> fmap f m error = (if x then y else return ()) ==> Control.Monad.when x $ _noParen_ y where _ = not (isAtom y) error = (if x then y else return ()) ==> Control.Monad.when x y where _ = isAtom y error = (if x then return () else y) ==> Control.Monad.unless x $ _noParen_ y where _ = not (isAtom y) error = (if x then return () else y) ==> Control.Monad.unless x y where _ = isAtom y error = sequence (map f x) ==> mapM f x error = sequence_ (map f x) ==> mapM_ f x warn = flip mapM ==> Control.Monad.forM warn = flip mapM_ ==> Control.Monad.forM_ error = when (not x) ==> unless x error = x >>= id ==> Control.Monad.join x error = liftM f (liftM g x) ==> liftM (f . g) x -- MONAD LIST error = liftM unzip (mapM f x) ==> Control.Monad.mapAndUnzipM f x error = sequence (zipWith f x y) ==> Control.Monad.zipWithM f x y error = sequence_ (zipWith f x y) ==> Control.Monad.zipWithM_ f x y error = sequence (replicate n x) ==> Control.Monad.replicateM n x error = sequence_ (replicate n x) ==> Control.Monad.replicateM_ n x error = mapM f (map g x) ==> mapM (f . g) x error = mapM_ f (map g x) ==> mapM_ (f . g) x -- LIST COMP warn "Use list comprehension" = (if b then [x] else []) ==> [x | b] warn "Redundant list comprehension" = [x | x <- y] ==> y where _ = isVar x -- SEQ error "Redundant seq" = x `seq` x ==> x error "Redundant $!" = id $! x ==> x -- MAYBE error = maybe x id ==> Data.Maybe.fromMaybe x error = maybe False (const True) ==> Data.Maybe.isJust error = maybe True (const False) ==> Data.Maybe.isNothing error = not (isNothing x) ==> isJust x error = not (isJust x) ==> isNothing x error = maybe [] (:[]) ==> maybeToList error = catMaybes (map f x) ==> mapMaybe f x warn = (case x of Nothing -> y; Just a -> a) ==> fromMaybe y x error = (if isNothing x then y else f (fromJust x)) ==> maybe y f x error = (if isJust x then f (fromJust x) else y) ==> maybe y f x error = maybe Nothing (Just . f) ==> fmap f warn = map fromJust . filter isJust ==> Data.Maybe.catMaybes error = x == Nothing ==> isNothing x error = Nothing == x ==> isNothing x error = x /= Nothing ==> Data.Maybe.isJust x error = Nothing /= x ==> Data.Maybe.isJust x error = concatMap (maybeToList . f) ==> Data.Maybe.mapMaybe f error = concatMap maybeToList ==> catMaybes error = maybe n Just x ==> Control.Monad.mplus x n warn = (case x of Just a -> a; Nothing -> y) ==> fromMaybe y x error = (if isNothing x then y else fromJust x) ==> fromMaybe y x error = (if isJust x then fromJust x else y) ==> fromMaybe y x error = isJust x && (fromJust x == y) ==> x == Just y error = mapMaybe f (map g x) ==> mapMaybe (f . g) x -- INFIX warn "Use infix" = X.elem x y ==> x `X.elem` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = X.notElem x y ==> x `X.notElem` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = X.isInfixOf x y ==> x `X.isInfixOf` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = X.isSuffixOf x y ==> x `X.isSuffixOf` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = X.isPrefixOf x y ==> x `X.isPrefixOf` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = X.union x y ==> x `X.union` y where _ = not (isInfixApp original) && not (isParen result) warn "Use infix" = X.intersect x y ==> x `X.intersect` y where _ = not (isInfixApp original) && not (isParen result) -- MATHS error "Redundant fromIntegral" = fromIntegral x ==> x where _ = isLitInt x error "Redundant fromInteger" = fromInteger x ==> x where _ = isLitInt x warn = x + negate y ==> x - y warn = 0 - x ==> negate x warn = log y / log x ==> logBase x y warn = x ** 0.5 ==> sqrt x warn = sin x / cos x ==> tan x warn = sinh x / cosh x ==> tanh x warn = n `rem` 2 == 0 ==> even n warn = n `rem` 2 /= 0 ==> odd n warn = not (even x) ==> odd x warn = not (odd x) ==> even x warn = x ** 0.5 ==> sqrt x warn = x ^^ y ==> x ** y where _ = isLitInt y warn "Use 1" = x ^ 0 ==> 1 warn = round (x - 0.5) ==> floor x -- EXCEPTION error "Use Control.Exception.catch" = Prelude.catch ==> Control.Exception.catch where note = "Prelude.catch does not catch most exceptions" warn = flip Control.Exception.catch ==> handle warn = flip (catchJust p) ==> handleJust p warn = Control.Exception.bracket b (const a) (const t) ==> Control.Exception.bracket_ b a t warn = Control.Exception.bracket (openFile x y) hClose ==> withFile x y warn = Control.Exception.bracket (openBinaryFile x y) hClose ==> withBinaryFile x y -- EVALUATE -- TODO: These should be moved in to HSE\Evaluate.hs and applied -- through a special evaluate hint mechanism error "Evaluate" = True && x ==> x error "Evaluate" = False && x ==> False error "Evaluate" = True || x ==> True error "Evaluate" = False || x ==> x error "Evaluate" = not True ==> False error "Evaluate" = not False ==> True error "Evaluate" = Nothing >>= k ==> Nothing error "Evaluate" = either f g (Left x) ==> f x error "Evaluate" = either f g (Right y) ==> g y error "Evaluate" = fst (x,y) ==> x error "Evaluate" = snd (x,y) ==> y error "Evaluate" = f (fst p) (snd p) ==> uncurry f p error "Evaluate" = init [x] ==> [] error "Evaluate" = null [] ==> True error "Evaluate" = length [] ==> 0 error "Evaluate" = foldl f z [] ==> z error "Evaluate" = foldr f z [] ==> z error "Evaluate" = foldr1 f [x] ==> x error "Evaluate" = scanr f z [] ==> [z] error "Evaluate" = scanr1 f [] ==> [] error "Evaluate" = scanr1 f [x] ==> [x] error "Evaluate" = take n [] ==> [] error "Evaluate" = drop n [] ==> [] error "Evaluate" = takeWhile p [] ==> [] error "Evaluate" = dropWhile p [] ==> [] error "Evaluate" = span p [] ==> ([],[]) error "Evaluate" = lines "" ==> [] error "Evaluate" = unwords [] ==> "" error "Evaluate" = x - 0 ==> x error "Evaluate" = x * 1 ==> x error "Evaluate" = x / 1 ==> x error "Evaluate" = concat [a] ==> a error "Evaluate" = concat [] ==> [] error "Evaluate" = zip [] [] ==> [] error "Evaluate" = id x ==> x error "Evaluate" = const x y ==> x -- COMPLEX error "Use isPrefixOf" = (take i s == t) ==> _eval_ ((i == length t) && (t `Data.List.isPrefixOf` s)) where _ = (isList t || isLit t) && isLit i {- -- clever hint, but not actually a good idea warn = (do a <- f; g a) ==> f >>= g where _ = (isAtom f || isApp f) && notIn a g -} test = hints named test are to allow people to put test code within hint files testPrefix = and any prefix also works {- <TEST> yes = concat . map f -- concatMap f yes = foo . bar . concat . map f . baz . bar -- concatMap f . baz . bar yes = map f (map g x) -- map (f . g) x yes = concat.map (\x->if x==e then l' else [x]) -- concatMap (\x->if x==e then l' else [x]) yes = f x where f x = concat . map head -- concatMap head yes = concat . map f . g -- concatMap f . g yes = concat $ map f x -- concatMap f x yes = "test" ++ concatMap (' ':) ["of","this"] -- unwords ("test":["of","this"]) yes = if f a then True else b -- f a || b yes = not (a == b) -- a /= b yes = not (a /= b) -- a == b yes = if a then 1 else if b then 1 else 2 -- if a || b then 1 else 2 no = if a then 1 else if b then 3 else 2 yes = a >>= return . id -- fmap id a yes = (x !! 0) + (x !! 2) -- head x yes = if b < 42 then [a] else [] -- [a | b < 42] yes = take 5 (foo xs) == "hello" -- "hello" `Data.List.isPrefixOf` foo xs no = take n (foo xs) == "hello" yes = head (reverse xs) -- last xs yes = reverse xs `isPrefixOf` reverse ys -- isSuffixOf xs ys no = putStrLn $ show (length xs) ++ "Test" yes = ftable ++ map (\ (c, x) -> (toUpper c, urlEncode x)) ftable -- toUpper Control.Arrow.*** urlEncode yes = map (\(a,b) -> a) xs -- fst yes = map (\(a,_) -> a) xs -- fst yes = readFile $ args !! 0 -- head args yes = if Debug `elem` opts then ["--debug"] else [] -- ["--debug" | Debug `elem` opts] yes = if nullPS s then return False else if headPS s /= '\n' then return False else alter_input tailPS >> return True \ -- if nullPS s || (headPS s /= '\n') then return False else alter_input tailPS >> return True yes = if foo then do stuff; moreStuff; lastOfTheStuff else return () \ -- Control.Monad.when foo $ do stuff ; moreStuff ; lastOfTheStuff yes = if foo then stuff else return () -- Control.Monad.when foo stuff yes = foo $ \(a, b) -> (a, y + b) -- Control.Arrow.second ((+) y) no = foo $ \(a, b) -> (a, a + b) yes = map (uncurry (+)) $ zip [1 .. 5] [6 .. 10] -- zipWith (+) [1 .. 5] [6 .. 10] no = do iter <- textBufferGetTextIter tb ; textBufferSelectRange tb iter iter no = flip f x $ \y -> y*y+y no = \x -> f x (g x) no = foo (\ v -> f v . g) yes = concat . intersperse " " -- unwords yes = Prelude.concat $ intersperse " " xs -- unwords xs yes = concat $ Data.List.intersperse " " xs -- unwords xs yes = if a then True else False -- a yes = if x then true else False -- x && true yes = elem x y -- x `elem` y yes = foo (elem x y) -- x `elem` y no = x `elem` y no = elem 1 [] : [] test a = foo (\x -> True) -- const True h a = flip f x (y z) -- f (y z) x h a = flip f x $ y z yes x = case x of {True -> a ; False -> b} -- if x then a else b yes x = case x of {False -> a ; _ -> b} -- if x then b else a no = const . ok . toResponse $ "saved" yes = case x z of Nothing -> y z; Just pattern -> pattern -- fromMaybe (y z) (x z) yes = if p then s else return () -- Control.Monad.when p s error = a $$$$ b $$$$ c ==> a . b $$$$$ c yes = when (not . null $ asdf) -- unless (null asdf) yes = id 1 -- 1 yes = case concat (map f x) of [] -> [] -- concatMap f x yes = Map.union a b -- a `Map.union` b yes = [v | v <- xs] -- xs no = [Left x | Left x <- xs] yes = Map.union a b -- a `Map.union` b when p s = if p then s else return () yes = x ^^ 18 -- x ** 18 no = x ^^ 18.5 instance Arrow (->) where first f = f *** id yes = fromInteger 12 -- 12 yes = catch -- Control.Exception.catch import Prelude hiding (catch); no = catch import Control.Exception as E; no = E.catch main = do f; putStrLn $ show x -- print x import Prelude \ yes = flip mapM -- Control.Monad.forM import Control.Monad \ yes = flip mapM -- forM import Control.Monad(forM) \ yes = flip mapM -- forM import Control.Monad(forM_) \ yes = flip mapM -- Control.Monad.forM import qualified Control.Monad \ yes = flip mapM -- Control.Monad.forM import qualified Control.Monad as CM \ yes = flip mapM -- CM.forM import qualified Control.Monad as CM(forM,filterM) \ yes = flip mapM -- CM.forM import Control.Monad as CM(forM,filterM) \ yes = flip mapM -- forM import Control.Monad hiding (forM) \ yes = flip mapM -- Control.Monad.forM import Control.Monad hiding (filterM) \ yes = flip mapM -- forM import qualified Data.Text.Lazy as DTL \ main = DTL.concat $ map (`DTL.snoc` '-') [DTL.pack "one", DTL.pack "two", DTL.pack "three"] import Text.Blaze.Html5.Attributes as A \ main = A.id (stringValue id') </TEST> -}
alphaHeavy/hlint
data/Default.hs
gpl-2.0
17,195
0
11
3,905
6,285
3,255
3,030
-1
-1
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ < 710 {-# LANGUAGE OverlappingInstances #-} #endif {-# LANGUAGE ViewPatterns, RankNTypes, ScopedTypeVariables, TypeSynonymInstances, FlexibleInstances #-} module Graphics.Implicit.ExtOpenScad.Util.OVal where import Graphics.Implicit.Definitions import Graphics.Implicit.ExtOpenScad.Definitions import qualified Control.Monad as Monad import Data.Maybe (isJust) -- | We'd like to be able to turn OVals into a given Haskell type class OTypeMirror a where fromOObj :: OVal -> Maybe a toOObj :: a -> OVal instance OTypeMirror OVal where fromOObj a = Just a toOObj a = a instance OTypeMirror ℝ where fromOObj (ONum n) = Just n fromOObj _ = Nothing toOObj n = ONum n instance OTypeMirror ℕ where fromOObj (ONum n) = if n == fromIntegral (floor n) then Just (floor n) else Nothing fromOObj _ = Nothing toOObj n = ONum $ fromIntegral n instance OTypeMirror Bool where fromOObj (OBool b) = Just b fromOObj _ = Nothing toOObj b = OBool b instance {-# Overlapping #-} OTypeMirror String where fromOObj (OString str) = Just str fromOObj _ = Nothing toOObj str = OString str instance forall a. (OTypeMirror a) => OTypeMirror (Maybe a) where fromOObj a = Just $ fromOObj a toOObj (Just a) = toOObj a toOObj Nothing = OUndefined instance {-# Overlappable #-} forall a. (OTypeMirror a) => OTypeMirror [a] where fromOObj (OList list) = Monad.sequence . map fromOObj $ list fromOObj _ = Nothing toOObj list = OList $ map toOObj list instance forall a b. (OTypeMirror a, OTypeMirror b) => OTypeMirror (a,b) where fromOObj (OList ((fromOObj -> Just a):(fromOObj -> Just b):[])) = Just (a,b) fromOObj _ = Nothing toOObj (a,b) = OList [toOObj a, toOObj b] instance forall a b c. (OTypeMirror a, OTypeMirror b, OTypeMirror c) => OTypeMirror (a,b,c) where fromOObj (OList ((fromOObj -> Just a):(fromOObj -> Just b):(fromOObj -> Just c):[])) = Just (a,b,c) fromOObj _ = Nothing toOObj (a,b,c) = OList [toOObj a, toOObj b, toOObj c] instance forall a b. (OTypeMirror a, OTypeMirror b) => OTypeMirror (a -> b) where fromOObj (OFunc f) = Just $ \input -> let oInput = toOObj input oOutput = f oInput output = fromOObj oOutput :: Maybe b in case output of Just out -> out Nothing -> error $ "coercing OVal to a -> b isn't always safe; use a -> Maybe b" ++ " (trace: " ++ show oInput ++ " -> " ++ show oOutput ++ " )" fromOObj _ = Nothing toOObj f = OFunc $ \oObj -> case fromOObj oObj :: Maybe a of Nothing -> OError ["bad input type"] Just obj -> toOObj $ f obj instance forall a b. (OTypeMirror a, OTypeMirror b) => OTypeMirror (Either a b) where fromOObj (fromOObj -> Just (x :: a)) = Just $ Left x fromOObj (fromOObj -> Just (x :: b)) = Just $ Right x fromOObj _ = Nothing toOObj (Right x) = toOObj x toOObj (Left x) = toOObj x oTypeStr :: OVal -> [Char] oTypeStr (OUndefined) = "Undefined" oTypeStr (OBool _ ) = "Bool" oTypeStr (ONum _ ) = "Number" oTypeStr (OList _ ) = "List" oTypeStr (OString _ ) = "String" oTypeStr (OFunc _ ) = "Function" oTypeStr (OModule _ ) = "Module" oTypeStr (OError _ ) = "Error" getErrors :: OVal -> Maybe String getErrors (OError er) = Just $ head er getErrors (OList l) = Monad.msum $ map getErrors l getErrors _ = Nothing type Any = OVal caseOType = flip ($) infixr 2 <||> (<||>) :: forall desiredType out. (OTypeMirror desiredType) => (desiredType -> out) -> (OVal -> out) -> (OVal -> out) (<||>) f g = \input -> let coerceAttempt = fromOObj input :: Maybe desiredType in if isJust coerceAttempt -- ≅ (/= Nothing) but no Eq req then f $ (\(Just a) -> a) coerceAttempt else g input divideObjs :: [OVal] -> ([SymbolicObj2], [SymbolicObj3], [OVal]) divideObjs children = (map fromOObj2 . filter isOObj2 $ children, map fromOObj3 . filter isOObj3 $ children, filter (not . isOObj) $ children) where isOObj2 (OObj2 _) = True isOObj2 _ = False isOObj3 (OObj3 _) = True isOObj3 _ = False isOObj (OObj2 _) = True isOObj (OObj3 _) = True isOObj _ = False fromOObj2 (OObj2 x) = x fromOObj3 (OObj3 x) = x
silky/ImplicitCAD
Graphics/Implicit/ExtOpenScad/Util/OVal.hs
gpl-2.0
4,519
0
18
1,260
1,633
847
786
108
5
{-# OPTIONS -fglasgow-exts -fno-monomorphism-restriction #-} ---------------------------------------------------------------------------- -- | -- Module : Text.XML.Schema.SOAP11.Encoding -- Copyright : (c) Simon Foster 2004 -- License : GPL version 2 (see COPYING) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (ghc >= 6 only) -- -- Equivelant data-types and mappers required for SOAP Encoding data-types -- at http://schema.xmlsoap.org/soap/encoding. Notably SOAP Arrays and -- XML Serializers for the same. -- -- This is a work in progress. -- -- @This file is part of HAIFA.@ -- -- @HAIFA is free software; you can redistribute it and\/or modify it under the terms of the -- GNU General Public License as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version.@ -- -- @HAIFA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without -- even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details.@ -- -- @You should have received a copy of the GNU General Public License along with HAIFA; if not, -- write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA@ ---------------------------------------------------------------------------- module Text.XML.SOAP11.Encoding where import qualified Text.XML.Serializer as TXS import Data.Typeable import Data.Generics import Data.Dynamic import Data.FiniteMap import Data.Array import Text.XML.HXT.Parser thisNamespace = "http://schemas.xmlsoap.org/soap/encoding/" tns = thisNamespace defaultPrefix = "SOAP-ENC" type Array = Data.Array.Array soapArrayType = "Array"
twopoint718/haifa
src/Text/XML/SOAP11/Encoding.hs
gpl-2.0
1,801
0
5
274
108
81
27
14
1
module Test.QuickFuzz.Derive ( module Test.QuickFuzz.Derive.Actions , module Test.QuickFuzz.Derive.Arbitrary , module Test.QuickFuzz.Derive.Fixable , module Test.QuickFuzz.Derive.Mutation , module Test.QuickFuzz.Derive.Show , module Test.QuickFuzz.Derive.Generator ) where import Test.QuickFuzz.Derive.Actions import Test.QuickFuzz.Derive.Arbitrary import Test.QuickFuzz.Derive.Fixable import Test.QuickFuzz.Derive.Generator import Test.QuickFuzz.Derive.Mutation import Test.QuickFuzz.Derive.Show
elopez/QuickFuzz
src/Test/QuickFuzz/Derive.hs
gpl-3.0
558
0
5
95
99
72
27
13
0
module SpacialGameMsg.SGModelMsg where import System.Random import Control.Monad.STM import Debug.Trace import qualified PureAgentsAct as PA import qualified Data.Map as Map data SGState = Defector | Cooperator deriving (Eq, Show) data SGMsg = NeighbourPayoff (SGState, Double) | NeighbourState SGState deriving (Eq, Show) data SGAgentState = SIRSAgentState { sgCurrState :: SGState, sgPrevState :: SGState, sgLocalPayoff :: Double, sgBestPayoff :: (SGState, Double), sgNeighbourPayoffCount :: Int, sgNeighbourStateCount :: Int } deriving (Show) type SGEnvironment = () type SGAgent = PA.Agent SGMsg SGAgentState SGEnvironment type SGTransformer = PA.AgentTransformer SGMsg SGAgentState SGEnvironment type SGSimHandle = PA.SimHandle SGMsg SGAgentState SGEnvironment bParam :: Double bParam = 1.95 sParam :: Double sParam = 0.0 pParam :: Double pParam = 0.0 rParam :: Double rParam = 1.0 sgTransformer :: SGTransformer sgTransformer (a, _) PA.Start = sgStart a sgTransformer (a, e) (PA.Dt dt) = return a sgTransformer (a, e) (PA.Message (_,m)) = sgMsg a m sgStart :: SGAgent -> STM SGAgent sgStart a = (broadCastLocalState a'') where a' = resetNeighbourPayoffCount a a'' = resetNeighbourStateCount a' sgMsg :: SGAgent -> SGMsg -> STM SGAgent sgMsg a (NeighbourState s) = sgStateMsg a s sgMsg a (NeighbourPayoff p) = sgPayoffMsg a p sgStateMsg :: SGAgent -> SGState -> STM SGAgent sgStateMsg a s = do if ( allNeighboursStateCountTicked a' ) then broadCastLocalPayoff $ resetNeighbourStateCount a' else return a' where a' = tickNeighbourStateCount $ playGame a s playGame :: SGAgent -> SGState -> SGAgent playGame a s = a' where lp = sgLocalPayoff (PA.state a) poIncrease = payoffWith a s newLp = lp + poIncrease a' = PA.updateState a (\s -> s { sgLocalPayoff = newLp }) broadCastLocalPayoff :: SGAgent -> STM SGAgent broadCastLocalPayoff a = do PA.broadcastMsgToNeighbours a (NeighbourPayoff (ls, lp)) return a where ls = sgCurrState (PA.state a) lp = sgLocalPayoff (PA.state a) sgPayoffMsg :: SGAgent -> (SGState, Double) -> STM SGAgent sgPayoffMsg a p = if ( allNeighboursPayoffCountTicked a' ) then broadCastLocalState $ resetNeighbourPayoffCount $ switchToBestPayoff a' else return a' where a' = tickNeighbourPayoffCount $ comparePayoff a p comparePayoff :: SGAgent -> (SGState, Double) -> SGAgent comparePayoff a p@(_, v) | v > localV = PA.updateState a (\s -> s { sgBestPayoff = p } ) | otherwise = a where (_, localV) = sgBestPayoff (PA.state a) switchToBestPayoff :: SGAgent -> SGAgent switchToBestPayoff a = PA.updateState a (\s -> s { sgCurrState = bestState, sgPrevState = oldState, sgLocalPayoff = 0.0, sgBestPayoff = (bestState, 0.0)} ) where (bestState, _) = sgBestPayoff (PA.state a) oldState = sgCurrState (PA.state a) broadCastLocalState :: SGAgent -> STM SGAgent broadCastLocalState a = do PA.broadcastMsgToNeighbours a (NeighbourState ls) return a where ls = sgCurrState (PA.state a) -- NOTE: the first state is always the owning agent payoffWith :: SGAgent -> SGState -> Double payoffWith a s = payoff as s where as = sgCurrState (PA.state a) payoff :: SGState -> SGState -> Double payoff Defector Defector = pParam payoff Cooperator Defector = sParam payoff Defector Cooperator = bParam payoff Cooperator Cooperator = rParam allNeighboursPayoffCountTicked :: SGAgent -> Bool allNeighboursPayoffCountTicked a = nf == 0 where nf = (sgNeighbourPayoffCount (PA.state a)) allNeighboursStateCountTicked :: SGAgent -> Bool allNeighboursStateCountTicked a = nf == 0 where nf = (sgNeighbourStateCount (PA.state a)) tickNeighbourPayoffCount :: SGAgent -> SGAgent tickNeighbourPayoffCount a = PA.updateState a (\s -> s { sgNeighbourPayoffCount = nf - 1 }) where nf = (sgNeighbourPayoffCount (PA.state a)) tickNeighbourStateCount :: SGAgent -> SGAgent tickNeighbourStateCount a = PA.updateState a (\s -> s { sgNeighbourStateCount = nf - 1 }) where nf = (sgNeighbourStateCount (PA.state a)) resetNeighbourPayoffCount :: SGAgent -> SGAgent resetNeighbourPayoffCount a = PA.updateState a (\s -> s { sgNeighbourPayoffCount = neighbourCount }) where neighbourCount = Map.size (PA.neighbours a) resetNeighbourStateCount :: SGAgent -> SGAgent resetNeighbourStateCount a = PA.updateState a (\s -> s { sgNeighbourStateCount = neighbourCount }) where neighbourCount = Map.size (PA.neighbours a) createRandomSGAgents :: StdGen -> (Int, Int) -> Double -> STM ([SGAgent], StdGen) createRandomSGAgents gInit cells@(x,y) p = do as <- mapM (\idx -> PA.createAgent idx (randStates !! idx) sgTransformer) [0..n-1] let as' = map (\a -> PA.addNeighbours a (agentNeighbours a as cells) ) as return (as', g') where n = x * y (randStates, g') = createRandomStates gInit n p createRandomStates :: StdGen -> Int -> Double -> ([SGAgentState], StdGen) createRandomStates g 0 p = ([], g) createRandomStates g n p = (rands, g'') where (randState, g') = randomAgentState g p (ras, g'') = createRandomStates g' (n-1) p rands = randState : ras randomAgentState :: StdGen -> Double -> (SGAgentState, StdGen) randomAgentState g p = (SIRSAgentState{ sgCurrState = s, sgPrevState = s, sgLocalPayoff = 0.0, sgBestPayoff = (s, 0.0), sgNeighbourPayoffCount = 0, sgNeighbourStateCount = 0}, g') where (isDefector, g') = randomThresh g p (g'', _) = split g' s = if isDefector then Defector else Cooperator randomThresh :: StdGen -> Double -> (Bool, StdGen) randomThresh g p = (flag, g') where (thresh, g') = randomR(0.0, 1.0) g flag = thresh <= p agentNeighbours :: SGAgent -> [SGAgent] -> (Int, Int) -> [SGAgent] agentNeighbours a as cells = filter (\a' -> any (==(agentToCell a' cells)) neighbourCells ) as where aCell = agentToCell a cells neighbourCells = neighbours aCell agentToCell :: SGAgent -> (Int, Int) -> (Int, Int) agentToCell a (xCells, yCells) = (ax, ay) where aid = PA.agentId a ax = mod aid yCells ay = floor((fromIntegral aid) / (fromIntegral xCells)) neighbourhood :: [(Int, Int)] neighbourhood = [topLeft, top, topRight, left, center, right, bottomLeft, bottom, bottomRight] where topLeft = (-1, -1) top = (0, -1) topRight = (1, -1) left = (-1, 0) center = (0, 0) right = (1, 0) bottomLeft = (-1, 1) bottom = (0, 1) bottomRight = (1, 1) neighbours :: (Int, Int) -> [(Int, Int)] neighbours (x,y) = map (\(x', y') -> (x+x', y+y')) neighbourhood
thalerjonathan/phd
public/ArtIterating/code/haskell/PureAgentsAct/src/SpacialGameMsg/SGModelMsg.hs
gpl-3.0
7,875
0
15
2,582
2,360
1,293
1,067
158
2
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} {-| Module : Label Description : Label widget for the Minitel Copyright : (c) Frédéric BISSON, 2014 License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : POSIX This module provides a Label widget for the Minitel. A label is a simple widget displaying a line of text. -} module Minitel.UI.Label ( Justification(JLeft, JCenter, JRight) , Label(Label) , width , value , justification , doDraw ) where import Minitel.Type.MNatural (MNat) import Minitel.Type.MString (MMString) import Minitel.Generate.Generator (mLocate, mForeground, mBackground, mString) import Minitel.UI.Widget ( Widget (common, draw) , CommonAttributes (mode, posX, posY, foreground, background) ) data Justification = JLeft | JCenter | JRight deriving Eq -- | A text field widget is used to manage simple user input (an input text -- field on one line) data Label = Label CommonAttributes -- ^ Common attributes String -- ^ Text to display MNat -- ^ Width Justification -- ^ Justification (Center, Left, Right) deriving Eq width :: Label -> MNat width (Label _ _ w _) = w value :: Label -> String value (Label _ s _ _) = s justification :: Label -> Justification justification (Label _ _ _ j) = j instance Widget Label where common (Label cm _ _ _) = cm draw widget = return $ doDraw widget doDraw :: Label -> MMString doDraw lb = Just [ mLocate (posX c) (posY c) , mForeground (foreground c) , mBackground (background c) , mString (mode c) (value lb) ] where c = common lb
Zigazou/HaMinitel
src/Minitel/UI/Label.hs
gpl-3.0
1,778
0
9
497
379
221
158
41
1
{-# LANGUAGE PackageImports #-} import "WebShelf" Application (getApplicationDev) import Network.Wai.Handler.Warp (runSettings, defaultSettings, settingsPort) import Control.Concurrent (forkIO) import System.Directory (doesFileExist, removeFile) import System.Exit (exitSuccess) import Control.Concurrent (threadDelay) main :: IO () main = do putStrLn "Starting devel application" (port, app) <- getApplicationDev forkIO $ runSettings defaultSettings { settingsPort = port } app loop loop :: IO () loop = do threadDelay 100000 e <- doesFileExist "yesod-devel/devel-terminate" if e then terminateDevel else loop terminateDevel :: IO () terminateDevel = exitSuccess
k-bx/web_shelf
WebShelf/devel.hs
gpl-3.0
709
0
10
123
186
101
85
23
2
import System.Exit import Test.HUnit import BlackJack import TestDecks tests = [ TestCase $ assertEqual "value of King" 10 (getValueCard (Card Hearts King)) , TestCase $ assertEqual "blackjack" 21 (getValueHand [Card Hearts King, Card Clubs Nine, Card Spades Two]), TestCase $ assertEqual "a deck should have 52 cards" 52 (length createDeck), TestCase $ assertEqual "a deck have a total value of" 380 (getValueHand createDeck), TestCase $ assertEqual "picking a card" (Card Hearts King, tail createDeck) (pickCard createDeck), TestCase $ assertEqual "picking a card consumes a card in the deck" 51 (length $ snd $ pickCard createDeck), TestCase $ assertEqual "picking the last card" (Card Clubs Ace, []) (pickCard [Card Clubs Ace]), TestCase $ do deck <- shuffle createDeck assertEqual "shuffle deck have 52 cards" 52 (length deck) assertBool "shuffled deck not equal to unshuffled deck" (createDeck /= deck) , TestCase $ do let deck1 = createDeck let (card1, deck2) = pickCard deck1 let (card2, deck3) = pickCard deck2 let dealerHand = [card1, card2] let (card3, deck4) = pickCard deck3 let (card4, deck5) = pickCard deck4 let (card5, deck6) = pickCard deck5 let playerHand = [card3, card4, card5] assertEqual "dealer score is" 20 (getValueHand dealerHand) assertBool "dealer should stop" (shouldDealerStop dealerHand) assertEqual "player score is" 29 (getValueHand playerHand) assertEqual "house wins" House (getWinner playerHand dealerHand) , TestCase $ do let initDeck = test_deck_1 let initHand = [] :: Hand let (dealerHand, deck) = dealerFinishPlay initHand initDeck assertEqual "dealers score is " 18 (getValueHand dealerHand) let (dealerHand2, deck2) = dealerFinishPlay initHand deck assertEqual "dealers score is " 21 (getValueHand dealerHand2) let (dealerHand3, deck3) = dealerFinishPlay initHand deck2 assertEqual "dealers score is " 27 (getValueHand dealerHand3) , TestCase $ do let initDeck = test_deck_1 let (dealerHand1, deck1) = pickCards initDeck 1 assertEqual "dealers score is " 6 (getValueHand dealerHand1) let (playerHand1, deck2) = pickCards deck1 1 assertEqual "player score is " 10 (getValueHand playerHand1) let (playerDrawnCard1, deck3) = pickCard deck2 let playerHand2 = playerDrawnCard1 : playerHand1 assertEqual "player score is " 12 (getValueHand playerHand2) let (playerDrawnCard2, deck4) = pickCard deck3 let playerHand3 = playerDrawnCard2 : playerHand2 assertEqual "player score is BUSTED!" 22 (getValueHand playerHand3) let (dealerHand2, deck5) = dealerFinishPlay dealerHand1 deck4 assertEqual "dealers score is " 22 (getValueHand dealerHand2) assertEqual "house wins" House (getWinner playerHand3 dealerHand2) assertEqual "player stoped earlier.." Player (getWinner playerHand2 dealerHand2) let score_board = "Score: 22\n" ++ "Hand: [King of Dimonds,Two of Spades,King of Clubs]" assertEqual "scoreBoard is.." score_board (scoreBoard playerHand3) ] main = do result <- runTestTT $ TestList tests let errs = errors result fails = failures result System.Exit.exitWith (codeGet errs fails) codeGet errs fails | fails > 0 = ExitFailure 2 | errs > 0 = ExitFailure 1 | otherwise = ExitSuccess
Norberg/cardgame
test/BlackJackTest.hs
gpl-3.0
3,687
0
12
1,009
1,026
487
539
74
1
module REPL (runREPL) where import Control.Monad.IO.Class (liftIO) import Data.Text (pack) import System.Console.Haskeline import Hython.Interpreter (defaultInterpreterState, interpret) runREPL :: IO () runREPL = do state <- defaultInterpreterState "<repl>" runInputT settings (loop state) where loop state = do input <- getInputLine ">>> " case input of Nothing -> return () Just "quit()" -> return () Just line -> do (result, newState) <- liftIO $ interpret state (pack line) case result of Left s -> outputStrLn s Right strs -> mapM_ outputStrLn strs loop newState settings = defaultSettings { historyFile = Just ".hython_history" }
mattgreen/hython
src/REPL.hs
gpl-3.0
816
0
18
271
233
116
117
21
4
module Mescaline.Sampler.Keyboard where import Control.Concurrent.Chan import Control.Monad.Trans (liftIO) import Data.IORef import Data.Map (Map) import qualified Data.Map as Map import Graphics.UI.Gtk.Gdk.EventM -- import Graphics.UI.Gtk (Event) -- import qualified Graphics.UI.Gtk.Gdk.Events as G import qualified Graphics.UI.Gtk.Gdk.Keys as G -- import qualified Graphics.UI.Gtk as G mkKeyMap :: [(String, EventM EKey Bool)] -> EventM EKey Bool mkKeyMap keys = do m <- flip Map.lookup keyMap `fmap` eventKeyVal case m of Nothing -> return False Just a -> a where keyMap = Map.fromList (map (\(kn, m) -> (G.keyFromName kn, m)) keys) suppressRepeatedKeys :: EventM EKey Bool -> IO (EventM EKey Bool) suppressRepeatedKeys a = do prevEventRef <- newIORef Nothing return $ do prevEvent <- liftIO $ readIORef prevEventRef case prevEvent of Nothing -> do val <- eventKeyVal mods <- eventModifierAll write prevEventRef (val, mods) a Just (val, mods) -> do val' <- eventKeyVal mods' <- eventModifierAll if val == val' && mods == mods' then return False else do write prevEventRef (val', mods') a where write r x = liftIO $ writeIORef r $ Just x
kaoskorobase/mescaline
tools/sampler/Mescaline/Sampler/Keyboard.hs
gpl-3.0
1,518
2
19
548
404
211
193
35
3
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeSynonymInstances #-} -- | WIP module Test.RSCoin.Pure.Update ( Update (..) , execUpdate , runUpdate , execUpdateSafe , runUpdateSafe ) where import Control.Exception (Exception, fromException, throw) import Control.Monad.Catch (MonadThrow (throwM), SomeException (..)) import Control.Monad.Except (runExceptT) import Control.Monad.Reader (MonadReader (ask, local)) import Control.Monad.State (State, get, modify, runState) import Control.Monad.State.Class (MonadState) import Control.Monad.Trans.Except (ExceptT, throwE) newtype Update e s a = Update { getUpdate :: ExceptT e (State s) a } deriving (MonadState s, Monad, Applicative, Functor) instance MonadReader s (Update e s) where ask = get local f m = modify f >> m instance Exception e => MonadThrow (Update e s) where throwM e = Update . maybe (throw e') throwE $ fromException e' where e' = SomeException e execUpdate :: Exception e => Update e s a -> s -> s execUpdate u = snd . runUpdate u runUpdate :: Exception e => Update e s a -> s -> (a, s) runUpdate upd storage = either throw (, newStorage) res where (res, newStorage) = runState (runExceptT $ getUpdate upd) storage execUpdateSafe :: (MonadThrow m, Exception e) => Update e s a -> s -> m s execUpdateSafe upd storage = snd <$> runUpdateSafe upd storage runUpdateSafe :: (MonadThrow m, Exception e) => Update e s a -> s -> m (a, s) runUpdateSafe upd storage = either throwM (return . (, newStorage)) res where (res, newStorage) = runState (runExceptT $ getUpdate upd) storage
input-output-hk/rscoin-haskell
test/Test/RSCoin/Pure/Update.hs
gpl-3.0
2,065
0
10
572
587
327
260
41
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Classroom.Types.Product -- 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.Classroom.Types.Product where import Network.Google.Classroom.Types.Sum import Network.Google.Prelude -- | Response when listing course aliases. -- -- /See:/ 'listCourseAliasesResponse' smart constructor. data ListCourseAliasesResponse = ListCourseAliasesResponse' { _lcarNextPageToken :: !(Maybe Text) , _lcarAliases :: !(Maybe [CourseAlias]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ListCourseAliasesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lcarNextPageToken' -- -- * 'lcarAliases' listCourseAliasesResponse :: ListCourseAliasesResponse listCourseAliasesResponse = ListCourseAliasesResponse' { _lcarNextPageToken = Nothing , _lcarAliases = Nothing } -- | Token identifying the next page of results to return. If empty, no -- further results are available. lcarNextPageToken :: Lens' ListCourseAliasesResponse (Maybe Text) lcarNextPageToken = lens _lcarNextPageToken (\ s a -> s{_lcarNextPageToken = a}) -- | The course aliases. lcarAliases :: Lens' ListCourseAliasesResponse [CourseAlias] lcarAliases = lens _lcarAliases (\ s a -> s{_lcarAliases = a}) . _Default . _Coerce instance FromJSON ListCourseAliasesResponse where parseJSON = withObject "ListCourseAliasesResponse" (\ o -> ListCourseAliasesResponse' <$> (o .:? "nextPageToken") <*> (o .:? "aliases" .!= mempty)) instance ToJSON ListCourseAliasesResponse where toJSON ListCourseAliasesResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lcarNextPageToken, ("aliases" .=) <$> _lcarAliases]) -- | Course work created by a teacher for students of the course. -- -- /See:/ 'courseWork' smart constructor. data CourseWork = CourseWork' { _cwCreationTime :: !(Maybe Text) , _cwState :: !(Maybe Text) , _cwMaterials :: !(Maybe [Material]) , _cwCourseId :: !(Maybe Text) , _cwMaxPoints :: !(Maybe (Textual Double)) , _cwWorkType :: !(Maybe Text) , _cwDueTime :: !(Maybe TimeOfDay') , _cwAssociatedWithDeveloper :: !(Maybe Bool) , _cwUpdateTime :: !(Maybe Text) , _cwMultipleChoiceQuestion :: !(Maybe MultipleChoiceQuestion) , _cwId :: !(Maybe Text) , _cwSubmissionModificationMode :: !(Maybe Text) , _cwDueDate :: !(Maybe Date) , _cwTitle :: !(Maybe Text) , _cwAlternateLink :: !(Maybe Text) , _cwAssignment :: !(Maybe Assignment) , _cwDescription :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CourseWork' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cwCreationTime' -- -- * 'cwState' -- -- * 'cwMaterials' -- -- * 'cwCourseId' -- -- * 'cwMaxPoints' -- -- * 'cwWorkType' -- -- * 'cwDueTime' -- -- * 'cwAssociatedWithDeveloper' -- -- * 'cwUpdateTime' -- -- * 'cwMultipleChoiceQuestion' -- -- * 'cwId' -- -- * 'cwSubmissionModificationMode' -- -- * 'cwDueDate' -- -- * 'cwTitle' -- -- * 'cwAlternateLink' -- -- * 'cwAssignment' -- -- * 'cwDescription' courseWork :: CourseWork courseWork = CourseWork' { _cwCreationTime = Nothing , _cwState = Nothing , _cwMaterials = Nothing , _cwCourseId = Nothing , _cwMaxPoints = Nothing , _cwWorkType = Nothing , _cwDueTime = Nothing , _cwAssociatedWithDeveloper = Nothing , _cwUpdateTime = Nothing , _cwMultipleChoiceQuestion = Nothing , _cwId = Nothing , _cwSubmissionModificationMode = Nothing , _cwDueDate = Nothing , _cwTitle = Nothing , _cwAlternateLink = Nothing , _cwAssignment = Nothing , _cwDescription = Nothing } -- | Timestamp when this course work was created. Read-only. cwCreationTime :: Lens' CourseWork (Maybe Text) cwCreationTime = lens _cwCreationTime (\ s a -> s{_cwCreationTime = a}) -- | Status of this course work. If unspecified, the default state is -- \`DRAFT\`. cwState :: Lens' CourseWork (Maybe Text) cwState = lens _cwState (\ s a -> s{_cwState = a}) -- | Additional materials. CourseWork must have no more than 20 material -- items. cwMaterials :: Lens' CourseWork [Material] cwMaterials = lens _cwMaterials (\ s a -> s{_cwMaterials = a}) . _Default . _Coerce -- | Identifier of the course. Read-only. cwCourseId :: Lens' CourseWork (Maybe Text) cwCourseId = lens _cwCourseId (\ s a -> s{_cwCourseId = a}) -- | Maximum grade for this course work. If zero or unspecified, this -- assignment is considered ungraded. This must be a non-negative integer -- value. cwMaxPoints :: Lens' CourseWork (Maybe Double) cwMaxPoints = lens _cwMaxPoints (\ s a -> s{_cwMaxPoints = a}) . mapping _Coerce -- | Type of this course work. The type is set when the course work is -- created and cannot be changed. cwWorkType :: Lens' CourseWork (Maybe Text) cwWorkType = lens _cwWorkType (\ s a -> s{_cwWorkType = a}) -- | Optional time of day, in UTC, that submissions for this this course work -- are due. This must be specified if \`due_date\` is specified. cwDueTime :: Lens' CourseWork (Maybe TimeOfDay') cwDueTime = lens _cwDueTime (\ s a -> s{_cwDueTime = a}) -- | Whether this course work item is associated with the Developer Console -- project making the request. See google.classroom.Work.CreateCourseWork -- for more details. Read-only. cwAssociatedWithDeveloper :: Lens' CourseWork (Maybe Bool) cwAssociatedWithDeveloper = lens _cwAssociatedWithDeveloper (\ s a -> s{_cwAssociatedWithDeveloper = a}) -- | Timestamp of the most recent change to this course work. Read-only. cwUpdateTime :: Lens' CourseWork (Maybe Text) cwUpdateTime = lens _cwUpdateTime (\ s a -> s{_cwUpdateTime = a}) -- | Multiple choice question details. For read operations, this field is -- populated only when \`work_type\` is \`MULTIPLE_CHOICE_QUESTION\`. For -- write operations, this field must be specified when creating course work -- with a \`work_type\` of \`MULTIPLE_CHOICE_QUESTION\`, and it must not be -- set otherwise. cwMultipleChoiceQuestion :: Lens' CourseWork (Maybe MultipleChoiceQuestion) cwMultipleChoiceQuestion = lens _cwMultipleChoiceQuestion (\ s a -> s{_cwMultipleChoiceQuestion = a}) -- | Classroom-assigned identifier of this course work, unique per course. -- Read-only. cwId :: Lens' CourseWork (Maybe Text) cwId = lens _cwId (\ s a -> s{_cwId = a}) -- | Setting to determine when students are allowed to modify submissions. If -- unspecified, the default value is \`MODIFIABLE_UNTIL_TURNED_IN\`. cwSubmissionModificationMode :: Lens' CourseWork (Maybe Text) cwSubmissionModificationMode = lens _cwSubmissionModificationMode (\ s a -> s{_cwSubmissionModificationMode = a}) -- | Optional date, in UTC, that submissions for this this course work are -- due. This must be specified if \`due_time\` is specified. cwDueDate :: Lens' CourseWork (Maybe Date) cwDueDate = lens _cwDueDate (\ s a -> s{_cwDueDate = a}) -- | Title of this course work. The title must be a valid UTF-8 string -- containing between 1 and 3000 characters. cwTitle :: Lens' CourseWork (Maybe Text) cwTitle = lens _cwTitle (\ s a -> s{_cwTitle = a}) -- | Absolute link to this course work in the Classroom web UI. This is only -- populated if \`state\` is \`PUBLISHED\`. Read-only. cwAlternateLink :: Lens' CourseWork (Maybe Text) cwAlternateLink = lens _cwAlternateLink (\ s a -> s{_cwAlternateLink = a}) -- | Assignment details. This is populated only when \`work_type\` is -- \`ASSIGNMENT\`. Read-only. cwAssignment :: Lens' CourseWork (Maybe Assignment) cwAssignment = lens _cwAssignment (\ s a -> s{_cwAssignment = a}) -- | Optional description of this course work. If set, the description must -- be a valid UTF-8 string containing no more than 30,000 characters. cwDescription :: Lens' CourseWork (Maybe Text) cwDescription = lens _cwDescription (\ s a -> s{_cwDescription = a}) instance FromJSON CourseWork where parseJSON = withObject "CourseWork" (\ o -> CourseWork' <$> (o .:? "creationTime") <*> (o .:? "state") <*> (o .:? "materials" .!= mempty) <*> (o .:? "courseId") <*> (o .:? "maxPoints") <*> (o .:? "workType") <*> (o .:? "dueTime") <*> (o .:? "associatedWithDeveloper") <*> (o .:? "updateTime") <*> (o .:? "multipleChoiceQuestion") <*> (o .:? "id") <*> (o .:? "submissionModificationMode") <*> (o .:? "dueDate") <*> (o .:? "title") <*> (o .:? "alternateLink") <*> (o .:? "assignment") <*> (o .:? "description")) instance ToJSON CourseWork where toJSON CourseWork'{..} = object (catMaybes [("creationTime" .=) <$> _cwCreationTime, ("state" .=) <$> _cwState, ("materials" .=) <$> _cwMaterials, ("courseId" .=) <$> _cwCourseId, ("maxPoints" .=) <$> _cwMaxPoints, ("workType" .=) <$> _cwWorkType, ("dueTime" .=) <$> _cwDueTime, ("associatedWithDeveloper" .=) <$> _cwAssociatedWithDeveloper, ("updateTime" .=) <$> _cwUpdateTime, ("multipleChoiceQuestion" .=) <$> _cwMultipleChoiceQuestion, ("id" .=) <$> _cwId, ("submissionModificationMode" .=) <$> _cwSubmissionModificationMode, ("dueDate" .=) <$> _cwDueDate, ("title" .=) <$> _cwTitle, ("alternateLink" .=) <$> _cwAlternateLink, ("assignment" .=) <$> _cwAssignment, ("description" .=) <$> _cwDescription]) -- | Representation of a Google Drive file. -- -- /See:/ 'driveFile' smart constructor. data DriveFile = DriveFile' { _dfThumbnailURL :: !(Maybe Text) , _dfId :: !(Maybe Text) , _dfTitle :: !(Maybe Text) , _dfAlternateLink :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DriveFile' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dfThumbnailURL' -- -- * 'dfId' -- -- * 'dfTitle' -- -- * 'dfAlternateLink' driveFile :: DriveFile driveFile = DriveFile' { _dfThumbnailURL = Nothing , _dfId = Nothing , _dfTitle = Nothing , _dfAlternateLink = Nothing } -- | URL of a thumbnail image of the Drive item. Read-only. dfThumbnailURL :: Lens' DriveFile (Maybe Text) dfThumbnailURL = lens _dfThumbnailURL (\ s a -> s{_dfThumbnailURL = a}) -- | Drive API resource ID. dfId :: Lens' DriveFile (Maybe Text) dfId = lens _dfId (\ s a -> s{_dfId = a}) -- | Title of the Drive item. Read-only. dfTitle :: Lens' DriveFile (Maybe Text) dfTitle = lens _dfTitle (\ s a -> s{_dfTitle = a}) -- | URL that can be used to access the Drive item. Read-only. dfAlternateLink :: Lens' DriveFile (Maybe Text) dfAlternateLink = lens _dfAlternateLink (\ s a -> s{_dfAlternateLink = a}) instance FromJSON DriveFile where parseJSON = withObject "DriveFile" (\ o -> DriveFile' <$> (o .:? "thumbnailUrl") <*> (o .:? "id") <*> (o .:? "title") <*> (o .:? "alternateLink")) instance ToJSON DriveFile where toJSON DriveFile'{..} = object (catMaybes [("thumbnailUrl" .=) <$> _dfThumbnailURL, ("id" .=) <$> _dfId, ("title" .=) <$> _dfTitle, ("alternateLink" .=) <$> _dfAlternateLink]) -- | An invitation to become the guardian of a specified user, sent to a -- specified email address. -- -- /See:/ 'guardianInvitation' smart constructor. data GuardianInvitation = GuardianInvitation' { _giCreationTime :: !(Maybe Text) , _giStudentId :: !(Maybe Text) , _giState :: !(Maybe Text) , _giInvitationId :: !(Maybe Text) , _giInvitedEmailAddress :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'GuardianInvitation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'giCreationTime' -- -- * 'giStudentId' -- -- * 'giState' -- -- * 'giInvitationId' -- -- * 'giInvitedEmailAddress' guardianInvitation :: GuardianInvitation guardianInvitation = GuardianInvitation' { _giCreationTime = Nothing , _giStudentId = Nothing , _giState = Nothing , _giInvitationId = Nothing , _giInvitedEmailAddress = Nothing } -- | The time that this invitation was created. Read-only. giCreationTime :: Lens' GuardianInvitation (Maybe Text) giCreationTime = lens _giCreationTime (\ s a -> s{_giCreationTime = a}) -- | ID of the student (in standard format) giStudentId :: Lens' GuardianInvitation (Maybe Text) giStudentId = lens _giStudentId (\ s a -> s{_giStudentId = a}) -- | The state that this invitation is in. giState :: Lens' GuardianInvitation (Maybe Text) giState = lens _giState (\ s a -> s{_giState = a}) -- | Unique identifier for this invitation. Read-only. giInvitationId :: Lens' GuardianInvitation (Maybe Text) giInvitationId = lens _giInvitationId (\ s a -> s{_giInvitationId = a}) -- | Email address that the invitation was sent to. This field is only -- visible to domain administrators. giInvitedEmailAddress :: Lens' GuardianInvitation (Maybe Text) giInvitedEmailAddress = lens _giInvitedEmailAddress (\ s a -> s{_giInvitedEmailAddress = a}) instance FromJSON GuardianInvitation where parseJSON = withObject "GuardianInvitation" (\ o -> GuardianInvitation' <$> (o .:? "creationTime") <*> (o .:? "studentId") <*> (o .:? "state") <*> (o .:? "invitationId") <*> (o .:? "invitedEmailAddress")) instance ToJSON GuardianInvitation where toJSON GuardianInvitation'{..} = object (catMaybes [("creationTime" .=) <$> _giCreationTime, ("studentId" .=) <$> _giStudentId, ("state" .=) <$> _giState, ("invitationId" .=) <$> _giInvitationId, ("invitedEmailAddress" .=) <$> _giInvitedEmailAddress]) -- | Request to return a student submission. -- -- /See:/ 'returnStudentSubmissionRequest' smart constructor. data ReturnStudentSubmissionRequest = ReturnStudentSubmissionRequest' deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ReturnStudentSubmissionRequest' with the minimum fields required to make a request. -- returnStudentSubmissionRequest :: ReturnStudentSubmissionRequest returnStudentSubmissionRequest = ReturnStudentSubmissionRequest' instance FromJSON ReturnStudentSubmissionRequest where parseJSON = withObject "ReturnStudentSubmissionRequest" (\ o -> pure ReturnStudentSubmissionRequest') instance ToJSON ReturnStudentSubmissionRequest where toJSON = const emptyObject -- | Request to reclaim a student submission. -- -- /See:/ 'reclaimStudentSubmissionRequest' smart constructor. data ReclaimStudentSubmissionRequest = ReclaimStudentSubmissionRequest' deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ReclaimStudentSubmissionRequest' with the minimum fields required to make a request. -- reclaimStudentSubmissionRequest :: ReclaimStudentSubmissionRequest reclaimStudentSubmissionRequest = ReclaimStudentSubmissionRequest' instance FromJSON ReclaimStudentSubmissionRequest where parseJSON = withObject "ReclaimStudentSubmissionRequest" (\ o -> pure ReclaimStudentSubmissionRequest') instance ToJSON ReclaimStudentSubmissionRequest where toJSON = const emptyObject -- | Response when listing course work. -- -- /See:/ 'listCourseWorkResponse' smart constructor. data ListCourseWorkResponse = ListCourseWorkResponse' { _lcwrCourseWork :: !(Maybe [CourseWork]) , _lcwrNextPageToken :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ListCourseWorkResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lcwrCourseWork' -- -- * 'lcwrNextPageToken' listCourseWorkResponse :: ListCourseWorkResponse listCourseWorkResponse = ListCourseWorkResponse' { _lcwrCourseWork = Nothing , _lcwrNextPageToken = Nothing } -- | Course work items that match the request. lcwrCourseWork :: Lens' ListCourseWorkResponse [CourseWork] lcwrCourseWork = lens _lcwrCourseWork (\ s a -> s{_lcwrCourseWork = a}) . _Default . _Coerce -- | Token identifying the next page of results to return. If empty, no -- further results are available. lcwrNextPageToken :: Lens' ListCourseWorkResponse (Maybe Text) lcwrNextPageToken = lens _lcwrNextPageToken (\ s a -> s{_lcwrNextPageToken = a}) instance FromJSON ListCourseWorkResponse where parseJSON = withObject "ListCourseWorkResponse" (\ o -> ListCourseWorkResponse' <$> (o .:? "courseWork" .!= mempty) <*> (o .:? "nextPageToken")) instance ToJSON ListCourseWorkResponse where toJSON ListCourseWorkResponse'{..} = object (catMaybes [("courseWork" .=) <$> _lcwrCourseWork, ("nextPageToken" .=) <$> _lcwrNextPageToken]) -- | A generic empty message that you can re-use to avoid defining duplicated -- empty messages in your APIs. A typical example is to use it as the -- request or the response type of an API method. For instance: service Foo -- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The -- JSON representation for \`Empty\` is empty JSON object \`{}\`. -- -- /See:/ 'empty' smart constructor. data Empty = Empty' deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Empty' with the minimum fields required to make a request. -- empty :: Empty empty = Empty' instance FromJSON Empty where parseJSON = withObject "Empty" (\ o -> pure Empty') instance ToJSON Empty where toJSON = const emptyObject -- | Global user permission description. -- -- /See:/ 'globalPermission' smart constructor. newtype GlobalPermission = GlobalPermission' { _gpPermission :: Maybe Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'GlobalPermission' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gpPermission' globalPermission :: GlobalPermission globalPermission = GlobalPermission' { _gpPermission = Nothing } -- | Permission value. gpPermission :: Lens' GlobalPermission (Maybe Text) gpPermission = lens _gpPermission (\ s a -> s{_gpPermission = a}) instance FromJSON GlobalPermission where parseJSON = withObject "GlobalPermission" (\ o -> GlobalPermission' <$> (o .:? "permission")) instance ToJSON GlobalPermission where toJSON GlobalPermission'{..} = object (catMaybes [("permission" .=) <$> _gpPermission]) -- | URL item. -- -- /See:/ 'link' smart constructor. data Link = Link' { _lThumbnailURL :: !(Maybe Text) , _lURL :: !(Maybe Text) , _lTitle :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Link' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lThumbnailURL' -- -- * 'lURL' -- -- * 'lTitle' link :: Link link = Link' { _lThumbnailURL = Nothing , _lURL = Nothing , _lTitle = Nothing } -- | URL of a thumbnail image of the target URL. Read-only. lThumbnailURL :: Lens' Link (Maybe Text) lThumbnailURL = lens _lThumbnailURL (\ s a -> s{_lThumbnailURL = a}) -- | URL to link to. This must be a valid UTF-8 string containing between 1 -- and 2024 characters. lURL :: Lens' Link (Maybe Text) lURL = lens _lURL (\ s a -> s{_lURL = a}) -- | Title of the target of the URL. Read-only. lTitle :: Lens' Link (Maybe Text) lTitle = lens _lTitle (\ s a -> s{_lTitle = a}) instance FromJSON Link where parseJSON = withObject "Link" (\ o -> Link' <$> (o .:? "thumbnailUrl") <*> (o .:? "url") <*> (o .:? "title")) instance ToJSON Link where toJSON Link'{..} = object (catMaybes [("thumbnailUrl" .=) <$> _lThumbnailURL, ("url" .=) <$> _lURL, ("title" .=) <$> _lTitle]) -- | Student work for an assignment. -- -- /See:/ 'assignmentSubmission' smart constructor. newtype AssignmentSubmission = AssignmentSubmission' { _asAttachments :: Maybe [Attachment] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AssignmentSubmission' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asAttachments' assignmentSubmission :: AssignmentSubmission assignmentSubmission = AssignmentSubmission' { _asAttachments = Nothing } -- | Attachments added by the student. Drive files that correspond to -- materials with a share mode of STUDENT_COPY may not exist yet if the -- student has not accessed the assignment in Classroom. Some attachment -- metadata is only populated if the requesting user has permission to -- access it. Identifier and alternate_link fields are always available, -- but others (e.g. title) may not be. asAttachments :: Lens' AssignmentSubmission [Attachment] asAttachments = lens _asAttachments (\ s a -> s{_asAttachments = a}) . _Default . _Coerce instance FromJSON AssignmentSubmission where parseJSON = withObject "AssignmentSubmission" (\ o -> AssignmentSubmission' <$> (o .:? "attachments" .!= mempty)) instance ToJSON AssignmentSubmission where toJSON AssignmentSubmission'{..} = object (catMaybes [("attachments" .=) <$> _asAttachments]) -- | Request to modify the attachments of a student submission. -- -- /See:/ 'modifyAttachmentsRequest' smart constructor. newtype ModifyAttachmentsRequest = ModifyAttachmentsRequest' { _marAddAttachments :: Maybe [Attachment] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ModifyAttachmentsRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'marAddAttachments' modifyAttachmentsRequest :: ModifyAttachmentsRequest modifyAttachmentsRequest = ModifyAttachmentsRequest' { _marAddAttachments = Nothing } -- | Attachments to add. A student submission may not have more than 20 -- attachments. Form attachments are not supported. marAddAttachments :: Lens' ModifyAttachmentsRequest [Attachment] marAddAttachments = lens _marAddAttachments (\ s a -> s{_marAddAttachments = a}) . _Default . _Coerce instance FromJSON ModifyAttachmentsRequest where parseJSON = withObject "ModifyAttachmentsRequest" (\ o -> ModifyAttachmentsRequest' <$> (o .:? "addAttachments" .!= mempty)) instance ToJSON ModifyAttachmentsRequest where toJSON ModifyAttachmentsRequest'{..} = object (catMaybes [("addAttachments" .=) <$> _marAddAttachments]) -- | Response when listing student submissions. -- -- /See:/ 'listStudentSubmissionsResponse' smart constructor. data ListStudentSubmissionsResponse = ListStudentSubmissionsResponse' { _lssrNextPageToken :: !(Maybe Text) , _lssrStudentSubmissions :: !(Maybe [StudentSubmission]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ListStudentSubmissionsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lssrNextPageToken' -- -- * 'lssrStudentSubmissions' listStudentSubmissionsResponse :: ListStudentSubmissionsResponse listStudentSubmissionsResponse = ListStudentSubmissionsResponse' { _lssrNextPageToken = Nothing , _lssrStudentSubmissions = Nothing } -- | Token identifying the next page of results to return. If empty, no -- further results are available. lssrNextPageToken :: Lens' ListStudentSubmissionsResponse (Maybe Text) lssrNextPageToken = lens _lssrNextPageToken (\ s a -> s{_lssrNextPageToken = a}) -- | Student work that matches the request. lssrStudentSubmissions :: Lens' ListStudentSubmissionsResponse [StudentSubmission] lssrStudentSubmissions = lens _lssrStudentSubmissions (\ s a -> s{_lssrStudentSubmissions = a}) . _Default . _Coerce instance FromJSON ListStudentSubmissionsResponse where parseJSON = withObject "ListStudentSubmissionsResponse" (\ o -> ListStudentSubmissionsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "studentSubmissions" .!= mempty)) instance ToJSON ListStudentSubmissionsResponse where toJSON ListStudentSubmissionsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lssrNextPageToken, ("studentSubmissions" .=) <$> _lssrStudentSubmissions]) -- | Material attached to course work. When creating attachments, setting the -- \`form\` field is not supported. -- -- /See:/ 'material' smart constructor. data Material = Material' { _mDriveFile :: !(Maybe SharedDriveFile) , _mLink :: !(Maybe Link) , _mYouTubeVideo :: !(Maybe YouTubeVideo) , _mForm :: !(Maybe Form) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Material' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mDriveFile' -- -- * 'mLink' -- -- * 'mYouTubeVideo' -- -- * 'mForm' material :: Material material = Material' { _mDriveFile = Nothing , _mLink = Nothing , _mYouTubeVideo = Nothing , _mForm = Nothing } -- | Google Drive file material. mDriveFile :: Lens' Material (Maybe SharedDriveFile) mDriveFile = lens _mDriveFile (\ s a -> s{_mDriveFile = a}) -- | Link material. On creation, will be upgraded to a more appropriate type -- if possible, and this will be reflected in the response. mLink :: Lens' Material (Maybe Link) mLink = lens _mLink (\ s a -> s{_mLink = a}) -- | YouTube video material. mYouTubeVideo :: Lens' Material (Maybe YouTubeVideo) mYouTubeVideo = lens _mYouTubeVideo (\ s a -> s{_mYouTubeVideo = a}) -- | Google Forms material. mForm :: Lens' Material (Maybe Form) mForm = lens _mForm (\ s a -> s{_mForm = a}) instance FromJSON Material where parseJSON = withObject "Material" (\ o -> Material' <$> (o .:? "driveFile") <*> (o .:? "link") <*> (o .:? "youtubeVideo") <*> (o .:? "form")) instance ToJSON Material where toJSON Material'{..} = object (catMaybes [("driveFile" .=) <$> _mDriveFile, ("link" .=) <$> _mLink, ("youtubeVideo" .=) <$> _mYouTubeVideo, ("form" .=) <$> _mForm]) -- | Student work for a multiple-choice question. -- -- /See:/ 'multipleChoiceSubmission' smart constructor. newtype MultipleChoiceSubmission = MultipleChoiceSubmission' { _mcsAnswer :: Maybe Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'MultipleChoiceSubmission' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mcsAnswer' multipleChoiceSubmission :: MultipleChoiceSubmission multipleChoiceSubmission = MultipleChoiceSubmission' { _mcsAnswer = Nothing } -- | Student\'s select choice. mcsAnswer :: Lens' MultipleChoiceSubmission (Maybe Text) mcsAnswer = lens _mcsAnswer (\ s a -> s{_mcsAnswer = a}) instance FromJSON MultipleChoiceSubmission where parseJSON = withObject "MultipleChoiceSubmission" (\ o -> MultipleChoiceSubmission' <$> (o .:? "answer")) instance ToJSON MultipleChoiceSubmission where toJSON MultipleChoiceSubmission'{..} = object (catMaybes [("answer" .=) <$> _mcsAnswer]) -- | Response when listing invitations. -- -- /See:/ 'listInvitationsResponse' smart constructor. data ListInvitationsResponse = ListInvitationsResponse' { _lirNextPageToken :: !(Maybe Text) , _lirInvitations :: !(Maybe [Invitation]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ListInvitationsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lirNextPageToken' -- -- * 'lirInvitations' listInvitationsResponse :: ListInvitationsResponse listInvitationsResponse = ListInvitationsResponse' { _lirNextPageToken = Nothing , _lirInvitations = Nothing } -- | Token identifying the next page of results to return. If empty, no -- further results are available. lirNextPageToken :: Lens' ListInvitationsResponse (Maybe Text) lirNextPageToken = lens _lirNextPageToken (\ s a -> s{_lirNextPageToken = a}) -- | Invitations that match the list request. lirInvitations :: Lens' ListInvitationsResponse [Invitation] lirInvitations = lens _lirInvitations (\ s a -> s{_lirInvitations = a}) . _Default . _Coerce instance FromJSON ListInvitationsResponse where parseJSON = withObject "ListInvitationsResponse" (\ o -> ListInvitationsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "invitations" .!= mempty)) instance ToJSON ListInvitationsResponse where toJSON ListInvitationsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lirNextPageToken, ("invitations" .=) <$> _lirInvitations]) -- | Association between a student and a guardian of that student. The -- guardian may receive information about the student\'s course work. -- -- /See:/ 'guardian' smart constructor. data Guardian = Guardian' { _gStudentId :: !(Maybe Text) , _gGuardianId :: !(Maybe Text) , _gInvitedEmailAddress :: !(Maybe Text) , _gGuardianProFile :: !(Maybe UserProFile) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Guardian' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gStudentId' -- -- * 'gGuardianId' -- -- * 'gInvitedEmailAddress' -- -- * 'gGuardianProFile' guardian :: Guardian guardian = Guardian' { _gStudentId = Nothing , _gGuardianId = Nothing , _gInvitedEmailAddress = Nothing , _gGuardianProFile = Nothing } -- | Identifier for the student to whom the guardian relationship applies. gStudentId :: Lens' Guardian (Maybe Text) gStudentId = lens _gStudentId (\ s a -> s{_gStudentId = a}) -- | Identifier for the guardian. gGuardianId :: Lens' Guardian (Maybe Text) gGuardianId = lens _gGuardianId (\ s a -> s{_gGuardianId = a}) -- | The email address to which the initial guardian invitation was sent. -- This field is only visible to domain administrators. gInvitedEmailAddress :: Lens' Guardian (Maybe Text) gInvitedEmailAddress = lens _gInvitedEmailAddress (\ s a -> s{_gInvitedEmailAddress = a}) -- | User profile for the guardian. gGuardianProFile :: Lens' Guardian (Maybe UserProFile) gGuardianProFile = lens _gGuardianProFile (\ s a -> s{_gGuardianProFile = a}) instance FromJSON Guardian where parseJSON = withObject "Guardian" (\ o -> Guardian' <$> (o .:? "studentId") <*> (o .:? "guardianId") <*> (o .:? "invitedEmailAddress") <*> (o .:? "guardianProfile")) instance ToJSON Guardian where toJSON Guardian'{..} = object (catMaybes [("studentId" .=) <$> _gStudentId, ("guardianId" .=) <$> _gGuardianId, ("invitedEmailAddress" .=) <$> _gInvitedEmailAddress, ("guardianProfile" .=) <$> _gGuardianProFile]) -- | A material attached to a course as part of a material set. -- -- /See:/ 'courseMaterial' smart constructor. data CourseMaterial = CourseMaterial' { _cmDriveFile :: !(Maybe DriveFile) , _cmLink :: !(Maybe Link) , _cmYouTubeVideo :: !(Maybe YouTubeVideo) , _cmForm :: !(Maybe Form) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CourseMaterial' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cmDriveFile' -- -- * 'cmLink' -- -- * 'cmYouTubeVideo' -- -- * 'cmForm' courseMaterial :: CourseMaterial courseMaterial = CourseMaterial' { _cmDriveFile = Nothing , _cmLink = Nothing , _cmYouTubeVideo = Nothing , _cmForm = Nothing } -- | Google Drive file attachment. cmDriveFile :: Lens' CourseMaterial (Maybe DriveFile) cmDriveFile = lens _cmDriveFile (\ s a -> s{_cmDriveFile = a}) -- | Link atatchment. cmLink :: Lens' CourseMaterial (Maybe Link) cmLink = lens _cmLink (\ s a -> s{_cmLink = a}) -- | Youtube video attachment. cmYouTubeVideo :: Lens' CourseMaterial (Maybe YouTubeVideo) cmYouTubeVideo = lens _cmYouTubeVideo (\ s a -> s{_cmYouTubeVideo = a}) -- | Google Forms attachment. cmForm :: Lens' CourseMaterial (Maybe Form) cmForm = lens _cmForm (\ s a -> s{_cmForm = a}) instance FromJSON CourseMaterial where parseJSON = withObject "CourseMaterial" (\ o -> CourseMaterial' <$> (o .:? "driveFile") <*> (o .:? "link") <*> (o .:? "youTubeVideo") <*> (o .:? "form")) instance ToJSON CourseMaterial where toJSON CourseMaterial'{..} = object (catMaybes [("driveFile" .=) <$> _cmDriveFile, ("link" .=) <$> _cmLink, ("youTubeVideo" .=) <$> _cmYouTubeVideo, ("form" .=) <$> _cmForm]) -- | Student work for a short answer question. -- -- /See:/ 'shortAnswerSubmission' smart constructor. newtype ShortAnswerSubmission = ShortAnswerSubmission' { _sasAnswer :: Maybe Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ShortAnswerSubmission' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sasAnswer' shortAnswerSubmission :: ShortAnswerSubmission shortAnswerSubmission = ShortAnswerSubmission' { _sasAnswer = Nothing } -- | Student response to a short-answer question. sasAnswer :: Lens' ShortAnswerSubmission (Maybe Text) sasAnswer = lens _sasAnswer (\ s a -> s{_sasAnswer = a}) instance FromJSON ShortAnswerSubmission where parseJSON = withObject "ShortAnswerSubmission" (\ o -> ShortAnswerSubmission' <$> (o .:? "answer")) instance ToJSON ShortAnswerSubmission where toJSON ShortAnswerSubmission'{..} = object (catMaybes [("answer" .=) <$> _sasAnswer]) -- | An invitation to join a course. -- -- /See:/ 'invitation' smart constructor. data Invitation = Invitation' { _iCourseId :: !(Maybe Text) , _iUserId :: !(Maybe Text) , _iRole :: !(Maybe Text) , _iId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Invitation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iCourseId' -- -- * 'iUserId' -- -- * 'iRole' -- -- * 'iId' invitation :: Invitation invitation = Invitation' { _iCourseId = Nothing , _iUserId = Nothing , _iRole = Nothing , _iId = Nothing } -- | Identifier of the course to invite the user to. iCourseId :: Lens' Invitation (Maybe Text) iCourseId = lens _iCourseId (\ s a -> s{_iCourseId = a}) -- | Identifier of the invited user. When specified as a parameter of a -- request, this identifier can be set to one of the following: * the -- numeric identifier for the user * the email address of the user * the -- string literal \`\"me\"\`, indicating the requesting user iUserId :: Lens' Invitation (Maybe Text) iUserId = lens _iUserId (\ s a -> s{_iUserId = a}) -- | Role to invite the user to have. Must not be -- \`COURSE_ROLE_UNSPECIFIED\`. iRole :: Lens' Invitation (Maybe Text) iRole = lens _iRole (\ s a -> s{_iRole = a}) -- | Identifier assigned by Classroom. Read-only. iId :: Lens' Invitation (Maybe Text) iId = lens _iId (\ s a -> s{_iId = a}) instance FromJSON Invitation where parseJSON = withObject "Invitation" (\ o -> Invitation' <$> (o .:? "courseId") <*> (o .:? "userId") <*> (o .:? "role") <*> (o .:? "id")) instance ToJSON Invitation where toJSON Invitation'{..} = object (catMaybes [("courseId" .=) <$> _iCourseId, ("userId" .=) <$> _iUserId, ("role" .=) <$> _iRole, ("id" .=) <$> _iId]) -- | Attachment added to student assignment work. When creating attachments, -- setting the \`form\` field is not supported. -- -- /See:/ 'attachment' smart constructor. data Attachment = Attachment' { _aDriveFile :: !(Maybe DriveFile) , _aLink :: !(Maybe Link) , _aYouTubeVideo :: !(Maybe YouTubeVideo) , _aForm :: !(Maybe Form) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Attachment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aDriveFile' -- -- * 'aLink' -- -- * 'aYouTubeVideo' -- -- * 'aForm' attachment :: Attachment attachment = Attachment' { _aDriveFile = Nothing , _aLink = Nothing , _aYouTubeVideo = Nothing , _aForm = Nothing } -- | Google Drive file attachment. aDriveFile :: Lens' Attachment (Maybe DriveFile) aDriveFile = lens _aDriveFile (\ s a -> s{_aDriveFile = a}) -- | Link attachment. aLink :: Lens' Attachment (Maybe Link) aLink = lens _aLink (\ s a -> s{_aLink = a}) -- | Youtube video attachment. aYouTubeVideo :: Lens' Attachment (Maybe YouTubeVideo) aYouTubeVideo = lens _aYouTubeVideo (\ s a -> s{_aYouTubeVideo = a}) -- | Google Forms attachment. aForm :: Lens' Attachment (Maybe Form) aForm = lens _aForm (\ s a -> s{_aForm = a}) instance FromJSON Attachment where parseJSON = withObject "Attachment" (\ o -> Attachment' <$> (o .:? "driveFile") <*> (o .:? "link") <*> (o .:? "youTubeVideo") <*> (o .:? "form")) instance ToJSON Attachment where toJSON Attachment'{..} = object (catMaybes [("driveFile" .=) <$> _aDriveFile, ("link" .=) <$> _aLink, ("youTubeVideo" .=) <$> _aYouTubeVideo, ("form" .=) <$> _aForm]) -- | Student submission for course work. StudentSubmission items are -- generated when a CourseWork item is created. StudentSubmissions that -- have never been accessed (i.e. with \`state\` = NEW) may not have a -- creation time or update time. -- -- /See:/ 'studentSubmission' smart constructor. data StudentSubmission = StudentSubmission' { _ssCreationTime :: !(Maybe Text) , _ssLate :: !(Maybe Bool) , _ssState :: !(Maybe Text) , _ssCourseId :: !(Maybe Text) , _ssMultipleChoiceSubmission :: !(Maybe MultipleChoiceSubmission) , _ssAssignmentSubmission :: !(Maybe AssignmentSubmission) , _ssShortAnswerSubmission :: !(Maybe ShortAnswerSubmission) , _ssAssociatedWithDeveloper :: !(Maybe Bool) , _ssUserId :: !(Maybe Text) , _ssUpdateTime :: !(Maybe Text) , _ssCourseWorkType :: !(Maybe Text) , _ssAssignedGrade :: !(Maybe (Textual Double)) , _ssId :: !(Maybe Text) , _ssDraftGrade :: !(Maybe (Textual Double)) , _ssAlternateLink :: !(Maybe Text) , _ssCourseWorkId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'StudentSubmission' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ssCreationTime' -- -- * 'ssLate' -- -- * 'ssState' -- -- * 'ssCourseId' -- -- * 'ssMultipleChoiceSubmission' -- -- * 'ssAssignmentSubmission' -- -- * 'ssShortAnswerSubmission' -- -- * 'ssAssociatedWithDeveloper' -- -- * 'ssUserId' -- -- * 'ssUpdateTime' -- -- * 'ssCourseWorkType' -- -- * 'ssAssignedGrade' -- -- * 'ssId' -- -- * 'ssDraftGrade' -- -- * 'ssAlternateLink' -- -- * 'ssCourseWorkId' studentSubmission :: StudentSubmission studentSubmission = StudentSubmission' { _ssCreationTime = Nothing , _ssLate = Nothing , _ssState = Nothing , _ssCourseId = Nothing , _ssMultipleChoiceSubmission = Nothing , _ssAssignmentSubmission = Nothing , _ssShortAnswerSubmission = Nothing , _ssAssociatedWithDeveloper = Nothing , _ssUserId = Nothing , _ssUpdateTime = Nothing , _ssCourseWorkType = Nothing , _ssAssignedGrade = Nothing , _ssId = Nothing , _ssDraftGrade = Nothing , _ssAlternateLink = Nothing , _ssCourseWorkId = Nothing } -- | Creation time of this submission. This may be unset if the student has -- not accessed this item. Read-only. ssCreationTime :: Lens' StudentSubmission (Maybe Text) ssCreationTime = lens _ssCreationTime (\ s a -> s{_ssCreationTime = a}) -- | Whether this submission is late. Read-only. ssLate :: Lens' StudentSubmission (Maybe Bool) ssLate = lens _ssLate (\ s a -> s{_ssLate = a}) -- | State of this submission. Read-only. ssState :: Lens' StudentSubmission (Maybe Text) ssState = lens _ssState (\ s a -> s{_ssState = a}) -- | Identifier of the course. Read-only. ssCourseId :: Lens' StudentSubmission (Maybe Text) ssCourseId = lens _ssCourseId (\ s a -> s{_ssCourseId = a}) -- | Submission content when course_work_type is MULTIPLE_CHOICE_QUESTION. ssMultipleChoiceSubmission :: Lens' StudentSubmission (Maybe MultipleChoiceSubmission) ssMultipleChoiceSubmission = lens _ssMultipleChoiceSubmission (\ s a -> s{_ssMultipleChoiceSubmission = a}) -- | Submission content when course_work_type is ASSIGNMENT . ssAssignmentSubmission :: Lens' StudentSubmission (Maybe AssignmentSubmission) ssAssignmentSubmission = lens _ssAssignmentSubmission (\ s a -> s{_ssAssignmentSubmission = a}) -- | Submission content when course_work_type is SHORT_ANSWER_QUESTION. ssShortAnswerSubmission :: Lens' StudentSubmission (Maybe ShortAnswerSubmission) ssShortAnswerSubmission = lens _ssShortAnswerSubmission (\ s a -> s{_ssShortAnswerSubmission = a}) -- | Whether this student submission is associated with the Developer Console -- project making the request. See google.classroom.Work.CreateCourseWork -- for more details. Read-only. ssAssociatedWithDeveloper :: Lens' StudentSubmission (Maybe Bool) ssAssociatedWithDeveloper = lens _ssAssociatedWithDeveloper (\ s a -> s{_ssAssociatedWithDeveloper = a}) -- | Identifier for the student that owns this submission. Read-only. ssUserId :: Lens' StudentSubmission (Maybe Text) ssUserId = lens _ssUserId (\ s a -> s{_ssUserId = a}) -- | Last update time of this submission. This may be unset if the student -- has not accessed this item. Read-only. ssUpdateTime :: Lens' StudentSubmission (Maybe Text) ssUpdateTime = lens _ssUpdateTime (\ s a -> s{_ssUpdateTime = a}) -- | Type of course work this submission is for. Read-only. ssCourseWorkType :: Lens' StudentSubmission (Maybe Text) ssCourseWorkType = lens _ssCourseWorkType (\ s a -> s{_ssCourseWorkType = a}) -- | Optional grade. If unset, no grade was set. This must be a non-negative -- integer value. This may be modified only by course teachers. ssAssignedGrade :: Lens' StudentSubmission (Maybe Double) ssAssignedGrade = lens _ssAssignedGrade (\ s a -> s{_ssAssignedGrade = a}) . mapping _Coerce -- | Classroom-assigned Identifier for the student submission. This is unique -- among submissions for the relevant course work. Read-only. ssId :: Lens' StudentSubmission (Maybe Text) ssId = lens _ssId (\ s a -> s{_ssId = a}) -- | Optional pending grade. If unset, no grade was set. This must be a -- non-negative integer value. This is only visible to and modifiable by -- course teachers. ssDraftGrade :: Lens' StudentSubmission (Maybe Double) ssDraftGrade = lens _ssDraftGrade (\ s a -> s{_ssDraftGrade = a}) . mapping _Coerce -- | Absolute link to the submission in the Classroom web UI. Read-only. ssAlternateLink :: Lens' StudentSubmission (Maybe Text) ssAlternateLink = lens _ssAlternateLink (\ s a -> s{_ssAlternateLink = a}) -- | Identifier for the course work this corresponds to. Read-only. ssCourseWorkId :: Lens' StudentSubmission (Maybe Text) ssCourseWorkId = lens _ssCourseWorkId (\ s a -> s{_ssCourseWorkId = a}) instance FromJSON StudentSubmission where parseJSON = withObject "StudentSubmission" (\ o -> StudentSubmission' <$> (o .:? "creationTime") <*> (o .:? "late") <*> (o .:? "state") <*> (o .:? "courseId") <*> (o .:? "multipleChoiceSubmission") <*> (o .:? "assignmentSubmission") <*> (o .:? "shortAnswerSubmission") <*> (o .:? "associatedWithDeveloper") <*> (o .:? "userId") <*> (o .:? "updateTime") <*> (o .:? "courseWorkType") <*> (o .:? "assignedGrade") <*> (o .:? "id") <*> (o .:? "draftGrade") <*> (o .:? "alternateLink") <*> (o .:? "courseWorkId")) instance ToJSON StudentSubmission where toJSON StudentSubmission'{..} = object (catMaybes [("creationTime" .=) <$> _ssCreationTime, ("late" .=) <$> _ssLate, ("state" .=) <$> _ssState, ("courseId" .=) <$> _ssCourseId, ("multipleChoiceSubmission" .=) <$> _ssMultipleChoiceSubmission, ("assignmentSubmission" .=) <$> _ssAssignmentSubmission, ("shortAnswerSubmission" .=) <$> _ssShortAnswerSubmission, ("associatedWithDeveloper" .=) <$> _ssAssociatedWithDeveloper, ("userId" .=) <$> _ssUserId, ("updateTime" .=) <$> _ssUpdateTime, ("courseWorkType" .=) <$> _ssCourseWorkType, ("assignedGrade" .=) <$> _ssAssignedGrade, ("id" .=) <$> _ssId, ("draftGrade" .=) <$> _ssDraftGrade, ("alternateLink" .=) <$> _ssAlternateLink, ("courseWorkId" .=) <$> _ssCourseWorkId]) -- | Response when listing guardians. -- -- /See:/ 'listGuardiansResponse' smart constructor. data ListGuardiansResponse = ListGuardiansResponse' { _lgrNextPageToken :: !(Maybe Text) , _lgrGuardians :: !(Maybe [Guardian]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ListGuardiansResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lgrNextPageToken' -- -- * 'lgrGuardians' listGuardiansResponse :: ListGuardiansResponse listGuardiansResponse = ListGuardiansResponse' { _lgrNextPageToken = Nothing , _lgrGuardians = Nothing } -- | Token identifying the next page of results to return. If empty, no -- further results are available. lgrNextPageToken :: Lens' ListGuardiansResponse (Maybe Text) lgrNextPageToken = lens _lgrNextPageToken (\ s a -> s{_lgrNextPageToken = a}) -- | Guardians on this page of results that met the criteria specified in the -- request. lgrGuardians :: Lens' ListGuardiansResponse [Guardian] lgrGuardians = lens _lgrGuardians (\ s a -> s{_lgrGuardians = a}) . _Default . _Coerce instance FromJSON ListGuardiansResponse where parseJSON = withObject "ListGuardiansResponse" (\ o -> ListGuardiansResponse' <$> (o .:? "nextPageToken") <*> (o .:? "guardians" .!= mempty)) instance ToJSON ListGuardiansResponse where toJSON ListGuardiansResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lgrNextPageToken, ("guardians" .=) <$> _lgrGuardians]) -- | Represents a whole calendar date, e.g. date of birth. The time of day -- and time zone are either specified elsewhere or are not significant. The -- date is relative to the Proleptic Gregorian Calendar. The day may be 0 -- to represent a year and month where the day is not significant, e.g. -- credit card expiration date. The year may be 0 to represent a month and -- day independent of year, e.g. anniversary date. Related types are -- google.type.TimeOfDay and \`google.protobuf.Timestamp\`. -- -- /See:/ 'date' smart constructor. data Date = Date' { _dDay :: !(Maybe (Textual Int32)) , _dYear :: !(Maybe (Textual Int32)) , _dMonth :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Date' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dDay' -- -- * 'dYear' -- -- * 'dMonth' date :: Date date = Date' { _dDay = Nothing , _dYear = Nothing , _dMonth = Nothing } -- | Day of month. Must be from 1 to 31 and valid for the year and month, or -- 0 if specifying a year\/month where the day is not significant. dDay :: Lens' Date (Maybe Int32) dDay = lens _dDay (\ s a -> s{_dDay = a}) . mapping _Coerce -- | Year of date. Must be from 1 to 9999, or 0 if specifying a date without -- a year. dYear :: Lens' Date (Maybe Int32) dYear = lens _dYear (\ s a -> s{_dYear = a}) . mapping _Coerce -- | Month of year. Must be from 1 to 12. dMonth :: Lens' Date (Maybe Int32) dMonth = lens _dMonth (\ s a -> s{_dMonth = a}) . mapping _Coerce instance FromJSON Date where parseJSON = withObject "Date" (\ o -> Date' <$> (o .:? "day") <*> (o .:? "year") <*> (o .:? "month")) instance ToJSON Date where toJSON Date'{..} = object (catMaybes [("day" .=) <$> _dDay, ("year" .=) <$> _dYear, ("month" .=) <$> _dMonth]) -- | YouTube video item. -- -- /See:/ 'youTubeVideo' smart constructor. data YouTubeVideo = YouTubeVideo' { _ytvThumbnailURL :: !(Maybe Text) , _ytvId :: !(Maybe Text) , _ytvTitle :: !(Maybe Text) , _ytvAlternateLink :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'YouTubeVideo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ytvThumbnailURL' -- -- * 'ytvId' -- -- * 'ytvTitle' -- -- * 'ytvAlternateLink' youTubeVideo :: YouTubeVideo youTubeVideo = YouTubeVideo' { _ytvThumbnailURL = Nothing , _ytvId = Nothing , _ytvTitle = Nothing , _ytvAlternateLink = Nothing } -- | URL of a thumbnail image of the YouTube video. Read-only. ytvThumbnailURL :: Lens' YouTubeVideo (Maybe Text) ytvThumbnailURL = lens _ytvThumbnailURL (\ s a -> s{_ytvThumbnailURL = a}) -- | YouTube API resource ID. ytvId :: Lens' YouTubeVideo (Maybe Text) ytvId = lens _ytvId (\ s a -> s{_ytvId = a}) -- | Title of the YouTube video. Read-only. ytvTitle :: Lens' YouTubeVideo (Maybe Text) ytvTitle = lens _ytvTitle (\ s a -> s{_ytvTitle = a}) -- | URL that can be used to view the YouTube video. Read-only. ytvAlternateLink :: Lens' YouTubeVideo (Maybe Text) ytvAlternateLink = lens _ytvAlternateLink (\ s a -> s{_ytvAlternateLink = a}) instance FromJSON YouTubeVideo where parseJSON = withObject "YouTubeVideo" (\ o -> YouTubeVideo' <$> (o .:? "thumbnailUrl") <*> (o .:? "id") <*> (o .:? "title") <*> (o .:? "alternateLink")) instance ToJSON YouTubeVideo where toJSON YouTubeVideo'{..} = object (catMaybes [("thumbnailUrl" .=) <$> _ytvThumbnailURL, ("id" .=) <$> _ytvId, ("title" .=) <$> _ytvTitle, ("alternateLink" .=) <$> _ytvAlternateLink]) -- | Teacher of a course. -- -- /See:/ 'teacher' smart constructor. data Teacher = Teacher' { _tCourseId :: !(Maybe Text) , _tProFile :: !(Maybe UserProFile) , _tUserId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Teacher' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tCourseId' -- -- * 'tProFile' -- -- * 'tUserId' teacher :: Teacher teacher = Teacher' { _tCourseId = Nothing , _tProFile = Nothing , _tUserId = Nothing } -- | Identifier of the course. Read-only. tCourseId :: Lens' Teacher (Maybe Text) tCourseId = lens _tCourseId (\ s a -> s{_tCourseId = a}) -- | Global user information for the teacher. Read-only. tProFile :: Lens' Teacher (Maybe UserProFile) tProFile = lens _tProFile (\ s a -> s{_tProFile = a}) -- | Identifier of the user. When specified as a parameter of a request, this -- identifier can be one of the following: * the numeric identifier for the -- user * the email address of the user * the string literal \`\"me\"\`, -- indicating the requesting user tUserId :: Lens' Teacher (Maybe Text) tUserId = lens _tUserId (\ s a -> s{_tUserId = a}) instance FromJSON Teacher where parseJSON = withObject "Teacher" (\ o -> Teacher' <$> (o .:? "courseId") <*> (o .:? "profile") <*> (o .:? "userId")) instance ToJSON Teacher where toJSON Teacher'{..} = object (catMaybes [("courseId" .=) <$> _tCourseId, ("profile" .=) <$> _tProFile, ("userId" .=) <$> _tUserId]) -- | A set of materials that appears on the \"About\" page of the course. -- These materials might include a syllabus, schedule, or other background -- information relating to the course as a whole. -- -- /See:/ 'courseMaterialSet' smart constructor. data CourseMaterialSet = CourseMaterialSet' { _cmsMaterials :: !(Maybe [CourseMaterial]) , _cmsTitle :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CourseMaterialSet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cmsMaterials' -- -- * 'cmsTitle' courseMaterialSet :: CourseMaterialSet courseMaterialSet = CourseMaterialSet' { _cmsMaterials = Nothing , _cmsTitle = Nothing } -- | Materials attached to this set. cmsMaterials :: Lens' CourseMaterialSet [CourseMaterial] cmsMaterials = lens _cmsMaterials (\ s a -> s{_cmsMaterials = a}) . _Default . _Coerce -- | Title for this set. cmsTitle :: Lens' CourseMaterialSet (Maybe Text) cmsTitle = lens _cmsTitle (\ s a -> s{_cmsTitle = a}) instance FromJSON CourseMaterialSet where parseJSON = withObject "CourseMaterialSet" (\ o -> CourseMaterialSet' <$> (o .:? "materials" .!= mempty) <*> (o .:? "title")) instance ToJSON CourseMaterialSet where toJSON CourseMaterialSet'{..} = object (catMaybes [("materials" .=) <$> _cmsMaterials, ("title" .=) <$> _cmsTitle]) -- | Details of the user\'s name. -- -- /See:/ 'name' smart constructor. data Name = Name' { _nGivenName :: !(Maybe Text) , _nFullName :: !(Maybe Text) , _nFamilyName :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Name' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nGivenName' -- -- * 'nFullName' -- -- * 'nFamilyName' name :: Name name = Name' { _nGivenName = Nothing , _nFullName = Nothing , _nFamilyName = Nothing } -- | The user\'s first name. Read-only. nGivenName :: Lens' Name (Maybe Text) nGivenName = lens _nGivenName (\ s a -> s{_nGivenName = a}) -- | The user\'s full name formed by concatenating the first and last name -- values. Read-only. nFullName :: Lens' Name (Maybe Text) nFullName = lens _nFullName (\ s a -> s{_nFullName = a}) -- | The user\'s last name. Read-only. nFamilyName :: Lens' Name (Maybe Text) nFamilyName = lens _nFamilyName (\ s a -> s{_nFamilyName = a}) instance FromJSON Name where parseJSON = withObject "Name" (\ o -> Name' <$> (o .:? "givenName") <*> (o .:? "fullName") <*> (o .:? "familyName")) instance ToJSON Name where toJSON Name'{..} = object (catMaybes [("givenName" .=) <$> _nGivenName, ("fullName" .=) <$> _nFullName, ("familyName" .=) <$> _nFamilyName]) -- | Response when listing courses. -- -- /See:/ 'listCoursesResponse' smart constructor. data ListCoursesResponse = ListCoursesResponse' { _lcrNextPageToken :: !(Maybe Text) , _lcrCourses :: !(Maybe [Course]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ListCoursesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lcrNextPageToken' -- -- * 'lcrCourses' listCoursesResponse :: ListCoursesResponse listCoursesResponse = ListCoursesResponse' { _lcrNextPageToken = Nothing , _lcrCourses = Nothing } -- | Token identifying the next page of results to return. If empty, no -- further results are available. lcrNextPageToken :: Lens' ListCoursesResponse (Maybe Text) lcrNextPageToken = lens _lcrNextPageToken (\ s a -> s{_lcrNextPageToken = a}) -- | Courses that match the list request. lcrCourses :: Lens' ListCoursesResponse [Course] lcrCourses = lens _lcrCourses (\ s a -> s{_lcrCourses = a}) . _Default . _Coerce instance FromJSON ListCoursesResponse where parseJSON = withObject "ListCoursesResponse" (\ o -> ListCoursesResponse' <$> (o .:? "nextPageToken") <*> (o .:? "courses" .!= mempty)) instance ToJSON ListCoursesResponse where toJSON ListCoursesResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lcrNextPageToken, ("courses" .=) <$> _lcrCourses]) -- | Request to turn in a student submission. -- -- /See:/ 'turnInStudentSubmissionRequest' smart constructor. data TurnInStudentSubmissionRequest = TurnInStudentSubmissionRequest' deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TurnInStudentSubmissionRequest' with the minimum fields required to make a request. -- turnInStudentSubmissionRequest :: TurnInStudentSubmissionRequest turnInStudentSubmissionRequest = TurnInStudentSubmissionRequest' instance FromJSON TurnInStudentSubmissionRequest where parseJSON = withObject "TurnInStudentSubmissionRequest" (\ o -> pure TurnInStudentSubmissionRequest') instance ToJSON TurnInStudentSubmissionRequest where toJSON = const emptyObject -- | Global information for a user. -- -- /See:/ 'userProFile' smart constructor. data UserProFile = UserProFile' { _upfPhotoURL :: !(Maybe Text) , _upfName :: !(Maybe Name) , _upfEmailAddress :: !(Maybe Text) , _upfId :: !(Maybe Text) , _upfPermissions :: !(Maybe [GlobalPermission]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UserProFile' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'upfPhotoURL' -- -- * 'upfName' -- -- * 'upfEmailAddress' -- -- * 'upfId' -- -- * 'upfPermissions' userProFile :: UserProFile userProFile = UserProFile' { _upfPhotoURL = Nothing , _upfName = Nothing , _upfEmailAddress = Nothing , _upfId = Nothing , _upfPermissions = Nothing } -- | URL of user\'s profile photo. Read-only. upfPhotoURL :: Lens' UserProFile (Maybe Text) upfPhotoURL = lens _upfPhotoURL (\ s a -> s{_upfPhotoURL = a}) -- | Name of the user. Read-only. upfName :: Lens' UserProFile (Maybe Name) upfName = lens _upfName (\ s a -> s{_upfName = a}) -- | Email address of the user. Read-only. upfEmailAddress :: Lens' UserProFile (Maybe Text) upfEmailAddress = lens _upfEmailAddress (\ s a -> s{_upfEmailAddress = a}) -- | Identifier of the user. Read-only. upfId :: Lens' UserProFile (Maybe Text) upfId = lens _upfId (\ s a -> s{_upfId = a}) -- | Global permissions of the user. Read-only. upfPermissions :: Lens' UserProFile [GlobalPermission] upfPermissions = lens _upfPermissions (\ s a -> s{_upfPermissions = a}) . _Default . _Coerce instance FromJSON UserProFile where parseJSON = withObject "UserProFile" (\ o -> UserProFile' <$> (o .:? "photoUrl") <*> (o .:? "name") <*> (o .:? "emailAddress") <*> (o .:? "id") <*> (o .:? "permissions" .!= mempty)) instance ToJSON UserProFile where toJSON UserProFile'{..} = object (catMaybes [("photoUrl" .=) <$> _upfPhotoURL, ("name" .=) <$> _upfName, ("emailAddress" .=) <$> _upfEmailAddress, ("id" .=) <$> _upfId, ("permissions" .=) <$> _upfPermissions]) -- | Representation of a Google Drive folder. -- -- /See:/ 'driveFolder' smart constructor. data DriveFolder = DriveFolder' { _dId :: !(Maybe Text) , _dTitle :: !(Maybe Text) , _dAlternateLink :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DriveFolder' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dId' -- -- * 'dTitle' -- -- * 'dAlternateLink' driveFolder :: DriveFolder driveFolder = DriveFolder' { _dId = Nothing , _dTitle = Nothing , _dAlternateLink = Nothing } -- | Drive API resource ID. dId :: Lens' DriveFolder (Maybe Text) dId = lens _dId (\ s a -> s{_dId = a}) -- | Title of the Drive folder. Read-only. dTitle :: Lens' DriveFolder (Maybe Text) dTitle = lens _dTitle (\ s a -> s{_dTitle = a}) -- | URL that can be used to access the Drive folder. Read-only. dAlternateLink :: Lens' DriveFolder (Maybe Text) dAlternateLink = lens _dAlternateLink (\ s a -> s{_dAlternateLink = a}) instance FromJSON DriveFolder where parseJSON = withObject "DriveFolder" (\ o -> DriveFolder' <$> (o .:? "id") <*> (o .:? "title") <*> (o .:? "alternateLink")) instance ToJSON DriveFolder where toJSON DriveFolder'{..} = object (catMaybes [("id" .=) <$> _dId, ("title" .=) <$> _dTitle, ("alternateLink" .=) <$> _dAlternateLink]) -- | Additional details for multiple-choice questions. -- -- /See:/ 'multipleChoiceQuestion' smart constructor. newtype MultipleChoiceQuestion = MultipleChoiceQuestion' { _mcqChoices :: Maybe [Text] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'MultipleChoiceQuestion' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mcqChoices' multipleChoiceQuestion :: MultipleChoiceQuestion multipleChoiceQuestion = MultipleChoiceQuestion' { _mcqChoices = Nothing } -- | Possible choices. mcqChoices :: Lens' MultipleChoiceQuestion [Text] mcqChoices = lens _mcqChoices (\ s a -> s{_mcqChoices = a}) . _Default . _Coerce instance FromJSON MultipleChoiceQuestion where parseJSON = withObject "MultipleChoiceQuestion" (\ o -> MultipleChoiceQuestion' <$> (o .:? "choices" .!= mempty)) instance ToJSON MultipleChoiceQuestion where toJSON MultipleChoiceQuestion'{..} = object (catMaybes [("choices" .=) <$> _mcqChoices]) -- | A Course in Classroom. -- -- /See:/ 'course' smart constructor. data Course = Course' { _cCreationTime :: !(Maybe Text) , _cRoom :: !(Maybe Text) , _cCourseMaterialSets :: !(Maybe [CourseMaterialSet]) , _cTeacherGroupEmail :: !(Maybe Text) , _cTeacherFolder :: !(Maybe DriveFolder) , _cCourseState :: !(Maybe Text) , _cGuardiansEnabled :: !(Maybe Bool) , _cEnrollmentCode :: !(Maybe Text) , _cUpdateTime :: !(Maybe Text) , _cOwnerId :: !(Maybe Text) , _cName :: !(Maybe Text) , _cId :: !(Maybe Text) , _cAlternateLink :: !(Maybe Text) , _cCourseGroupEmail :: !(Maybe Text) , _cDescription :: !(Maybe Text) , _cDescriptionHeading :: !(Maybe Text) , _cSection :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Course' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cCreationTime' -- -- * 'cRoom' -- -- * 'cCourseMaterialSets' -- -- * 'cTeacherGroupEmail' -- -- * 'cTeacherFolder' -- -- * 'cCourseState' -- -- * 'cGuardiansEnabled' -- -- * 'cEnrollmentCode' -- -- * 'cUpdateTime' -- -- * 'cOwnerId' -- -- * 'cName' -- -- * 'cId' -- -- * 'cAlternateLink' -- -- * 'cCourseGroupEmail' -- -- * 'cDescription' -- -- * 'cDescriptionHeading' -- -- * 'cSection' course :: Course course = Course' { _cCreationTime = Nothing , _cRoom = Nothing , _cCourseMaterialSets = Nothing , _cTeacherGroupEmail = Nothing , _cTeacherFolder = Nothing , _cCourseState = Nothing , _cGuardiansEnabled = Nothing , _cEnrollmentCode = Nothing , _cUpdateTime = Nothing , _cOwnerId = Nothing , _cName = Nothing , _cId = Nothing , _cAlternateLink = Nothing , _cCourseGroupEmail = Nothing , _cDescription = Nothing , _cDescriptionHeading = Nothing , _cSection = Nothing } -- | Creation time of the course. Specifying this field in a course update -- mask results in an error. Read-only. cCreationTime :: Lens' Course (Maybe Text) cCreationTime = lens _cCreationTime (\ s a -> s{_cCreationTime = a}) -- | Optional room location. For example, \"301\". If set, this field must be -- a valid UTF-8 string and no longer than 650 characters. cRoom :: Lens' Course (Maybe Text) cRoom = lens _cRoom (\ s a -> s{_cRoom = a}) -- | Sets of materials that appear on the \"about\" page of this course. -- Read-only. cCourseMaterialSets :: Lens' Course [CourseMaterialSet] cCourseMaterialSets = lens _cCourseMaterialSets (\ s a -> s{_cCourseMaterialSets = a}) . _Default . _Coerce -- | The email address of a Google group containing all teachers of the -- course. This group does not accept email and can only be used for -- permissions. Read-only. cTeacherGroupEmail :: Lens' Course (Maybe Text) cTeacherGroupEmail = lens _cTeacherGroupEmail (\ s a -> s{_cTeacherGroupEmail = a}) -- | Information about a Drive Folder that is shared with all teachers of the -- course. This field will only be set for teachers of the course and -- domain administrators. Read-only. cTeacherFolder :: Lens' Course (Maybe DriveFolder) cTeacherFolder = lens _cTeacherFolder (\ s a -> s{_cTeacherFolder = a}) -- | State of the course. If unspecified, the default state is -- \`PROVISIONED\`. cCourseState :: Lens' Course (Maybe Text) cCourseState = lens _cCourseState (\ s a -> s{_cCourseState = a}) -- | Whether or not guardian notifications are enabled for this course. -- Read-only. cGuardiansEnabled :: Lens' Course (Maybe Bool) cGuardiansEnabled = lens _cGuardiansEnabled (\ s a -> s{_cGuardiansEnabled = a}) -- | Enrollment code to use when joining this course. Specifying this field -- in a course update mask results in an error. Read-only. cEnrollmentCode :: Lens' Course (Maybe Text) cEnrollmentCode = lens _cEnrollmentCode (\ s a -> s{_cEnrollmentCode = a}) -- | Time of the most recent update to this course. Specifying this field in -- a course update mask results in an error. Read-only. cUpdateTime :: Lens' Course (Maybe Text) cUpdateTime = lens _cUpdateTime (\ s a -> s{_cUpdateTime = a}) -- | The identifier of the owner of a course. When specified as a parameter -- of a create course request, this field is required. The identifier can -- be one of the following: * the numeric identifier for the user * the -- email address of the user * the string literal \`\"me\"\`, indicating -- the requesting user This must be set in a create request. Specifying -- this field in a course update mask results in an \`INVALID_ARGUMENT\` -- error. cOwnerId :: Lens' Course (Maybe Text) cOwnerId = lens _cOwnerId (\ s a -> s{_cOwnerId = a}) -- | Name of the course. For example, \"10th Grade Biology\". The name is -- required. It must be between 1 and 750 characters and a valid UTF-8 -- string. cName :: Lens' Course (Maybe Text) cName = lens _cName (\ s a -> s{_cName = a}) -- | Identifier for this course assigned by Classroom. When creating a -- course, you may optionally set this identifier to an alias string in the -- request to create a corresponding alias. The \`id\` is still assigned by -- Classroom and cannot be updated after the course is created. Specifying -- this field in a course update mask results in an error. cId :: Lens' Course (Maybe Text) cId = lens _cId (\ s a -> s{_cId = a}) -- | Absolute link to this course in the Classroom web UI. Read-only. cAlternateLink :: Lens' Course (Maybe Text) cAlternateLink = lens _cAlternateLink (\ s a -> s{_cAlternateLink = a}) -- | The email address of a Google group containing all members of the -- course. This group does not accept email and can only be used for -- permissions. Read-only. cCourseGroupEmail :: Lens' Course (Maybe Text) cCourseGroupEmail = lens _cCourseGroupEmail (\ s a -> s{_cCourseGroupEmail = a}) -- | Optional description. For example, \"We\'ll be learning about the -- structure of living creatures from a combination of textbooks, guest -- lectures, and lab work. Expect to be excited!\" If set, this field must -- be a valid UTF-8 string and no longer than 30,000 characters. cDescription :: Lens' Course (Maybe Text) cDescription = lens _cDescription (\ s a -> s{_cDescription = a}) -- | Optional heading for the description. For example, \"Welcome to 10th -- Grade Biology.\" If set, this field must be a valid UTF-8 string and no -- longer than 3600 characters. cDescriptionHeading :: Lens' Course (Maybe Text) cDescriptionHeading = lens _cDescriptionHeading (\ s a -> s{_cDescriptionHeading = a}) -- | Section of the course. For example, \"Period 2\". If set, this field -- must be a valid UTF-8 string and no longer than 2800 characters. cSection :: Lens' Course (Maybe Text) cSection = lens _cSection (\ s a -> s{_cSection = a}) instance FromJSON Course where parseJSON = withObject "Course" (\ o -> Course' <$> (o .:? "creationTime") <*> (o .:? "room") <*> (o .:? "courseMaterialSets" .!= mempty) <*> (o .:? "teacherGroupEmail") <*> (o .:? "teacherFolder") <*> (o .:? "courseState") <*> (o .:? "guardiansEnabled") <*> (o .:? "enrollmentCode") <*> (o .:? "updateTime") <*> (o .:? "ownerId") <*> (o .:? "name") <*> (o .:? "id") <*> (o .:? "alternateLink") <*> (o .:? "courseGroupEmail") <*> (o .:? "description") <*> (o .:? "descriptionHeading") <*> (o .:? "section")) instance ToJSON Course where toJSON Course'{..} = object (catMaybes [("creationTime" .=) <$> _cCreationTime, ("room" .=) <$> _cRoom, ("courseMaterialSets" .=) <$> _cCourseMaterialSets, ("teacherGroupEmail" .=) <$> _cTeacherGroupEmail, ("teacherFolder" .=) <$> _cTeacherFolder, ("courseState" .=) <$> _cCourseState, ("guardiansEnabled" .=) <$> _cGuardiansEnabled, ("enrollmentCode" .=) <$> _cEnrollmentCode, ("updateTime" .=) <$> _cUpdateTime, ("ownerId" .=) <$> _cOwnerId, ("name" .=) <$> _cName, ("id" .=) <$> _cId, ("alternateLink" .=) <$> _cAlternateLink, ("courseGroupEmail" .=) <$> _cCourseGroupEmail, ("description" .=) <$> _cDescription, ("descriptionHeading" .=) <$> _cDescriptionHeading, ("section" .=) <$> _cSection]) -- | Represents a time of day. The date and time zone are either not -- significant or are specified elsewhere. An API may chose to allow leap -- seconds. Related types are google.type.Date and -- \`google.protobuf.Timestamp\`. -- -- /See:/ 'timeOfDay' smart constructor. data TimeOfDay' = TimeOfDay'' { _todNanos :: !(Maybe (Textual Int32)) , _todHours :: !(Maybe (Textual Int32)) , _todMinutes :: !(Maybe (Textual Int32)) , _todSeconds :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TimeOfDay' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'todNanos' -- -- * 'todHours' -- -- * 'todMinutes' -- -- * 'todSeconds' timeOfDay :: TimeOfDay' timeOfDay = TimeOfDay'' { _todNanos = Nothing , _todHours = Nothing , _todMinutes = Nothing , _todSeconds = Nothing } -- | Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999. todNanos :: Lens' TimeOfDay' (Maybe Int32) todNanos = lens _todNanos (\ s a -> s{_todNanos = a}) . mapping _Coerce -- | Hours of day in 24 hour format. Should be from 0 to 23. An API may -- choose to allow the value \"24:00:00\" for scenarios like business -- closing time. todHours :: Lens' TimeOfDay' (Maybe Int32) todHours = lens _todHours (\ s a -> s{_todHours = a}) . mapping _Coerce -- | Minutes of hour of day. Must be from 0 to 59. todMinutes :: Lens' TimeOfDay' (Maybe Int32) todMinutes = lens _todMinutes (\ s a -> s{_todMinutes = a}) . mapping _Coerce -- | Seconds of minutes of the time. Must normally be from 0 to 59. An API -- may allow the value 60 if it allows leap-seconds. todSeconds :: Lens' TimeOfDay' (Maybe Int32) todSeconds = lens _todSeconds (\ s a -> s{_todSeconds = a}) . mapping _Coerce instance FromJSON TimeOfDay' where parseJSON = withObject "TimeOfDay" (\ o -> TimeOfDay'' <$> (o .:? "nanos") <*> (o .:? "hours") <*> (o .:? "minutes") <*> (o .:? "seconds")) instance ToJSON TimeOfDay' where toJSON TimeOfDay''{..} = object (catMaybes [("nanos" .=) <$> _todNanos, ("hours" .=) <$> _todHours, ("minutes" .=) <$> _todMinutes, ("seconds" .=) <$> _todSeconds]) -- | Response when listing guardian invitations. -- -- /See:/ 'listGuardianInvitationsResponse' smart constructor. data ListGuardianInvitationsResponse = ListGuardianInvitationsResponse' { _lgirNextPageToken :: !(Maybe Text) , _lgirGuardianInvitations :: !(Maybe [GuardianInvitation]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ListGuardianInvitationsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lgirNextPageToken' -- -- * 'lgirGuardianInvitations' listGuardianInvitationsResponse :: ListGuardianInvitationsResponse listGuardianInvitationsResponse = ListGuardianInvitationsResponse' { _lgirNextPageToken = Nothing , _lgirGuardianInvitations = Nothing } -- | Token identifying the next page of results to return. If empty, no -- further results are available. lgirNextPageToken :: Lens' ListGuardianInvitationsResponse (Maybe Text) lgirNextPageToken = lens _lgirNextPageToken (\ s a -> s{_lgirNextPageToken = a}) -- | Guardian invitations that matched the list request. lgirGuardianInvitations :: Lens' ListGuardianInvitationsResponse [GuardianInvitation] lgirGuardianInvitations = lens _lgirGuardianInvitations (\ s a -> s{_lgirGuardianInvitations = a}) . _Default . _Coerce instance FromJSON ListGuardianInvitationsResponse where parseJSON = withObject "ListGuardianInvitationsResponse" (\ o -> ListGuardianInvitationsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "guardianInvitations" .!= mempty)) instance ToJSON ListGuardianInvitationsResponse where toJSON ListGuardianInvitationsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lgirNextPageToken, ("guardianInvitations" .=) <$> _lgirGuardianInvitations]) -- | Additional details for assignments. -- -- /See:/ 'assignment' smart constructor. newtype Assignment = Assignment' { _aStudentWorkFolder :: Maybe DriveFolder } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Assignment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aStudentWorkFolder' assignment :: Assignment assignment = Assignment' { _aStudentWorkFolder = Nothing } -- | Drive folder where attachments from student submissions are placed. This -- is only populated for course teachers. aStudentWorkFolder :: Lens' Assignment (Maybe DriveFolder) aStudentWorkFolder = lens _aStudentWorkFolder (\ s a -> s{_aStudentWorkFolder = a}) instance FromJSON Assignment where parseJSON = withObject "Assignment" (\ o -> Assignment' <$> (o .:? "studentWorkFolder")) instance ToJSON Assignment where toJSON Assignment'{..} = object (catMaybes [("studentWorkFolder" .=) <$> _aStudentWorkFolder]) -- | Response when listing students. -- -- /See:/ 'listStudentsResponse' smart constructor. data ListStudentsResponse = ListStudentsResponse' { _lsrNextPageToken :: !(Maybe Text) , _lsrStudents :: !(Maybe [Student]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ListStudentsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lsrNextPageToken' -- -- * 'lsrStudents' listStudentsResponse :: ListStudentsResponse listStudentsResponse = ListStudentsResponse' { _lsrNextPageToken = Nothing , _lsrStudents = Nothing } -- | Token identifying the next page of results to return. If empty, no -- further results are available. lsrNextPageToken :: Lens' ListStudentsResponse (Maybe Text) lsrNextPageToken = lens _lsrNextPageToken (\ s a -> s{_lsrNextPageToken = a}) -- | Students who match the list request. lsrStudents :: Lens' ListStudentsResponse [Student] lsrStudents = lens _lsrStudents (\ s a -> s{_lsrStudents = a}) . _Default . _Coerce instance FromJSON ListStudentsResponse where parseJSON = withObject "ListStudentsResponse" (\ o -> ListStudentsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "students" .!= mempty)) instance ToJSON ListStudentsResponse where toJSON ListStudentsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lsrNextPageToken, ("students" .=) <$> _lsrStudents]) -- | Drive file that is used as material for course work. -- -- /See:/ 'sharedDriveFile' smart constructor. data SharedDriveFile = SharedDriveFile' { _sdfDriveFile :: !(Maybe DriveFile) , _sdfShareMode :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'SharedDriveFile' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdfDriveFile' -- -- * 'sdfShareMode' sharedDriveFile :: SharedDriveFile sharedDriveFile = SharedDriveFile' { _sdfDriveFile = Nothing , _sdfShareMode = Nothing } -- | Drive file details. sdfDriveFile :: Lens' SharedDriveFile (Maybe DriveFile) sdfDriveFile = lens _sdfDriveFile (\ s a -> s{_sdfDriveFile = a}) -- | Mechanism by which students access the Drive item. sdfShareMode :: Lens' SharedDriveFile (Maybe Text) sdfShareMode = lens _sdfShareMode (\ s a -> s{_sdfShareMode = a}) instance FromJSON SharedDriveFile where parseJSON = withObject "SharedDriveFile" (\ o -> SharedDriveFile' <$> (o .:? "driveFile") <*> (o .:? "shareMode")) instance ToJSON SharedDriveFile where toJSON SharedDriveFile'{..} = object (catMaybes [("driveFile" .=) <$> _sdfDriveFile, ("shareMode" .=) <$> _sdfShareMode]) -- | Alternative identifier for a course. An alias uniquely identifies a -- course. It must be unique within one of the following scopes: * domain: -- A domain-scoped alias is visible to all users within the alias -- creator\'s domain and can be created only by a domain admin. A -- domain-scoped alias is often used when a course has an identifier -- external to Classroom. * project: A project-scoped alias is visible to -- any request from an application using the Developer Console project ID -- that created the alias and can be created by any project. A -- project-scoped alias is often used when an application has alternative -- identifiers. A random value can also be used to avoid duplicate courses -- in the event of transmission failures, as retrying a request will return -- \`ALREADY_EXISTS\` if a previous one has succeeded. -- -- /See:/ 'courseAlias' smart constructor. newtype CourseAlias = CourseAlias' { _caAlias :: Maybe Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CourseAlias' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'caAlias' courseAlias :: CourseAlias courseAlias = CourseAlias' { _caAlias = Nothing } -- | Alias string. The format of the string indicates the desired alias -- scoping. * \`d:\` indicates a domain-scoped alias. Example: -- \`d:math_101\` * \`p:\` indicates a project-scoped alias. Example: -- \`p:abc123\` This field has a maximum length of 256 characters. caAlias :: Lens' CourseAlias (Maybe Text) caAlias = lens _caAlias (\ s a -> s{_caAlias = a}) instance FromJSON CourseAlias where parseJSON = withObject "CourseAlias" (\ o -> CourseAlias' <$> (o .:? "alias")) instance ToJSON CourseAlias where toJSON CourseAlias'{..} = object (catMaybes [("alias" .=) <$> _caAlias]) -- | Google Forms item. -- -- /See:/ 'form' smart constructor. data Form = Form' { _fThumbnailURL :: !(Maybe Text) , _fFormURL :: !(Maybe Text) , _fTitle :: !(Maybe Text) , _fResponseURL :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Form' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fThumbnailURL' -- -- * 'fFormURL' -- -- * 'fTitle' -- -- * 'fResponseURL' form :: Form form = Form' { _fThumbnailURL = Nothing , _fFormURL = Nothing , _fTitle = Nothing , _fResponseURL = Nothing } -- | URL of a thumbnail image of the Form. Read-only. fThumbnailURL :: Lens' Form (Maybe Text) fThumbnailURL = lens _fThumbnailURL (\ s a -> s{_fThumbnailURL = a}) -- | URL of the form. fFormURL :: Lens' Form (Maybe Text) fFormURL = lens _fFormURL (\ s a -> s{_fFormURL = a}) -- | Title of the Form. Read-only. fTitle :: Lens' Form (Maybe Text) fTitle = lens _fTitle (\ s a -> s{_fTitle = a}) -- | URL of the form responses document. Only set if respsonses have been -- recorded and only when the requesting user is an editor of the form. -- Read-only. fResponseURL :: Lens' Form (Maybe Text) fResponseURL = lens _fResponseURL (\ s a -> s{_fResponseURL = a}) instance FromJSON Form where parseJSON = withObject "Form" (\ o -> Form' <$> (o .:? "thumbnailUrl") <*> (o .:? "formUrl") <*> (o .:? "title") <*> (o .:? "responseUrl")) instance ToJSON Form where toJSON Form'{..} = object (catMaybes [("thumbnailUrl" .=) <$> _fThumbnailURL, ("formUrl" .=) <$> _fFormURL, ("title" .=) <$> _fTitle, ("responseUrl" .=) <$> _fResponseURL]) -- | Response when listing teachers. -- -- /See:/ 'listTeachersResponse' smart constructor. data ListTeachersResponse = ListTeachersResponse' { _ltrNextPageToken :: !(Maybe Text) , _ltrTeachers :: !(Maybe [Teacher]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ListTeachersResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ltrNextPageToken' -- -- * 'ltrTeachers' listTeachersResponse :: ListTeachersResponse listTeachersResponse = ListTeachersResponse' { _ltrNextPageToken = Nothing , _ltrTeachers = Nothing } -- | Token identifying the next page of results to return. If empty, no -- further results are available. ltrNextPageToken :: Lens' ListTeachersResponse (Maybe Text) ltrNextPageToken = lens _ltrNextPageToken (\ s a -> s{_ltrNextPageToken = a}) -- | Teachers who match the list request. ltrTeachers :: Lens' ListTeachersResponse [Teacher] ltrTeachers = lens _ltrTeachers (\ s a -> s{_ltrTeachers = a}) . _Default . _Coerce instance FromJSON ListTeachersResponse where parseJSON = withObject "ListTeachersResponse" (\ o -> ListTeachersResponse' <$> (o .:? "nextPageToken") <*> (o .:? "teachers" .!= mempty)) instance ToJSON ListTeachersResponse where toJSON ListTeachersResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _ltrNextPageToken, ("teachers" .=) <$> _ltrTeachers]) -- | Student in a course. -- -- /See:/ 'student' smart constructor. data Student = Student' { _sCourseId :: !(Maybe Text) , _sProFile :: !(Maybe UserProFile) , _sStudentWorkFolder :: !(Maybe DriveFolder) , _sUserId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Student' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sCourseId' -- -- * 'sProFile' -- -- * 'sStudentWorkFolder' -- -- * 'sUserId' student :: Student student = Student' { _sCourseId = Nothing , _sProFile = Nothing , _sStudentWorkFolder = Nothing , _sUserId = Nothing } -- | Identifier of the course. Read-only. sCourseId :: Lens' Student (Maybe Text) sCourseId = lens _sCourseId (\ s a -> s{_sCourseId = a}) -- | Global user information for the student. Read-only. sProFile :: Lens' Student (Maybe UserProFile) sProFile = lens _sProFile (\ s a -> s{_sProFile = a}) -- | Information about a Drive Folder for this student\'s work in this -- course. Only visible to the student and domain administrators. -- Read-only. sStudentWorkFolder :: Lens' Student (Maybe DriveFolder) sStudentWorkFolder = lens _sStudentWorkFolder (\ s a -> s{_sStudentWorkFolder = a}) -- | Identifier of the user. When specified as a parameter of a request, this -- identifier can be one of the following: * the numeric identifier for the -- user * the email address of the user * the string literal \`\"me\"\`, -- indicating the requesting user sUserId :: Lens' Student (Maybe Text) sUserId = lens _sUserId (\ s a -> s{_sUserId = a}) instance FromJSON Student where parseJSON = withObject "Student" (\ o -> Student' <$> (o .:? "courseId") <*> (o .:? "profile") <*> (o .:? "studentWorkFolder") <*> (o .:? "userId")) instance ToJSON Student where toJSON Student'{..} = object (catMaybes [("courseId" .=) <$> _sCourseId, ("profile" .=) <$> _sProFile, ("studentWorkFolder" .=) <$> _sStudentWorkFolder, ("userId" .=) <$> _sUserId])
rueshyna/gogol
gogol-classroom/gen/Network/Google/Classroom/Types/Product.hs
mpl-2.0
93,104
0
27
23,844
17,740
10,219
7,521
1,950
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.ConsumerSurveys.Surveys.Stop -- 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) -- -- Stops a running survey. -- -- /See:/ <https://developers.google.com/surveys/ Consumer Surveys API Reference> for @consumersurveys.surveys.stop@. module Network.Google.Resource.ConsumerSurveys.Surveys.Stop ( -- * REST Resource SurveysStopResource -- * Creating a Request , surveysStop , SurveysStop -- * Request Lenses , sResourceId ) where import Network.Google.ConsumerSurveys.Types import Network.Google.Prelude -- | A resource alias for @consumersurveys.surveys.stop@ method which the -- 'SurveysStop' request conforms to. type SurveysStopResource = "consumersurveys" :> "v2" :> "surveys" :> Capture "resourceId" Text :> "stop" :> QueryParam "alt" AltJSON :> Post '[JSON] SurveysStopResponse -- | Stops a running survey. -- -- /See:/ 'surveysStop' smart constructor. newtype SurveysStop = SurveysStop' { _sResourceId :: Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SurveysStop' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sResourceId' surveysStop :: Text -- ^ 'sResourceId' -> SurveysStop surveysStop pSResourceId_ = SurveysStop' {_sResourceId = pSResourceId_} sResourceId :: Lens' SurveysStop Text sResourceId = lens _sResourceId (\ s a -> s{_sResourceId = a}) instance GoogleRequest SurveysStop where type Rs SurveysStop = SurveysStopResponse type Scopes SurveysStop = '["https://www.googleapis.com/auth/consumersurveys", "https://www.googleapis.com/auth/userinfo.email"] requestClient SurveysStop'{..} = go _sResourceId (Just AltJSON) consumerSurveysService where go = buildClient (Proxy :: Proxy SurveysStopResource) mempty
brendanhay/gogol
gogol-consumersurveys/gen/Network/Google/Resource/ConsumerSurveys/Surveys/Stop.hs
mpl-2.0
2,703
0
13
619
305
187
118
50
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DeploymentManager.Operations.List -- 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) -- -- Lists all operations for a project. -- -- /See:/ <https://cloud.google.com/deployment-manager/ Google Cloud Deployment Manager API Reference> for @deploymentmanager.operations.list@. module Network.Google.Resource.DeploymentManager.Operations.List ( -- * REST Resource OperationsListResource -- * Creating a Request , operationsList , OperationsList -- * Request Lenses , olOrderBy , olProject , olFilter , olPageToken , olMaxResults ) where import Network.Google.DeploymentManager.Types import Network.Google.Prelude -- | A resource alias for @deploymentmanager.operations.list@ method which the -- 'OperationsList' request conforms to. type OperationsListResource = "deploymentmanager" :> "v2" :> "projects" :> Capture "project" Text :> "global" :> "operations" :> QueryParam "orderBy" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] OperationsListResponse -- | Lists all operations for a project. -- -- /See:/ 'operationsList' smart constructor. data OperationsList = OperationsList' { _olOrderBy :: !(Maybe Text) , _olProject :: !Text , _olFilter :: !(Maybe Text) , _olPageToken :: !(Maybe Text) , _olMaxResults :: !(Textual Word32) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OperationsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'olOrderBy' -- -- * 'olProject' -- -- * 'olFilter' -- -- * 'olPageToken' -- -- * 'olMaxResults' operationsList :: Text -- ^ 'olProject' -> OperationsList operationsList pOlProject_ = OperationsList' { _olOrderBy = Nothing , _olProject = pOlProject_ , _olFilter = Nothing , _olPageToken = Nothing , _olMaxResults = 500 } -- | Sorts list results by a certain order. By default, results are returned -- in alphanumerical order based on the resource name. You can also sort -- results in descending order based on the creation timestamp using -- orderBy=\"creationTimestamp desc\". This sorts results based on the -- creationTimestamp field in reverse chronological order (newest result -- first). Use this to sort resources like operations so that the newest -- operation is returned first. Currently, only sorting by name or -- creationTimestamp desc is supported. olOrderBy :: Lens' OperationsList (Maybe Text) olOrderBy = lens _olOrderBy (\ s a -> s{_olOrderBy = a}) -- | The project ID for this request. olProject :: Lens' OperationsList Text olProject = lens _olProject (\ s a -> s{_olProject = a}) -- | Sets a filter expression for filtering listed resources, in the form -- filter={expression}. Your {expression} must be in the format: field_name -- comparison_string literal_string. The field_name is the name of the -- field you want to compare. Only atomic field types are supported -- (string, number, boolean). The comparison_string must be either eq -- (equals) or ne (not equals). The literal_string is the string value to -- filter to. The literal value must be valid for the type of field you are -- filtering by (string, number, boolean). For string fields, the literal -- value is interpreted as a regular expression using RE2 syntax. The -- literal value must match the entire field. For example, to filter for -- instances that do not have a name of example-instance, you would use -- filter=name ne example-instance. You can filter on nested fields. For -- example, you could filter on instances that have set the -- scheduling.automaticRestart field to true. Use filtering on nested -- fields to take advantage of labels to organize and search for results -- based on label values. To filter on multiple expressions, provide each -- separate expression within parentheses. For example, -- (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple -- expressions are treated as AND expressions, meaning that resources must -- match all expressions to pass the filters. olFilter :: Lens' OperationsList (Maybe Text) olFilter = lens _olFilter (\ s a -> s{_olFilter = a}) -- | Specifies a page token to use. Set pageToken to the nextPageToken -- returned by a previous list request to get the next page of results. olPageToken :: Lens' OperationsList (Maybe Text) olPageToken = lens _olPageToken (\ s a -> s{_olPageToken = a}) -- | The maximum number of results per page that should be returned. If the -- number of available results is larger than maxResults, Compute Engine -- returns a nextPageToken that can be used to get the next page of results -- in subsequent list requests. olMaxResults :: Lens' OperationsList Word32 olMaxResults = lens _olMaxResults (\ s a -> s{_olMaxResults = a}) . _Coerce instance GoogleRequest OperationsList where type Rs OperationsList = OperationsListResponse type Scopes OperationsList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/ndev.cloudman", "https://www.googleapis.com/auth/ndev.cloudman.readonly"] requestClient OperationsList'{..} = go _olProject _olOrderBy _olFilter _olPageToken (Just _olMaxResults) (Just AltJSON) deploymentManagerService where go = buildClient (Proxy :: Proxy OperationsListResource) mempty
rueshyna/gogol
gogol-deploymentmanager/gen/Network/Google/Resource/DeploymentManager/Operations/List.hs
mpl-2.0
6,574
0
18
1,441
679
409
270
94
1
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } autocheckCases = [ ("Never Deadlocks", representative deadlocksNever) , ("No Exceptions", representative exceptionsNever) , ("Consistent Result", alwaysSame) -- already representative ]
lspitzner/brittany
data/Test521.hs
agpl-3.0
308
0
7
39
41
25
16
4
1
module Model.AssetSegment.TypesTest (test_all) where import Test.Tasty import Test.Tasty.HUnit import Model.Asset.Types import Model.AssetSlot.Types import Model.AssetSegment.Types import Model.Container.Types import Model.Id.Types import Model.Release.Types import Model.Segment (fullSegment) import Model.Slot.Types import Model.TypeOrphans () import Model.Volume.Types -- See -- https://projects.databrary.org/confluence/pages/viewpage.action?pageId=18449565 -- for an explanation of testgetAssetSegmentRelease2. Short version: this needs -- refactoring. test_all :: [TestTree] test_all = [ testCase "testgetAssetSegmentRelease2" $ testgetAssetSegmentRelease2 @?= [ ( EffectiveRelease { effRelPublic = ReleasePRIVATE , effRelPrivate = ReleasePRIVATE } , EffectiveRelease { effRelPublic = ReleasePRIVATE , effRelPrivate = ReleasePRIVATE } ) , ( EffectiveRelease { effRelPublic = ReleasePRIVATE , effRelPrivate = ReleasePRIVATE } , EffectiveRelease { effRelPublic = ReleasePRIVATE , effRelPrivate = ReleasePRIVATE } ) , ( EffectiveRelease { effRelPublic = ReleasePUBLIC , effRelPrivate = ReleasePUBLIC } , EffectiveRelease { effRelPublic = ReleasePUBLIC , effRelPrivate = ReleasePUBLIC } ) , ( EffectiveRelease { effRelPublic = ReleasePUBLIC , effRelPrivate = ReleasePUBLIC } , EffectiveRelease { effRelPublic = ReleasePUBLIC , effRelPrivate = ReleasePUBLIC } ) , ( EffectiveRelease { effRelPublic = ReleaseSHARED , effRelPrivate = ReleaseSHARED } , EffectiveRelease { effRelPublic = ReleaseSHARED , effRelPrivate = ReleaseSHARED } ) , ( EffectiveRelease { effRelPublic = ReleasePRIVATE , effRelPrivate = ReleasePRIVATE } , EffectiveRelease { effRelPublic = ReleasePRIVATE , effRelPrivate = ReleasePRIVATE } ) ] ] testmakeAssetSegment :: AssetSlot -> Bool -> Maybe Release -> AssetSegment testmakeAssetSegment as hasExcerpt mRel = AssetSegment { segmentAsset = as , assetSegment = fullSegment , assetExcerpt = if hasExcerpt then Just (newExcerpt as fullSegment mRel) else Nothing } testmakeAssetSlot :: Id Volume -> Maybe Release -> Maybe Slot -> AssetSlot testmakeAssetSlot vid mRel ms = let asset = blankAsset (testmakeVolume vid) asset2 = asset { assetRow = (assetRow asset) { assetRelease = mRel } } in AssetSlot {slotAsset = asset2, assetSlot = ms} containerAssetSlot :: Maybe Release -> AssetSlot containerAssetSlot mRel = testmakeAssetSlot realVolumeId mRel (Just testmakeSlot) testmakeSlot :: Slot testmakeSlot = Slot { slotContainer = Container { containerRow = ContainerRow { containerId = Id 200 , containerTop = False , containerName = Nothing , containerDate = Nothing } , containerRelease = Nothing , containerVolume = realVolume } , slotSegment = fullSegment } testmakeVolume :: Id Volume -> Volume testmakeVolume vid = blankVolume { volumeRow = (volumeRow blankVolume) { volumeId = vid } } realVolume :: Volume realVolume = testmakeVolume realVolumeId realVolumeId :: Id Volume realVolumeId = Id 100 noExcerptContainerAssetNoRelease :: AssetSegment excerptNoReleaseContainerAssetNoRelease :: AssetSegment excerptNoReleaseContainerAssetHasRelease :: AssetSegment excerptPublicReleaseContainerAssetNoRelease :: AssetSegment excerptSharedReleaseContainerAssetNoRelease :: AssetSegment excerptPrivateReleaseContainerAssetNoRelease :: AssetSegment noExcerptContainerAssetNoRelease = testmakeAssetSegment (containerAssetSlot Nothing) False Nothing excerptNoReleaseContainerAssetNoRelease = testmakeAssetSegment (containerAssetSlot Nothing) True Nothing excerptNoReleaseContainerAssetHasRelease = testmakeAssetSegment (containerAssetSlot (Just ReleasePUBLIC)) True Nothing excerptPublicReleaseContainerAssetNoRelease = testmakeAssetSegment (containerAssetSlot Nothing) True (Just ReleasePUBLIC) excerptSharedReleaseContainerAssetNoRelease = testmakeAssetSegment (containerAssetSlot Nothing) True (Just ReleaseSHARED) excerptPrivateReleaseContainerAssetNoRelease = testmakeAssetSegment (containerAssetSlot Nothing) True (Just ReleasePRIVATE) assetReleaseForPartialAndFullShared :: EffectiveRelease privateReleaseIgnoreSharing :: EffectiveRelease excerptReleaseForPartialAndFullShared :: EffectiveRelease excerptReleaseForPartialAndFullShared' :: EffectiveRelease excerptReleaseForPartialAndFullShared'' :: EffectiveRelease assetReleaseForPartialAndFullShared = EffectiveRelease ReleasePUBLIC ReleasePUBLIC privateReleaseIgnoreSharing = EffectiveRelease ReleasePRIVATE ReleasePRIVATE excerptReleaseForPartialAndFullShared = EffectiveRelease ReleasePUBLIC ReleasePUBLIC excerptReleaseForPartialAndFullShared' = EffectiveRelease ReleaseSHARED ReleaseSHARED excerptReleaseForPartialAndFullShared'' = EffectiveRelease ReleasePRIVATE ReleasePRIVATE {- test cases: (focus on excerpt present or not test to begin with -- has excerpt -- excerpt rel, assetslot rel , pub vol res , priv vol res -- x x priv priv -- DONE -- x has val (pub) pub pub ------ see asset slot tests --- -- DONE -- pub x pub pub -- DONE -- share x share priv?? -- DONE -- priv x priv priv -- DONE -- pub pub pub pub -- TODO: what other cases matter? -- no excerpt -- see asset slot tests -- DONE -} testgetAssetSegmentRelease2 :: [(EffectiveRelease, EffectiveRelease)] testgetAssetSegmentRelease2 = [ ( getAssetSegmentRelease2 noExcerptContainerAssetNoRelease , privateReleaseIgnoreSharing ) , ( getAssetSegmentRelease2 excerptNoReleaseContainerAssetNoRelease , privateReleaseIgnoreSharing ) , ( getAssetSegmentRelease2 excerptNoReleaseContainerAssetHasRelease , assetReleaseForPartialAndFullShared ) -- wrong? , ( getAssetSegmentRelease2 excerptPublicReleaseContainerAssetNoRelease , excerptReleaseForPartialAndFullShared ) , ( getAssetSegmentRelease2 excerptSharedReleaseContainerAssetNoRelease , excerptReleaseForPartialAndFullShared' ) -- wrong? , ( getAssetSegmentRelease2 excerptPrivateReleaseContainerAssetNoRelease , excerptReleaseForPartialAndFullShared'' ) ] -- END TODO
databrary/databrary
test/Model/AssetSegment/TypesTest.hs
agpl-3.0
7,230
0
13
2,012
1,023
595
428
132
2
{-# LANGUAGE PackageImports #-} module ProjectM36.Sessions where import Control.Concurrent.STM #if MIN_VERSION_stm_containers(1,0,0) import qualified StmContainers.Map as StmMap import qualified StmContainers.Set as StmSet #else import qualified STMContainers.Map as StmMap import qualified STMContainers.Set as StmSet #endif import ProjectM36.Attribute import ProjectM36.Base import ProjectM36.Session import ProjectM36.Relation import ProjectM36.Error import qualified Data.UUID as U #if MIN_VERSION_stm_containers(1,0,0) import qualified Control.Foldl as Foldl import qualified DeferredFolds.UnfoldlM as UF #else import "list-t" ListT #endif type Sessions = StmMap.Map SessionId Session --from https://github.com/nikita-volkov/stm-containers/blob/master/test/Main/MapTests.hs stmMapToList :: StmMap.Map k v -> STM [(k, v)] #if MIN_VERSION_stm_containers(1,0,0) stmMapToList = UF.foldM (Foldl.generalize Foldl.list) . StmMap.unfoldlM #else stmMapToList = ListT.fold (\l -> return . (:l)) [] . StmMap.stream #endif stmSetToList :: StmSet.Set v -> STM [v] #if MIN_VERSION_stm_containers(1,0,0) stmSetToList = UF.foldM (Foldl.generalize Foldl.list) . StmSet.unfoldlM #else stmSetToList = ListT.fold (\l -> return . (:l)) [] . StmSet.stream #endif uuidAtom :: U.UUID -> Atom uuidAtom = TextAtom . U.toText sessionsAsRelation :: Sessions -> STM (Either RelationalError Relation) sessionsAsRelation sessions = do sessionAssocs <- stmMapToList sessions let atomMatrix = map (\(sessionId, session) -> [uuidAtom sessionId, uuidAtom (parentId session)]) sessionAssocs pure $ mkRelationFromList (attributesFromList [Attribute "sessionid" TextAtomType, Attribute "parentCommit" TextAtomType]) atomMatrix
agentm/project-m36
src/lib/ProjectM36/Sessions.hs
unlicense
1,735
0
16
224
344
195
149
25
1
module PowerDivisibility.A254733Spec (main, spec) where import Test.Hspec import PowerDivisibility.A254733 (a254733) main :: IO () main = hspec spec spec :: Spec spec = describe "A254733" $ it "correctly computes the first 20 elements" $ take 20 (map a254733 [1..]) `shouldBe` expectedValue where expectedValue = [2,4,6,6,10,12,14,10,12,20,22,18,26,28,30,20,34,24,38,30]
peterokagey/haskellOEIS
test/PowerDivisibility/A254733Spec.hs
apache-2.0
385
0
10
59
160
95
65
10
1
-- Copyright 2020 Google LLC -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module Chain2Dupe where import Chain1 () chain2Dupe f = appendFile f "e"
google/hrepl
hrepl/tests/Chain2Dupe.hs
apache-2.0
664
0
5
115
36
26
10
3
1
module Codec.JVM.Const (Const(..), ConstVal(..), constTag, constValType, cclass, cstring, cint, clong, cfloat, cdouble, getObjConst, isConstCategory2 ) where import Data.Text (Text) import Data.Word (Word8) import Data.Int (Int32,Int64) import Codec.JVM.Types (IClassName(..), FieldRef, FieldType(..), MethodRef, PrimType(..), NameAndDesc, jlString, mkFieldDesc') constTag :: Const -> Word8 constTag (CUTF8 _) = 1 constTag (CValue (CInteger _)) = 3 constTag (CValue (CFloat _)) = 4 constTag (CValue (CLong _)) = 5 constTag (CValue (CDouble _)) = 6 constTag (CClass _) = 7 constTag (CValue (CString _)) = 8 constTag (CFieldRef _) = 9 constTag (CMethodRef _) = 10 constTag (CInterfaceMethodRef _)= 11 constTag (CNameAndType _) = 12 -- | https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4 data Const = CUTF8 Text | CValue ConstVal | CClass IClassName | CFieldRef FieldRef | CMethodRef MethodRef | CInterfaceMethodRef MethodRef | CNameAndType NameAndDesc deriving (Eq, Ord, Show) -- | https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.2-300-C.1 data ConstVal = CString Text | CInteger Int32 | CLong Int64 | CFloat Float | CDouble Double deriving (Eq, Ord, Show) -- instance Show ConstVal where -- show (CInteger x) = show x -- concat ["Int ", show x] -- show (CString x) = show x -- concat ["String ", show x] -- show (CLong x) show x -- show (CFloat x) = show x constValType :: ConstVal -> FieldType constValType (CString _) = ObjectType jlString constValType (CInteger _) = BaseType JInt constValType (CLong _) = BaseType JLong constValType (CFloat _) = BaseType JFloat constValType (CDouble _) = BaseType JDouble cclass :: IClassName -> Const cclass = CClass cstring :: Text -> Const cstring = CValue . CString clong :: Int64 -> Const clong = CValue . CLong cint :: Int32 -> Const cint = CValue . CInteger cfloat :: Float -> Const cfloat = CValue . CFloat cdouble :: Double -> Const cdouble = CValue . CDouble getObjConst :: FieldType -> Maybe Const getObjConst (ObjectType iclass) = Just $ cclass iclass getObjConst ft@(ArrayType _) = Just $ cclass (IClassName $ mkFieldDesc' ft) getObjConst _ = Nothing isConstCategory2 :: Const -> Bool isConstCategory2 (CValue x) | CLong _ <- x = True | CDouble _ <- x = True isConstCategory2 _ = False
rahulmutt/codec-jvm
src/Codec/JVM/Const.hs
apache-2.0
2,451
0
9
514
761
414
347
75
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} {-# OPTIONS_GHC -fno-warn-missing-import-lists #-} {-| Module : Reflex.Dom.HTML5.Component.Common.DrawFuns Description : Helpers to build components. Copyright : (c) gspia 2018 License : BSD3 Maintainer : gspia = Drawing functions Use these or take one as starting point to build your own. Function 'drawNothing' is defined in module "CompEvent". The drawing is done in adeCombFun that is in "CompEvent"-module. There are variants of that function, too. Those put in place the listening, drawing and using of events together. -} module Reflex.Dom.HTML5.Component.Common.DrawFuns ( -- * Drawing functions for components (table cells, tree nodes, etc) drawDivContent , drawDivContentS , drawDCCommon , drawDivWdt , drawDivContentEx , drawDivActElemEx , drawDivAECntEx , elemAttrs ) where import Control.Lens import Control.Monad (join) import Data.Semigroup ((<>)) import Data.Text (Text) import qualified Data.Text as T -- import Language.Javascript.JSaddle import Reflex import Reflex.Dom.Core -- import Reflex.Dom.HTML5.Component.Table.ActElem -- import Reflex.Dom.HTML5.Component.Table.Common import Reflex.Dom.HTML5.Component.Common.StateInfo -- import Reflex.Dom.HTML5.Component.Common.CompEvent import qualified Reflex.Dom.HTML5.Attrs as A import qualified Reflex.Dom.HTML5.Elements as E -------------------------------------------------------------------------------- -- | This forms Dynamic attributes for element @elm@. elemAttrs ∷ (Reflex t, A.AttrHasGlobals elm) ⇒ elm → ActiveState t e r → Dynamic t elm elemAttrs elm actS = dUse where dA = _activeStateActive actS dNA = not <$> _activeStateActivable actS dAGl = (`A.attrSetGlobals` elm) <$> _activeStateActiveGl actS dNAGl = (`A.attrSetGlobals` elm) <$> _activeStateNotActiveGl actS dNAvGl = (`A.attrSetGlobals` elm) <$> _activeStateNotActivableGl actS dUse = (\ba bna acl nacl navcl → if bna then navcl else if ba then acl else nacl ) <$> dA <*> dNA <*> dAGl <*> dNAGl <*> dNAvGl -------------------------------------------------------------------------------- -- | Draw content on a div that allows events to go. The provided class-attributes -- for not activable, active and not active elements (cells/nodes) are used. -- Note that this is only used on how to show things. drawDivContent ∷ forall t m e r. (Reflex t, DomBuilder t m, PostBuild t m , DomBuilderSpace m ~ GhcjsDomSpace , ActSelem e, ActSretval r) ⇒ Dynamic t Text -- ^ The element that we are drawing (the dynamic text of it). → ActiveState t e r -- ^ The activity information of the element @e@ together with -- the value to be returned (of type @Dynamic t r@). → m (Element EventResult (DomBuilderSpace m) t, Dynamic t r) -- ^ Reflex element with dynamic value (of type @r@). -- (The dynamic value is not used in this example, -- it is default value.) drawDivContent = drawDCCommon id -- | Similar to 'drawDivContent' but the showed element is showable. drawDivContentS ∷ forall t m a e r. (Reflex t, DomBuilder t m, PostBuild t m , Show a, DomBuilderSpace m ~ GhcjsDomSpace , ActSelem e, ActSretval r) ⇒ Dynamic t a → ActiveState t e r → m (Element EventResult (DomBuilderSpace m) t, Dynamic t r) drawDivContentS = drawDCCommon (T.pack . show) -- | See 'drawDivContent'. drawDCCommon ∷ forall t m a e r. (Reflex t, DomBuilder t m, PostBuild t m -- , Show a, DomBuilderSpace m ~ GhcjsDomSpace , DomBuilderSpace m ~ GhcjsDomSpace , ActSelem e, ActSretval r) ⇒ (a → Text) → Dynamic t a → ActiveState t e r → m (Element EventResult (DomBuilderSpace m) t, Dynamic t r) drawDCCommon txtFun dElm actS = do let dUse = elemAttrs E.defDiv actS -- let dA = _activeStateActive actS -- dNA = not <$> _activeStateActivable actS -- dAGl = (`A.attrSetGlobals` E.defDiv) <$> _activeStateActiveGl actS -- dNAGl = (`A.attrSetGlobals` E.defDiv) <$> _activeStateNotActiveGl actS -- dNAvGl = (`A.attrSetGlobals` E.defDiv) <$> _activeStateNotActivableGl actS -- dUse = -- (\ba bna acl nacl navcl → -- if bna -- then navcl -- else if ba -- then acl -- else nacl -- ) -- <$> dA <*> dNA <*> dAGl <*> dNAGl <*> dNAvGl (eRes,_) ← E.divD' dUse $ -- text $ txtFun elm dynText $ txtFun <$> dElm pure (eRes, defRetval) -- | See 'drawDivContent' and 'drawDCCommon'. drawDivWdt ∷ forall t m a e r. (Reflex t, DomBuilder t m, PostBuild t m -- , Show a, DomBuilderSpace m ~ GhcjsDomSpace , DomBuilderSpace m ~ GhcjsDomSpace , ActSelem e, ActSretval r) ⇒ (a → Dynamic t Text) → Dynamic t a → ActiveState t e r → m (Element EventResult (DomBuilderSpace m) t, Dynamic t r) drawDivWdt txtFun dElm actS = do let dUse = elemAttrs E.defDiv actS (eRes,_) ← E.divD' dUse $ dynText $ join $ txtFun <$> dElm pure (eRes, defRetval) -- | An example of a function that draws a some content for, e.g. li- or td- -- elements. -- -- The drawing function is -- given the "cell name" (ActElem), the "cell contents" (a), and "cell state" -- (ActiveState) that can be used to decide, how to draw. -- This function shows the "cell contents" only together with activity -- information. And similarly for nodes in the trees. drawDivContentEx ∷ forall t m a e r. (Reflex t, DomBuilder t m, PostBuild t m , Show a, DomBuilderSpace m ~ GhcjsDomSpace , ActSelem e, ActSretval r) ⇒ Dynamic t a → ActiveState t e r → m (Element EventResult (DomBuilderSpace m) t, Dynamic t r) drawDivContentEx dElm actS = do (e,_) ← E.divN' $ do -- text $ (T.pack . show $ elm) <> " : " dynText $ T.pack . show <$> dElm text " : " dynText $ (T.pack . show) <$> _activeStateActive actS pure (e, defRetval) -- | An example of a function that draws a li- or td-content. -- This function shows the ActElem only together with activity information. drawDivActElemEx ∷ forall t m a e r. (Reflex t, DomBuilder t m, PostBuild t m , DomBuilderSpace m ~ GhcjsDomSpace , ActSelem e, ActSretval r, Show e) ⇒ Dynamic t a → ActiveState t e r → m (Element EventResult (DomBuilderSpace m) t, Dynamic t r) drawDivActElemEx _dA actS = do (e,_) ← E.divN' $ do text $ (T.pack . show $ view activeStateElemId actS) <> " : " dynText $ (T.pack . show) <$> _activeStateActive actS pure (e, defRetval) -- | An example of a function that draws a td-content. -- This function shows both the ActElem and "cell contents". drawDivAECntEx ∷ forall t m a e r. (Reflex t, DomBuilder t m, PostBuild t m , Show a, DomBuilderSpace m ~ GhcjsDomSpace , ActSelem e, ActSretval r, Show e) ⇒ Dynamic t a → ActiveState t e r → m (Element EventResult (DomBuilderSpace m) t, Dynamic t r) drawDivAECntEx dElm actS = do (e,_) ← E.divN' $ do text $ psh (view activeStateElemId actS) <> " : " let dTxt = psh <$> dElm -- text $ psh (view activeStateElemId actS) <> " : " <> psh elm <> " : " dynText dTxt text $ " : " dynText $ psh <$> _activeStateActive actS text " : avable " dynText $ psh <$> view activeStateActivable actS pure (e, defRetval) where psh ∷ Show b ⇒ b → T.Text psh = T.pack . show
gspia/reflex-dom-htmlea
lib/src/Reflex/Dom/HTML5/Component/Common/DrawFuns.hs
bsd-3-clause
8,890
0
16
2,939
1,694
912
782
123
3
{-# LANGUAGE OverloadedStrings #-} module DTX2MIDI.MIDI ( MIDI (..), updateInitialTempo, bpmToTempo, ) where import Codec.Midi (Midi (..)) import qualified Codec.Midi as Midi type MIDI = Midi type BPM = Double -- | Euterpeaの固定テンポ(bpm = 120, tempo = 500000)を上書きする updateInitialTempo :: Midi.Tempo -> MIDI -> MIDI updateInitialTempo tempo midi = midi {Midi.tracks = mapTrack update $ Midi.tracks midi} where mapTrack f tracks = map (map f) tracks update (0, Midi.TempoChange 500000) = (0, Midi.TempoChange tempo) update t = t -- bpm (beat/minute) を tempo (μs/beat) に変換する bpmToTempo :: BPM -> Midi.Tempo bpmToTempo bpm = round $ 1000000 / (bpm / 60)
akiomik/dtx2midi
src/DTX2MIDI/MIDI.hs
bsd-3-clause
718
0
10
134
201
114
87
17
2
import DSL.Abstract.Api type Literal = String a, b, c :: Literal a = "A" b = "B" c = "C" example1 :: Model Literal example1 = Abst [a, b, c] [(a, b), (b, c)] example2 :: Model Literal example2 = Abst [a, b] [(a, b), (b, a)] d, e :: Literal d = "D" e = "E" example3 :: Model Literal example3 = Abst [a, b, c, d] [(a, a), (a, c), (b, c), (c, d)] example4 :: Model Literal example4 = Abst [a, b, c, d, e] [(a, b), (b, a), (b, c), (c, d), (d, e), (e, c)]
shingoOKAWA/hsarg-haskell
src/DSL/Abstract/Test.hs
bsd-3-clause
503
0
7
152
294
183
111
17
1
module Renderer where import StringUtils import Category import PaymentTracker import Data.Char import Data.List (intercalate) chartPaymentsByCat :: [Payment] -> String chartPaymentsByCat payments = let presentable = presentableChartForCats . percentPerCategory $ payments catsChart = map joinCategoryAndBars presentable in unlines catsChart presentableChartForCats :: [(Category, Percent)] -> [(String, String)] presentableChartForCats catPercents = let formattedCats = alignStrings $ map (show . fst) catPercents pixels = map percentToChartPixels $ map snd catPercents in zip formattedCats pixels joinCategoryAndBars :: (String, String) -> String joinCategoryAndBars (cat, bars) = cat ++ colon ++ bars percentToChartPixels :: Percent -> String percentToChartPixels val = intercalate emptyString $ take (ceiling $ val / 10) (repeat chartPixel) -- renderPaymentsOfCategory :: [(Category, [Payment])] -> Category -> String renderPaymentsOfCategory paysPerCat cat = let paysOfCat = extractPaymentsOfCat paysPerCat cat in case paysOfCat of Nothing -> emptyString (Just pays) -> unlines $ [formatCatAndItsTotalPaid cat pays] ++ alignPayments pays extractPaymentsOfCat :: [(Category, [Payment])] -> Category -> Maybe [Payment] extractPaymentsOfCat paysPerCat cat = let paysForCat = filter (\(c, _) -> c == cat) paysPerCat in if (length paysForCat) == 0 then Nothing else Just (snd . head $ paysForCat) formatCatAndItsTotalPaid :: Category -> [Payment] -> String formatCatAndItsTotalPaid cat payments = (show cat) ++ colon ++ spaceStr ++ (show $ totalPaid payments) alignPayments :: [Payment] -> [String] alignPayments payments = let alignedDesc = alignStrings $ map description payments values = map (show . value) payments in map (\(desc, val) -> desc ++ arrow ++ val) (zip alignedDesc values) -- renderWarnings :: Maybe [Warning] -> String renderWarnings Nothing = emptyString renderWarnings (Just warns) = unlines $ alignWarnings warns alignWarnings :: [Warning] -> [String] alignWarnings warns = let alignedCats = alignStrings $ map (show . categ) warns overs = map (show . overPaid) warns in map (\(cat, over) -> cat ++ arrow ++ over) (zip alignedCats overs) -- Bar Charts for money spent on each category in different months -- Bar Chart for FOOD, for CLOTHES, etc. barChartCategories :: [(String, [Payment])] -> [String] barChartCategories monthsPayments = let monthsSpentOnCat = categoryPaidOverMonths monthsPayments in map barChartCatSpentMonths monthsSpentOnCat barChartCatSpentMonths :: (Category, [(String, Money)]) -> String barChartCatSpentMonths (cat, monthsSpent) = let alignedMonths = alignStrings $ map fst monthsSpent barPixels = map valueToPixel $ map snd monthsSpent monthPixels = zip alignedMonths barPixels graphBars = map (\(month, pix) -> month ++ colon ++ pix) monthPixels in unlines $ [map toUpper (name cat), emptyString] ++ graphBars valueToPixel :: Money -> String valueToPixel money = intercalate emptyString $ take (ceiling $ money / 50) (repeat chartPixel)
Sam-Serpoosh/WatchIt
src/Renderer.hs
bsd-3-clause
3,121
0
13
542
984
521
463
58
2
{-# LANGUAGE DeriveDataTypeable #-} -- | Possible options passed to The ABS-Haskell compiler module ABS.Compiler.CmdOpt where import System.Console.CmdArgs import System.IO.Unsafe (unsafePerformIO) {-# NOINLINE cmdOpt #-} cmdOpt :: CmdOpt cmdOpt = unsafePerformIO (cmdArgs cmdOptSpec) data CmdOpt = CmdOpt { abs_sources :: [FilePath] -- ^ The input ABS module files (ending in .abs) or ABS directories , output_dir :: FilePath -- ^ In which directory to put all the Haskell translated files (.hs files) , create_script :: Bool -- ^ creates a helper bash script for easier invoking the ghc Haskell compiler and puts it in the outputdir , dump_ast :: Bool -- ^ A flag to dump the parsed AST to stderr , nostdlib :: Bool } deriving (Show, Data, Typeable) cmdOptSpec :: CmdOpt cmdOptSpec = CmdOpt { abs_sources = def &= args &= typ "FILES/DIRS" , output_dir = "gen/haskell" &= typDir &= help "In which directory to put all the Haskell translated files (.hs files)" , create_script = def &= help "If given, creates a helper bash script for easier invoking the ghc Haskell compiler." , dump_ast = def &= help "A flag to dump the parsed AST to stderr" , nostdlib = def &= help "Will not include by-default the ABS.StdLib module. You have to do it manually with an import declaration." } &= program "habs" &= help "A transcompiler from the ABS language to Haskell. Expects as input the ABS module files (ending in .abs) or whole directories containing ABS code." &= helpArg [explicit, name "h", name "help"] &= summary ("The ABS-Haskell compiler, Nikolaos Bezirgiannis, Envisage Project") -- summary is --version
abstools/habs
src/ABS/Compiler/CmdOpt.hs
bsd-3-clause
1,787
0
12
445
239
137
102
25
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Applicative import Control.Concurrent (forkIO, killThread) import qualified Control.Exception as CE import Control.Monad (unless) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C8 import qualified Data.ByteString.Lazy as LB import Data.Char (toLower, isSpace) import Network.Socket () import System.IO (withFile, hSetBinaryMode, IOMode(..), openBinaryFile, hClose, hIsEOF) import Options import Data.Certificate.KeyRSA (decodePrivate) import Data.Certificate.X509 (X509, decodeCertificate) import Data.PEM (pemParseLBS, pemContent) import qualified Network.TLS as TLS import Network.SPDY.Server data ProgOptions = ProgOptions { optCertFile :: String, optKeyFile :: String, optPort :: Int, optStaticDir :: String, optNoTLS :: Bool } instance Options ProgOptions where defineOptions = pure ProgOptions <*> simpleOption "cert-file" "server-cert.pem" "The certificate file to use for TLS. Default is 'server-cert.pem'." <*> simpleOption "key-file" "server-private-key.pem" ("The private key file to use for TLS. " ++ "Default is 'server-private-key.pem'.") <*> simpleOption "port" 16000 "The port on which to accept incoming connections. Default is 16000." <*> simpleOption "static-dir" "." "The static directory from which to serve files." <*> simpleOption "no-tls" False "Don't use TLS." main :: IO () main = runCommand $ \opts _ -> do let port = fromIntegral $ optPort opts useTLS = not $ optNoTLS opts staticDir = optStaticDir opts sopts = defaultServerOptions { soptIncomingRequestHandler = requestHandler staticDir } theServer <- server sopts tid <- forkIO (if useTLS then runTLSServer' port (optCertFile opts) (optKeyFile opts) theServer else runSocketServer port theServer) quitLoop tid where runTLSServer' port certFile keyFile theServer = do cert <- getCertificate certFile key <- getKey keyFile runTLSServer port cert key theServer quitLoop tid = do s <- getLine let s' = map toLower $ dropWhile isSpace s case s' of 'q':_ -> killThread tid _ -> quitLoop tid -- TODO: why is 'maybePuller' unused here? requestHandler :: FilePath -> RequestHandler requestHandler staticDir (HeaderBlock pairs) maybePuller = maybe badRequest forPath $ lookup (HeaderName ":path") pairs where badRequest = return (responseHeaders 400, Nothing) forPath (HeaderValue pathBytes) = CE.catch (do h <- openBinaryFile (toFilePath pathBytes) ReadMode return (responseHeaders 200, Just $ sendFile h)) notFound toFilePath pathBytes = relativeTo staticDir (C8.unpack pathBytes) relativeTo staticDir path = staticDir ++ "/" ++ path sendFile h pushContent = CE.finally loop (hClose h) where loop = do chunk <- B.hGetSome h 1200 isLast <- hIsEOF h pushContent $ moreData chunk isLast unless isLast loop notFound :: CE.IOException -> IO (HeaderBlock, Maybe a) notFound _ = return (responseHeaders 404, Nothing) responseHeaders statusCode = HeaderBlock [httpStatus statusCode, http1_1Version] getCertificate :: String -> IO X509 getCertificate certFileName = withFile certFileName ReadMode $ \h -> hSetBinaryMode h True >> LB.hGetContents h >>= either (error . ("decodeCertificate: " ++)) return . decodeCertificate . either (error . ("pemParseLBS: " ++)) (LB.fromChunks . map pemContent) . pemParseLBS getKey :: String -> IO TLS.PrivateKey getKey keyFileName = fmap TLS.PrivRSA $ withFile keyFileName ReadMode $ \h -> hSetBinaryMode h True >> LB.hGetContents h >>= either (error . ("decodePrivate: " ++)) (return . snd) . decodePrivate . either (error . ("pemParseLBS: " ++)) (LB.fromChunks . map pemContent) . pemParseLBS
kcharter/spdy-base
examples/SServe.hs
bsd-3-clause
4,156
0
15
1,047
1,084
563
521
91
3
{-# LANGUAGE TypeFamilies, FlexibleContexts, TypeOperators, FlexibleInstances #-} -- | -- Module : Control.FiniteStateMachine -- Copyright : (C) Robert Atkey 2013 -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : unknown -- -- This module contains a type class capturing finite state machines -- over arbitrary input alphabets. This class has the following -- features: -- -- * When reaching an accepting state, a value may be returned. See -- the 'isAcceptingState' function. -- -- * Very large alphabets (e.g., unicode) are supported by means of -- the 'classes' function. module Data.FiniteStateMachine ( -- * Finite State Machines: definition and simulation FiniteStateMachine (..) , runFSM -- * Combinators for 'FiniteStateMachine's , (:==>) (..) , Literal (..) ) where import Data.RangeSet (Partition, fromSet, singleton) import Data.Monoid (mempty) import Data.Maybe (listToMaybe, mapMaybe) import Data.Foldable (foldMap) -- | Class of types whose inhabitants represent finite state -- machines. Members of this type class should be /finite/ state. So -- there can only be a finite number of possible states reachable from -- 'initState' via 'advance'. FIXME: mention why this doesn't -- necessarily mean that the 'State fsm' type is an instance of -- 'Bounded'. class ( Ord (State fsm) , Eq (State fsm) , Enum (Alphabet fsm) , Ord (Alphabet fsm) , Bounded (Alphabet fsm)) => FiniteStateMachine fsm where -- | The type of states of finite state acceptors of this type. data State fsm :: * -- | The type of symbols recognised by this type of finite state -- acceptor. type Alphabet fsm :: * -- | The type of results returned by this type of finite state -- acceptor on acceptance of an input sequence. type Result fsm :: * -- | The initial state of a given finite state acceptor of this -- type. initState :: fsm -> State fsm -- | State transition function given an input token from the -- alphabet of this finite state acceptor. advance :: fsm -> Alphabet fsm -> State fsm -> State fsm -- | Determine whether the given state is an accepting state of -- the finite state acceptor. If so, return the result value for -- this accepting state. isAcceptingState :: fsm -> State fsm -> Maybe (Result fsm) -- | Returns a partition of the alphabet of this finite state -- acceptor such that for each equivalence class in the partition, -- it is the case that 'advance fsm c1 s == advance fsm c2 -- s'. FIXME: explain this better. classes :: fsm -> State fsm -> Partition (Alphabet fsm) -------------------------------------------------------------------------------- -- | Really should be fixed length vectors, but I can't be -- bothered. FIXME: might be easier with the data kinds stuff. instance FiniteStateMachine fsm => FiniteStateMachine [fsm] where data State [fsm] = ListFSMState { unListFSMState :: [State fsm] } type Alphabet [fsm] = Alphabet fsm type Result [fsm] = Result fsm initState fsms = ListFSMState (map initState fsms) advance fsms c = ListFSMState . map (\(fsm,s) -> advance fsm c s) . zip fsms . unListFSMState isAcceptingState fsm = listToMaybe . mapMaybe (uncurry isAcceptingState) . zip fsm . unListFSMState classes fsm = foldMap (uncurry classes) . zip fsm . unListFSMState instance Eq (State fsm) => Eq (State [fsm]) where ListFSMState s1 == ListFSMState s2 = s1 == s2 instance Ord (State fsm) => Ord (State [fsm]) where compare (ListFSMState s1) (ListFSMState s2) = compare s1 s2 -------------------------------------------------------------------------------- -- | A tuple type intended for attaching result values to existing -- 'FiniteStateMachine's. data fsm :==> a = fsm :==> a deriving (Eq, Ord, Show) infixr 5 :==> -- | Attaching results to 'FiniteStateMachine's instance (FiniteStateMachine fsm) => FiniteStateMachine (fsm :==> a) where data State (fsm :==> a) = TaggedFSMState { unTaggedFSMState :: State fsm } type Alphabet (fsm :==> a) = Alphabet fsm type Result (fsm :==> a) = a initState (fsm :==> a) = TaggedFSMState $ initState fsm advance (fsm :==> a) c = TaggedFSMState . advance fsm c . unTaggedFSMState isAcceptingState (fsm :==> a) = fmap (const a) . isAcceptingState fsm . unTaggedFSMState classes (fsm :==> a) = classes fsm . unTaggedFSMState instance Eq (State fsm) => Eq (State (fsm :==> a)) where TaggedFSMState s1 == TaggedFSMState s2 = s1 == s2 instance Ord (State fsm) => Ord (State (fsm :==> a)) where compare (TaggedFSMState s1) (TaggedFSMState s2) = compare s1 s2 -------------------------------------------------------------------------------- -- | Treat a list of items as a 'FiniteStateMachine'. As a -- 'FiniteStateMachine', @Literal l@ accepts exactly the list of -- symbols @l@. newtype Literal a = Literal [a] -- | Treat a list of items as a 'FiniteStateMachine'. As a -- 'FiniteStateMachine', @Literal l@ accepts exactly the list of -- symbols @l@. instance (Bounded a, Enum a, Ord a) => FiniteStateMachine (Literal a) where data State (Literal a) = Expecting [a] | Error deriving (Eq, Ord) type Alphabet (Literal a) = a type Result (Literal a) = () initState (Literal l) = Expecting l advance _ c Error = Error advance _ c (Expecting []) = Error advance _ c (Expecting (c':cs)) | c == c' = Expecting cs | otherwise = Error isAcceptingState _ (Expecting []) = Just () isAcceptingState _ _ = Nothing classes _ Error = mempty classes _ (Expecting []) = mempty classes _ (Expecting (c:_)) = fromSet (singleton c) -------------------------------------------------------------------------------- -- | Simulate a finite state machine on an input sequence. The input -- sequence should be finite. runFSM :: FiniteStateMachine fsm => fsm -- ^ A finite state machine -> [Alphabet fsm] -- ^ Input sequence, should be finite -> Maybe (Result fsm) -- ^ @Nothing@ if the sequence is not -- accepted by the finite state -- machine. @Just x@ if the whole -- sequence is accepted runFSM fsm input = run (initState fsm) input where run q [] = isAcceptingState fsm q run q (x:xs) = run (advance fsm x q) xs
bobatkey/Forvie
src/Data/FiniteStateMachine.hs
bsd-3-clause
6,764
0
12
1,735
1,399
749
650
94
2
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.AMD.SamplePositions -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/AMD/sample_positions.txt AMD_sample_positions> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.AMD.SamplePositions ( -- * Enums gl_SUBSAMPLE_DISTANCE_AMD, -- * Functions glSetMultisamplefvAMD ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/AMD/SamplePositions.hs
bsd-3-clause
755
0
4
88
49
40
9
5
0
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} module Data.Logic.CNF where import Data.Logic.Atomic.Class import Data.Logic.Boolean.Class import Data.Logic.Decidable import Data.Logic.Embed import Data.Logic.Propositional.Class import Data.Logic.Modal.Class import Data.Logic.Render import Data.Logic.Util import Test.QuickCheck (CoArbitrary(..), Arbitrary(..)) type StrProp r = (Atomic String r, Propositional r) type StrMode m r = (Atomic String r, Modal m r) -- PushNeg {{{ newtype PushNeg r = PushNeg { pushNeg :: Bool -> r } pushNeg_ :: PushNeg r -> r pushNeg_ = ($ False) . pushNeg instance Arbitrary r => Arbitrary (PushNeg r) where arbitrary = PushNeg <$> arbitrary shrink p = [PushNeg q | q <- shrink $ pushNeg p] instance Propositional r => Embed r (PushNeg r) where embed p = PushNeg $ neg p ? p lower p = pushNeg p False instance (Propositional r, EmbedStar a r) => EmbedStar a (PushNeg r) instance Contextual r (PushNeg r) where type Context (PushNeg r) = (->) Bool embedCxt = PushNeg lowerCxt = pushNeg instance ContextStar a r => ContextStar a (PushNeg r) where type AllContext (PushNeg r) = Compose (Context (PushNeg r)) (AllContext r) instance (Atomic a r, Propositional r) => Atomic a (PushNeg r) where atom = embed . atom instance (Boolean r, Propositional r) => Boolean (PushNeg r) where tt = embed tt ff = embed ff instance Propositional r => Propositional (PushNeg r) where neg = mapCxt (. not) (.|.) = distribCxt2 $ (.&.) ? (.|.) (.&.) = distribCxt2 $ (.|.) ? (.&.) (.^.) = distribCxt2_ (.^.) instance (Modal m r, Propositional r) => Modal m (PushNeg r) where square m = distribCxt1 $ diamond m ? square m diamond m = distribCxt1 $ square m ? diamond m -- }}} -- PushDisj {{{ newtype PushDisj r = PushDisj { pushDisj :: Maybe r -> r } pushDisj_ :: PushDisj r -> r pushDisj_ = ($ Nothing) . pushDisj instance (Arbitrary r, CoArbitrary r) => Arbitrary (PushDisj r) where arbitrary = PushDisj <$> arbitrary instance Propositional r => Embed r (PushDisj r) where embed p = PushDisj $ maybe p (p .|.) lower p = pushDisj p Nothing instance (Propositional r, EmbedStar a r) => EmbedStar a (PushDisj r) instance Contextual r (PushDisj r) where type Context (PushDisj r) = (->) (Maybe r) embedCxt = PushDisj lowerCxt = pushDisj instance ContextStar a r => ContextStar a (PushDisj r) where type AllContext (PushDisj r) = Compose (Context (PushDisj r)) (AllContext r) instance (Atomic a r, Propositional r) => Atomic a (PushDisj r) where atom = embed . atom instance (Boolean r, Propositional r) => Boolean (PushDisj r) where tt = embed tt ff = embed ff instance Propositional r => Propositional (PushDisj r) where neg = placeCxt1_ neg (.|.) = apChainCxtR (.&.) = distribCxt2_ (.&.) instance (Modal m r, Propositional r) => Modal m (PushDisj r) where square = placeCxt1_ . square diamond = placeCxt1_ . diamond -- }}} -- PushConj {{{ newtype PushConj r = PushConj { pushConj :: Maybe r -> r } pushConj_ :: PushConj r -> r pushConj_ = ($ Nothing) . pushConj instance (Arbitrary r, CoArbitrary r) => Arbitrary (PushConj r) where arbitrary = PushConj <$> arbitrary instance Propositional r => Embed r (PushConj r) where embed p = PushConj $ maybe p (p .&.) lower p = pushConj p Nothing instance (Propositional r, EmbedStar a r) => EmbedStar a (PushConj r) instance Contextual r (PushConj r) where type Context (PushConj r) = (->) (Maybe r) embedCxt = PushConj lowerCxt = pushConj instance ContextStar a r => ContextStar a (PushConj r) where type AllContext (PushConj r) = Compose (Context (PushConj r)) (AllContext r) instance (Atomic a r, Propositional r) => Atomic a (PushConj r) where atom = embed . atom instance (Boolean r, Propositional r) => Boolean (PushConj r) where tt = embed tt ff = embed ff instance Propositional r => Propositional (PushConj r) where neg = placeCxt1_ neg (.|.) = apChainCxtR (.&.) = distribCxt2_ (.&.) instance (Modal m r, Propositional r) => Modal m (PushConj r) where square = placeCxt1_ . square diamond = placeCxt1_ . diamond -- }}} p0 :: StrProp r => r p0 = neg (atom "A" .|. atom "B") p1 :: StrProp r => r p1 = atom "C" .|. (atom "A" .&. atom "B") p2 :: StrProp r => r p2 = (atom "A" .&. atom "B") .|. atom "C" p3 :: StrProp r => r p3 = (atom "A" .|. atom "B") .|. atom "C" p4 :: StrProp r => r p4 = ((atom "A" .|. atom "B") .|. atom "C") .|. ((atom "D" .|. atom "E") .|. atom "F") .|. atom "G" testProp :: PushNeg (PushDisj (PushConj Render)) -> IO () testProp = renderIO . pushConj_ . pushDisj_ . pushNeg_ m0 :: StrMode Alethic r => r m0 = neg $ nec $ atom "A"
kylcarte/finally-logical
src/Data/Logic/CNF.hs
bsd-3-clause
4,908
0
11
991
1,929
1,023
906
120
1
module Main where import Data.Maybe import Lib main :: IO () main = print . fromMaybe "Problem not solved" $ problem "15"
anup-2s/project-euler
app/Main.hs
bsd-3-clause
124
0
7
24
41
22
19
5
1
{-| Module : Idris.IBC Description : Core representations and code to generate IBC files. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} {-# OPTIONS_GHC -fwarn-unused-imports #-} module Idris.IBC (loadIBC, loadPkgIndex, writeIBC, writePkgIndex, hasValidIBCVersion, IBCPhase(..)) where import Idris.AbsSyntax import Idris.Core.CaseTree import Idris.Core.Evaluate import Idris.Core.TT import Idris.DeepSeq () import Idris.Docstrings (Docstring) import qualified Idris.Docstrings as D import Idris.Error import Idris.Imports import Idris.Options import Idris.Output import IRTS.System (getIdrisLibDir) import qualified Cheapskate.Types as CT import Codec.Archive.Zip import Control.DeepSeq import Control.Monad import Data.Binary import Data.ByteString.Lazy as B hiding (elem, length, map) import Data.List as L import Data.Maybe (catMaybes) import qualified Data.Set as S import System.Directory import System.FilePath ibcVersion :: Word16 ibcVersion = 164 -- | When IBC is being loaded - we'll load different things (and omit -- different structures/definitions) depending on which phase we're in. data IBCPhase = IBC_Building -- ^ when building the module tree | IBC_REPL Bool -- ^ when loading modules for the REPL Bool = True for top level module deriving (Show, Eq) data IBCFile = IBCFile { ver :: Word16 , sourcefile :: FilePath , ibc_imports :: ![(Bool, FilePath)] , ibc_importdirs :: ![FilePath] , ibc_sourcedirs :: ![FilePath] , ibc_implicits :: ![(Name, [PArg])] , ibc_fixes :: ![FixDecl] , ibc_statics :: ![(Name, [Bool])] , ibc_interfaces :: ![(Name, InterfaceInfo)] , ibc_records :: ![(Name, RecordInfo)] , ibc_implementations :: ![(Bool, Bool, Name, Name)] , ibc_dsls :: ![(Name, DSL)] , ibc_datatypes :: ![(Name, TypeInfo)] , ibc_optimise :: ![(Name, OptInfo)] , ibc_syntax :: ![Syntax] , ibc_keywords :: ![String] , ibc_objs :: ![(Codegen, FilePath)] , ibc_libs :: ![(Codegen, String)] , ibc_cgflags :: ![(Codegen, String)] , ibc_dynamic_libs :: ![String] , ibc_hdrs :: ![(Codegen, String)] , ibc_totcheckfail :: ![(FC, String)] , ibc_flags :: ![(Name, [FnOpt])] , ibc_fninfo :: ![(Name, FnInfo)] , ibc_cg :: ![(Name, CGInfo)] , ibc_docstrings :: ![(Name, (Docstring D.DocTerm, [(Name, Docstring D.DocTerm)]))] , ibc_moduledocs :: ![(Name, Docstring D.DocTerm)] , ibc_transforms :: ![(Name, (Term, Term))] , ibc_errRev :: ![(Term, Term)] , ibc_errReduce :: ![Name] , ibc_coercions :: ![Name] , ibc_lineapps :: ![(FilePath, Int, PTerm)] , ibc_namehints :: ![(Name, Name)] , ibc_metainformation :: ![(Name, MetaInformation)] , ibc_errorhandlers :: ![Name] , ibc_function_errorhandlers :: ![(Name, Name, Name)] -- fn, arg, handler , ibc_metavars :: ![(Name, (Maybe Name, Int, [Name], Bool, Bool))] , ibc_patdefs :: ![(Name, ([([(Name, Term)], Term, Term)], [PTerm]))] , ibc_postulates :: ![Name] , ibc_externs :: ![(Name, Int)] , ibc_parsedSpan :: !(Maybe FC) , ibc_usage :: ![(Name, Int)] , ibc_exports :: ![Name] , ibc_autohints :: ![(Name, Name)] , ibc_deprecated :: ![(Name, String)] , ibc_defs :: ![(Name, Def)] , ibc_total :: ![(Name, Totality)] , ibc_injective :: ![(Name, Injectivity)] , ibc_access :: ![(Name, Accessibility)] , ibc_fragile :: ![(Name, String)] , ibc_constraints :: ![(FC, UConstraint)] , ibc_langexts :: ![LanguageExt] } deriving Show {-! deriving instance Binary IBCFile !-} initIBC :: IBCFile initIBC = IBCFile ibcVersion "" [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] Nothing [] [] [] [] [] [] [] [] [] [] [] hasValidIBCVersion :: FilePath -> Idris Bool hasValidIBCVersion fp = do archiveFile <- runIO $ B.readFile fp case toArchiveOrFail archiveFile of Left _ -> return False Right archive -> do ver <- getEntry 0 "ver" archive return (ver == ibcVersion) loadIBC :: Bool -- ^ True = reexport, False = make everything private -> IBCPhase -> FilePath -> Idris () loadIBC reexport phase fp = do logIBC 1 $ "loadIBC (reexport, phase, fp)" ++ show (reexport, phase, fp) imps <- getImported logIBC 3 $ "loadIBC imps" ++ show imps case lookup fp imps of Nothing -> load True Just p -> if (not p && reexport) then load False else return () where load fullLoad = do logIBC 1 $ "Loading ibc " ++ fp ++ " " ++ show reexport archiveFile <- runIO $ B.readFile fp case toArchiveOrFail archiveFile of Left _ -> do ifail $ fp ++ " isn't loadable, it may have an old ibc format.\n" ++ "Please clean and rebuild it." Right archive -> do if fullLoad then process reexport phase archive fp else unhide phase fp archive addImported reexport fp -- | Load an entire package from its index file loadPkgIndex :: String -> Idris () loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir addImportDir (ddir </> pkg) fp <- findPkgIndex pkg loadIBC True IBC_Building fp makeEntry :: (Binary b) => String -> [b] -> Maybe Entry makeEntry name val = if L.null val then Nothing else Just $ toEntry name 0 (encode val) entries :: IBCFile -> [Entry] entries i = catMaybes [Just $ toEntry "ver" 0 (encode $ ver i), makeEntry "sourcefile" (sourcefile i), makeEntry "ibc_imports" (ibc_imports i), makeEntry "ibc_importdirs" (ibc_importdirs i), makeEntry "ibc_sourcedirs" (ibc_sourcedirs i), makeEntry "ibc_implicits" (ibc_implicits i), makeEntry "ibc_fixes" (ibc_fixes i), makeEntry "ibc_statics" (ibc_statics i), makeEntry "ibc_interfaces" (ibc_interfaces i), makeEntry "ibc_records" (ibc_records i), makeEntry "ibc_implementations" (ibc_implementations i), makeEntry "ibc_dsls" (ibc_dsls i), makeEntry "ibc_datatypes" (ibc_datatypes i), makeEntry "ibc_optimise" (ibc_optimise i), makeEntry "ibc_syntax" (ibc_syntax i), makeEntry "ibc_keywords" (ibc_keywords i), makeEntry "ibc_objs" (ibc_objs i), makeEntry "ibc_libs" (ibc_libs i), makeEntry "ibc_cgflags" (ibc_cgflags i), makeEntry "ibc_dynamic_libs" (ibc_dynamic_libs i), makeEntry "ibc_hdrs" (ibc_hdrs i), makeEntry "ibc_totcheckfail" (ibc_totcheckfail i), makeEntry "ibc_flags" (ibc_flags i), makeEntry "ibc_fninfo" (ibc_fninfo i), makeEntry "ibc_cg" (ibc_cg i), makeEntry "ibc_docstrings" (ibc_docstrings i), makeEntry "ibc_moduledocs" (ibc_moduledocs i), makeEntry "ibc_transforms" (ibc_transforms i), makeEntry "ibc_errRev" (ibc_errRev i), makeEntry "ibc_errReduce" (ibc_errReduce i), makeEntry "ibc_coercions" (ibc_coercions i), makeEntry "ibc_lineapps" (ibc_lineapps i), makeEntry "ibc_namehints" (ibc_namehints i), makeEntry "ibc_metainformation" (ibc_metainformation i), makeEntry "ibc_errorhandlers" (ibc_errorhandlers i), makeEntry "ibc_function_errorhandlers" (ibc_function_errorhandlers i), makeEntry "ibc_metavars" (ibc_metavars i), makeEntry "ibc_patdefs" (ibc_patdefs i), makeEntry "ibc_postulates" (ibc_postulates i), makeEntry "ibc_externs" (ibc_externs i), toEntry "ibc_parsedSpan" 0 . encode <$> ibc_parsedSpan i, makeEntry "ibc_usage" (ibc_usage i), makeEntry "ibc_exports" (ibc_exports i), makeEntry "ibc_autohints" (ibc_autohints i), makeEntry "ibc_deprecated" (ibc_deprecated i), makeEntry "ibc_defs" (ibc_defs i), makeEntry "ibc_total" (ibc_total i), makeEntry "ibc_injective" (ibc_injective i), makeEntry "ibc_access" (ibc_access i), makeEntry "ibc_fragile" (ibc_fragile i), makeEntry "ibc_langexts" (ibc_langexts i)] -- TODO: Put this back in shortly after minimising/pruning constraints -- makeEntry "ibc_constraints" (ibc_constraints i)] writeArchive :: FilePath -> IBCFile -> Idris () writeArchive fp i = do let a = L.foldl (\x y -> addEntryToArchive y x) emptyArchive (entries i) runIO $ B.writeFile fp (fromArchive a) writeIBC :: FilePath -> FilePath -> Idris () writeIBC src f = do logIBC 2 $ "Writing IBC for: " ++ show f iReport 2 $ "Writing IBC for: " ++ show f i <- getIState resetNameIdx ibcf <- mkIBC (ibc_write i) (initIBC { sourcefile = src, ibc_langexts = idris_language_extensions i }) idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f) writeArchive f ibcf logIBC 2 "Written") (\c -> do logIBC 2 $ "Failed " ++ pshow i c) return () -- | Write a package index containing all the imports in the current -- IState Used for ':search' of an entire package, to ensure -- everything is loaded. writePkgIndex :: FilePath -> Idris () writePkgIndex f = do i <- getIState let imps = map (\ (x, y) -> (True, x)) $ idris_imported i logIBC 2 $ "Writing package index " ++ show f ++ " including\n" ++ show (map snd imps) resetNameIdx let ibcf = initIBC { ibc_imports = imps, ibc_langexts = idris_language_extensions i } idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f) writeArchive f ibcf logIBC 2 "Written") (\c -> do logIBC 2 $ "Failed " ++ pshow i c) return () mkIBC :: [IBCWrite] -> IBCFile -> Idris IBCFile mkIBC [] f = return f mkIBC (i:is) f = do ist <- getIState logIBC 5 $ show i ++ " " ++ show (L.length is) f' <- ibc ist i f mkIBC is f' ibc :: IState -> IBCWrite -> IBCFile -> Idris IBCFile ibc i (IBCFix d) f = return f { ibc_fixes = d : ibc_fixes f } ibc i (IBCImp n) f = case lookupCtxtExact n (idris_implicits i) of Just v -> return f { ibc_implicits = (n,v): ibc_implicits f } _ -> ifail "IBC write failed" ibc i (IBCStatic n) f = case lookupCtxtExact n (idris_statics i) of Just v -> return f { ibc_statics = (n,v): ibc_statics f } _ -> ifail "IBC write failed" ibc i (IBCInterface n) f = case lookupCtxtExact n (idris_interfaces i) of Just v -> return f { ibc_interfaces = (n,v): ibc_interfaces f } _ -> ifail "IBC write failed" ibc i (IBCRecord n) f = case lookupCtxtExact n (idris_records i) of Just v -> return f { ibc_records = (n,v): ibc_records f } _ -> ifail "IBC write failed" ibc i (IBCImplementation int res n ins) f = return f { ibc_implementations = (int, res, n, ins) : ibc_implementations f } ibc i (IBCDSL n) f = case lookupCtxtExact n (idris_dsls i) of Just v -> return f { ibc_dsls = (n,v): ibc_dsls f } _ -> ifail "IBC write failed" ibc i (IBCData n) f = case lookupCtxtExact n (idris_datatypes i) of Just v -> return f { ibc_datatypes = (n,v): ibc_datatypes f } _ -> ifail "IBC write failed" ibc i (IBCOpt n) f = case lookupCtxtExact n (idris_optimisation i) of Just v -> return f { ibc_optimise = (n,v): ibc_optimise f } _ -> ifail "IBC write failed" ibc i (IBCSyntax n) f = return f { ibc_syntax = n : ibc_syntax f } ibc i (IBCKeyword n) f = return f { ibc_keywords = n : ibc_keywords f } ibc i (IBCImport n) f = return f { ibc_imports = n : ibc_imports f } ibc i (IBCImportDir n) f = return f { ibc_importdirs = n : ibc_importdirs f } ibc i (IBCSourceDir n) f = return f { ibc_sourcedirs = n : ibc_sourcedirs f } ibc i (IBCObj tgt n) f = return f { ibc_objs = (tgt, n) : ibc_objs f } ibc i (IBCLib tgt n) f = return f { ibc_libs = (tgt, n) : ibc_libs f } ibc i (IBCCGFlag tgt n) f = return f { ibc_cgflags = (tgt, n) : ibc_cgflags f } ibc i (IBCDyLib n) f = return f {ibc_dynamic_libs = n : ibc_dynamic_libs f } ibc i (IBCHeader tgt n) f = return f { ibc_hdrs = (tgt, n) : ibc_hdrs f } ibc i (IBCDef n) f = do f' <- case lookupDefExact n (tt_ctxt i) of Just v -> return f { ibc_defs = (n,v) : ibc_defs f } _ -> ifail "IBC write failed" case lookupCtxtExact n (idris_patdefs i) of Just v -> return f' { ibc_patdefs = (n,v) : ibc_patdefs f } _ -> return f' -- Not a pattern definition ibc i (IBCDoc n) f = case lookupCtxtExact n (idris_docstrings i) of Just v -> return f { ibc_docstrings = (n,v) : ibc_docstrings f } _ -> ifail "IBC write failed" ibc i (IBCCG n) f = case lookupCtxtExact n (idris_callgraph i) of Just v -> return f { ibc_cg = (n,v) : ibc_cg f } _ -> ifail "IBC write failed" ibc i (IBCCoercion n) f = return f { ibc_coercions = n : ibc_coercions f } ibc i (IBCAccess n a) f = return f { ibc_access = (n,a) : ibc_access f } ibc i (IBCFlags n) f = case lookupCtxtExact n (idris_flags i) of Just a -> return f { ibc_flags = (n,a): ibc_flags f } _ -> ifail "IBC write failed" ibc i (IBCFnInfo n a) f = return f { ibc_fninfo = (n,a) : ibc_fninfo f } ibc i (IBCTotal n a) f = return f { ibc_total = (n,a) : ibc_total f } ibc i (IBCInjective n a) f = return f { ibc_injective = (n,a) : ibc_injective f } ibc i (IBCTrans n t) f = return f { ibc_transforms = (n, t) : ibc_transforms f } ibc i (IBCErrRev t) f = return f { ibc_errRev = t : ibc_errRev f } ibc i (IBCErrReduce t) f = return f { ibc_errReduce = t : ibc_errReduce f } ibc i (IBCLineApp fp l t) f = return f { ibc_lineapps = (fp,l,t) : ibc_lineapps f } ibc i (IBCNameHint (n, ty)) f = return f { ibc_namehints = (n, ty) : ibc_namehints f } ibc i (IBCMetaInformation n m) f = return f { ibc_metainformation = (n,m) : ibc_metainformation f } ibc i (IBCErrorHandler n) f = return f { ibc_errorhandlers = n : ibc_errorhandlers f } ibc i (IBCFunctionErrorHandler fn a n) f = return f { ibc_function_errorhandlers = (fn, a, n) : ibc_function_errorhandlers f } ibc i (IBCMetavar n) f = case lookup n (idris_metavars i) of Nothing -> return f Just t -> return f { ibc_metavars = (n, t) : ibc_metavars f } ibc i (IBCPostulate n) f = return f { ibc_postulates = n : ibc_postulates f } ibc i (IBCExtern n) f = return f { ibc_externs = n : ibc_externs f } ibc i (IBCTotCheckErr fc err) f = return f { ibc_totcheckfail = (fc, err) : ibc_totcheckfail f } ibc i (IBCParsedRegion fc) f = return f { ibc_parsedSpan = Just fc } ibc i (IBCModDocs n) f = case lookupCtxtExact n (idris_moduledocs i) of Just v -> return f { ibc_moduledocs = (n,v) : ibc_moduledocs f } _ -> ifail "IBC write failed" ibc i (IBCUsage n) f = return f { ibc_usage = n : ibc_usage f } ibc i (IBCExport n) f = return f { ibc_exports = n : ibc_exports f } ibc i (IBCAutoHint n h) f = return f { ibc_autohints = (n, h) : ibc_autohints f } ibc i (IBCDeprecate n r) f = return f { ibc_deprecated = (n, r) : ibc_deprecated f } ibc i (IBCFragile n r) f = return f { ibc_fragile = (n,r) : ibc_fragile f } ibc i (IBCConstraint fc u) f = return f { ibc_constraints = (fc, u) : ibc_constraints f } getEntry :: (Binary b, NFData b) => b -> FilePath -> Archive -> Idris b getEntry alt f a = case findEntryByPath f a of Nothing -> return alt Just e -> return $! (force . decode . fromEntry) e unhide :: IBCPhase -> FilePath -> Archive -> Idris () unhide phase fp ar = do processImports True phase fp ar processAccess True phase ar process :: Bool -- ^ Reexporting -> IBCPhase -> Archive -> FilePath -> Idris () process reexp phase archive fn = do ver <- getEntry 0 "ver" archive when (ver /= ibcVersion) $ do logIBC 2 "ibc out of date" let e = if ver < ibcVersion then "an earlier" else "a later" ldir <- runIO $ getIdrisLibDir let start = if ldir `L.isPrefixOf` fn then "This external module" else "This module" let end = case L.stripPrefix ldir fn of Nothing -> "Please clean and rebuild." Just ploc -> unwords ["Please reinstall:", L.head $ splitDirectories ploc] ifail $ unlines [ unwords ["Incompatible ibc version for:", show fn] , unwords [start , "was built with" , e , "version of Idris."] , end ] source <- getEntry "" "sourcefile" archive srcok <- runIO $ doesFileExist source when srcok $ timestampOlder source fn processImportDirs archive processSourceDirs archive processImports reexp phase fn archive processImplicits archive processInfix archive processStatics archive processInterfaces archive processRecords archive processImplementations archive processDSLs archive processDatatypes archive processOptimise archive processSyntax archive processKeywords archive processObjectFiles fn archive processLibs archive processCodegenFlags archive processDynamicLibs archive processHeaders archive processPatternDefs archive processFlags archive processFnInfo archive processTotalityCheckError archive processCallgraph archive processDocs archive processModuleDocs archive processCoercions archive processTransforms archive processErrRev archive processErrReduce archive processLineApps archive processNameHints archive processMetaInformation archive processErrorHandlers archive processFunctionErrorHandlers archive processMetaVars archive processPostulates archive processExterns archive processParsedSpan archive processUsage archive processExports archive processAutoHints archive processDeprecate archive processDefs archive processTotal archive processInjective archive processAccess reexp phase archive processFragile archive processConstraints archive processLangExts phase archive timestampOlder :: FilePath -> FilePath -> Idris () timestampOlder src ibc = do srct <- runIO $ getModificationTime src ibct <- runIO $ getModificationTime ibc if (srct > ibct) then ifail $ unlines [ "Module needs reloading:" , unwords ["\tSRC :", show src] , unwords ["\tModified at:", show srct] , unwords ["\tIBC :", show ibc] , unwords ["\tModified at:", show ibct] ] else return () processPostulates :: Archive -> Idris () processPostulates ar = do ns <- getEntry [] "ibc_postulates" ar updateIState (\i -> i { idris_postulates = idris_postulates i `S.union` S.fromList ns }) processExterns :: Archive -> Idris () processExterns ar = do ns <- getEntry [] "ibc_externs" ar updateIState (\i -> i{ idris_externs = idris_externs i `S.union` S.fromList ns }) processParsedSpan :: Archive -> Idris () processParsedSpan ar = do fc <- getEntry Nothing "ibc_parsedSpan" ar updateIState (\i -> i { idris_parsedSpan = fc }) processUsage :: Archive -> Idris () processUsage ar = do ns <- getEntry [] "ibc_usage" ar updateIState (\i -> i { idris_erasureUsed = ns ++ idris_erasureUsed i }) processExports :: Archive -> Idris () processExports ar = do ns <- getEntry [] "ibc_exports" ar updateIState (\i -> i { idris_exports = ns ++ idris_exports i }) processAutoHints :: Archive -> Idris () processAutoHints ar = do ns <- getEntry [] "ibc_autohints" ar mapM_ (\(n,h) -> addAutoHint n h) ns processDeprecate :: Archive -> Idris () processDeprecate ar = do ns <- getEntry [] "ibc_deprecated" ar mapM_ (\(n,reason) -> addDeprecated n reason) ns processFragile :: Archive -> Idris () processFragile ar = do ns <- getEntry [] "ibc_fragile" ar mapM_ (\(n,reason) -> addFragile n reason) ns processConstraints :: Archive -> Idris () processConstraints ar = do cs <- getEntry [] "ibc_constraints" ar mapM_ (\ (fc, c) -> addConstraints fc (0, [c])) cs processImportDirs :: Archive -> Idris () processImportDirs ar = do fs <- getEntry [] "ibc_importdirs" ar mapM_ addImportDir fs processSourceDirs :: Archive -> Idris () processSourceDirs ar = do fs <- getEntry [] "ibc_sourcedirs" ar mapM_ addSourceDir fs processImports :: Bool -> IBCPhase -> FilePath -> Archive -> Idris () processImports reexp phase fname ar = do fs <- getEntry [] "ibc_imports" ar mapM_ (\(re, f) -> do i <- getIState ibcsd <- valIBCSubDir i ids <- rankedImportDirs fname putIState (i { imported = f : imported i }) let (phase', reexp') = case phase of IBC_REPL True -> (IBC_REPL False, reexp) IBC_REPL False -> (IBC_Building, reexp && re) p -> (p, reexp && re) fp <- findIBC ids ibcsd f logIBC 4 $ "processImports (fp, phase')" ++ show (fp, phase') case fp of Nothing -> do logIBC 2 $ "Failed to load ibc " ++ f Just fn -> do loadIBC reexp' phase' fn) fs processImplicits :: Archive -> Idris () processImplicits ar = do imps <- getEntry [] "ibc_implicits" ar mapM_ (\ (n, imp) -> do i <- getIState case lookupDefAccExact n False (tt_ctxt i) of Just (n, Hidden) -> return () Just (n, Private) -> return () _ -> putIState (i { idris_implicits = addDef n imp (idris_implicits i) })) imps processInfix :: Archive -> Idris () processInfix ar = do f <- getEntry [] "ibc_fixes" ar updateIState (\i -> i { idris_infixes = sort $ f ++ idris_infixes i }) processStatics :: Archive -> Idris () processStatics ar = do ss <- getEntry [] "ibc_statics" ar mapM_ (\ (n, s) -> updateIState (\i -> i { idris_statics = addDef n s (idris_statics i) })) ss processInterfaces :: Archive -> Idris () processInterfaces ar = do cs <- getEntry [] "ibc_interfaces" ar mapM_ (\ (n, c) -> do i <- getIState -- Don't lose implementations from previous IBCs, which -- could have loaded in any order let is = case lookupCtxtExact n (idris_interfaces i) of Just ci -> interface_implementations ci _ -> [] let c' = c { interface_implementations = interface_implementations c ++ is } putIState (i { idris_interfaces = addDef n c' (idris_interfaces i) })) cs processRecords :: Archive -> Idris () processRecords ar = do rs <- getEntry [] "ibc_records" ar mapM_ (\ (n, r) -> updateIState (\i -> i { idris_records = addDef n r (idris_records i) })) rs processImplementations :: Archive -> Idris () processImplementations ar = do cs <- getEntry [] "ibc_implementations" ar mapM_ (\ (i, res, n, ins) -> addImplementation i res n ins) cs processDSLs :: Archive -> Idris () processDSLs ar = do cs <- getEntry [] "ibc_dsls" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_dsls = addDef n c (idris_dsls i) })) cs processDatatypes :: Archive -> Idris () processDatatypes ar = do cs <- getEntry [] "ibc_datatypes" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_datatypes = addDef n c (idris_datatypes i) })) cs processOptimise :: Archive -> Idris () processOptimise ar = do cs <- getEntry [] "ibc_optimise" ar mapM_ (\ (n, c) -> updateIState (\i -> i { idris_optimisation = addDef n c (idris_optimisation i) })) cs processSyntax :: Archive -> Idris () processSyntax ar = do s <- getEntry [] "ibc_syntax" ar updateIState (\i -> i { syntax_rules = updateSyntaxRules s (syntax_rules i) }) processKeywords :: Archive -> Idris () processKeywords ar = do k <- getEntry [] "ibc_keywords" ar updateIState (\i -> i { syntax_keywords = k ++ syntax_keywords i }) processObjectFiles :: FilePath -> Archive -> Idris () processObjectFiles fn ar = do os <- getEntry [] "ibc_objs" ar mapM_ (\ (cg, obj) -> do dirs <- rankedImportDirs fn o <- runIO $ findInPath dirs obj addObjectFile cg o) os processLibs :: Archive -> Idris () processLibs ar = do ls <- getEntry [] "ibc_libs" ar mapM_ (uncurry addLib) ls processCodegenFlags :: Archive -> Idris () processCodegenFlags ar = do ls <- getEntry [] "ibc_cgflags" ar mapM_ (uncurry addFlag) ls processDynamicLibs :: Archive -> Idris () processDynamicLibs ar = do ls <- getEntry [] "ibc_dynamic_libs" ar res <- mapM (addDyLib . return) ls mapM_ checkLoad res where checkLoad (Left _) = return () checkLoad (Right err) = ifail err processHeaders :: Archive -> Idris () processHeaders ar = do hs <- getEntry [] "ibc_hdrs" ar mapM_ (uncurry addHdr) hs processPatternDefs :: Archive -> Idris () processPatternDefs ar = do ds <- getEntry [] "ibc_patdefs" ar mapM_ (\ (n, d) -> updateIState (\i -> i { idris_patdefs = addDef n (force d) (idris_patdefs i) })) ds processDefs :: Archive -> Idris () processDefs ar = do ds <- getEntry [] "ibc_defs" ar logIBC 4 $ "processDefs ds" ++ show ds mapM_ (\ (n, d) -> do d' <- updateDef d case d' of TyDecl _ _ -> return () _ -> do logIBC 2 $ "SOLVING " ++ show n solveDeferred emptyFC n updateIState (\i -> i { tt_ctxt = addCtxtDef n d' (tt_ctxt i) })) ds where updateDef (CaseOp c t args o s cd) = do o' <- mapM updateOrig o cd' <- updateCD cd return $ CaseOp c t args o' s cd' updateDef t = return t updateOrig (Left t) = liftM Left (update t) updateOrig (Right (l, r)) = do l' <- update l r' <- update r return $ Right (l', r') updateCD (CaseDefs (cs, c) (rs, r)) = do c' <- updateSC c r' <- updateSC r return $ CaseDefs (cs, c') (rs, r') updateSC (Case t n alts) = do alts' <- mapM updateAlt alts return (Case t n alts') updateSC (ProjCase t alts) = do alts' <- mapM updateAlt alts return (ProjCase t alts') updateSC (STerm t) = do t' <- update t return (STerm t') updateSC c = return c updateAlt (ConCase n i ns t) = do t' <- updateSC t return (ConCase n i ns t') updateAlt (FnCase n ns t) = do t' <- updateSC t return (FnCase n ns t') updateAlt (ConstCase c t) = do t' <- updateSC t return (ConstCase c t') updateAlt (SucCase n t) = do t' <- updateSC t return (SucCase n t') updateAlt (DefaultCase t) = do t' <- updateSC t return (DefaultCase t') -- We get a lot of repetition in sub terms and can save a fair chunk -- of memory if we make sure they're shared. addTT looks for a term -- and returns it if it exists already, while also keeping stats of -- how many times a subterm is repeated. update t = do tm <- addTT t case tm of Nothing -> update' t Just t' -> return t' update' (P t n ty) = do n' <- getSymbol n return $ P t n' ty update' (App s f a) = liftM2 (App s) (update' f) (update' a) update' (Bind n b sc) = do b' <- updateB b sc' <- update sc return $ Bind n b' sc' where updateB (Let rig t v) = liftM2 (Let rig) (update' t) (update' v) updateB b = do ty' <- update' (binderTy b) return (b { binderTy = ty' }) update' (Proj t i) = do t' <- update' t return $ Proj t' i update' t = return t processDocs :: Archive -> Idris () processDocs ar = do ds <- getEntry [] "ibc_docstrings" ar mapM_ (\(n, a) -> addDocStr n (fst a) (snd a)) ds processModuleDocs :: Archive -> Idris () processModuleDocs ar = do ds <- getEntry [] "ibc_moduledocs" ar mapM_ (\ (n, d) -> updateIState (\i -> i { idris_moduledocs = addDef n d (idris_moduledocs i) })) ds processAccess :: Bool -- ^ Reexporting? -> IBCPhase -> Archive -> Idris () processAccess reexp phase ar = do logIBC 3 $ "processAccess (reexp, phase)" ++ show (reexp, phase) ds <- getEntry [] "ibc_access" ar logIBC 3 $ "processAccess ds" ++ show ds mapM_ (\ (n, a_in) -> do let a = if reexp then a_in else Hidden logIBC 3 $ "Setting " ++ show (a, n) ++ " to " ++ show a updateIState (\i -> i { tt_ctxt = setAccess n a (tt_ctxt i) }) if (not reexp) then do logIBC 2 $ "Not exporting " ++ show n setAccessibility n Hidden else logIBC 2 $ "Exporting " ++ show n -- Everything should be available at the REPL from -- things imported publicly. when (phase == IBC_REPL True) $ do logIBC 2 $ "Top level, exporting " ++ show n setAccessibility n Public ) ds processFlags :: Archive -> Idris () processFlags ar = do ds <- getEntry [] "ibc_flags" ar mapM_ (\ (n, a) -> setFlags n a) ds processFnInfo :: Archive -> Idris () processFnInfo ar = do ds <- getEntry [] "ibc_fninfo" ar mapM_ (\ (n, a) -> setFnInfo n a) ds processTotal :: Archive -> Idris () processTotal ar = do ds <- getEntry [] "ibc_total" ar mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setTotal n a (tt_ctxt i) })) ds processInjective :: Archive -> Idris () processInjective ar = do ds <- getEntry [] "ibc_injective" ar mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setInjective n a (tt_ctxt i) })) ds processTotalityCheckError :: Archive -> Idris () processTotalityCheckError ar = do es <- getEntry [] "ibc_totcheckfail" ar updateIState (\i -> i { idris_totcheckfail = idris_totcheckfail i ++ es }) processCallgraph :: Archive -> Idris () processCallgraph ar = do ds <- getEntry [] "ibc_cg" ar mapM_ (\ (n, a) -> addToCG n a) ds processCoercions :: Archive -> Idris () processCoercions ar = do ns <- getEntry [] "ibc_coercions" ar mapM_ (\ n -> addCoercion n) ns processTransforms :: Archive -> Idris () processTransforms ar = do ts <- getEntry [] "ibc_transforms" ar mapM_ (\ (n, t) -> addTrans n t) ts processErrRev :: Archive -> Idris () processErrRev ar = do ts <- getEntry [] "ibc_errRev" ar mapM_ addErrRev ts processErrReduce :: Archive -> Idris () processErrReduce ar = do ts <- getEntry [] "ibc_errReduce" ar mapM_ addErrReduce ts processLineApps :: Archive -> Idris () processLineApps ar = do ls <- getEntry [] "ibc_lineapps" ar mapM_ (\ (f, i, t) -> addInternalApp f i t) ls processNameHints :: Archive -> Idris () processNameHints ar = do ns <- getEntry [] "ibc_namehints" ar mapM_ (\ (n, ty) -> addNameHint n ty) ns processMetaInformation :: Archive -> Idris () processMetaInformation ar = do ds <- getEntry [] "ibc_metainformation" ar mapM_ (\ (n, m) -> updateIState (\i -> i { tt_ctxt = setMetaInformation n m (tt_ctxt i) })) ds processErrorHandlers :: Archive -> Idris () processErrorHandlers ar = do ns <- getEntry [] "ibc_errorhandlers" ar updateIState (\i -> i { idris_errorhandlers = idris_errorhandlers i ++ ns }) processFunctionErrorHandlers :: Archive -> Idris () processFunctionErrorHandlers ar = do ns <- getEntry [] "ibc_function_errorhandlers" ar mapM_ (\ (fn,arg,handler) -> addFunctionErrorHandlers fn arg [handler]) ns processMetaVars :: Archive -> Idris () processMetaVars ar = do ns <- getEntry [] "ibc_metavars" ar updateIState (\i -> i { idris_metavars = L.reverse ns ++ idris_metavars i }) -- We only want the language extensions when reading the top level thing processLangExts :: IBCPhase -> Archive -> Idris () processLangExts (IBC_REPL True) ar = do ds <- getEntry [] "ibc_langexts" ar mapM_ addLangExt ds processLangExts _ _ = return () ----- For Cheapskate and docstrings instance Binary a => Binary (D.Docstring a) instance Binary CT.Options instance Binary D.DocTerm instance Binary a => Binary (D.Block a) instance Binary a => Binary (D.Inline a) instance Binary CT.ListType instance Binary CT.CodeAttr instance Binary CT.NumWrapper ----- Generated by 'derive' instance Binary SizeChange instance Binary CGInfo where put (CGInfo x1 x2 x3 x4) = do put x1 -- put x3 -- Already used SCG info for totality check put x2 put x4 get = do x1 <- get x2 <- get x3 <- get return (CGInfo x1 x2 [] x3) instance Binary CaseType instance Binary SC instance Binary CaseAlt instance Binary CaseDefs instance Binary CaseInfo instance Binary Def where put x = {-# SCC "putDef" #-} case x of Function x1 x2 -> do putWord8 0 put x1 put x2 TyDecl x1 x2 -> do putWord8 1 put x1 put x2 -- all primitives just get added at the start, don't write Operator x1 x2 x3 -> do return () -- no need to add/load original patterns, because they're not -- used again after totality checking CaseOp x1 x2 x3 _ _ x4 -> do putWord8 3 put x1 put x2 put x3 put x4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get return (Function x1 x2) 1 -> do x1 <- get x2 <- get return (TyDecl x1 x2) -- Operator isn't written, don't read 3 -> do x1 <- get x2 <- get x3 <- get -- x4 <- get -- x3 <- get always [] x5 <- get return (CaseOp x1 x2 x3 [] [] x5) _ -> error "Corrupted binary data for Def" instance Binary Accessibility instance Binary PReason instance Binary Totality instance Binary MetaInformation instance Binary DataOpt instance Binary FnOpt instance Binary Fixity instance Binary FixDecl instance Binary ArgOpt instance Binary Static instance Binary Plicity where put x = case x of Imp x1 x2 x3 x4 _ x5 -> do putWord8 0 put x1 put x2 put x3 put x4 put x5 Exp x1 x2 x3 x4 -> do putWord8 1 put x1 put x2 put x3 put x4 Constraint x1 x2 x3 -> do putWord8 2 put x1 put x2 put x3 TacImp x1 x2 x3 x4 -> do putWord8 3 put x1 put x2 put x3 put x4 get = do i <- getWord8 case i of 0 -> do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get return (Imp x1 x2 x3 x4 False x5) 1 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (Exp x1 x2 x3 x4) 2 -> do x1 <- get x2 <- get x3 <- get return (Constraint x1 x2 x3) 3 -> do x1 <- get x2 <- get x3 <- get x4 <- get return (TacImp x1 x2 x3 x4) _ -> error "Corrupted binary data for Plicity" instance Binary DefaultTotality instance Binary LanguageExt instance Binary Directive instance (Binary t) => Binary (PDecl' t) instance Binary t => Binary (ProvideWhat' t) instance Binary Using instance Binary SyntaxInfo where put (Syn x1 x2 x3 x4 _ _ x5 x6 x7 _ _ x8 _ _ _) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (Syn x1 x2 x3 x4 [] id x5 x6 x7 Nothing 0 x8 0 True True) instance (Binary t) => Binary (PClause' t) instance (Binary t) => Binary (PData' t) instance Binary PunInfo instance Binary PTerm instance Binary PAltType instance (Binary t) => Binary (PTactic' t) instance (Binary t) => Binary (PDo' t) instance (Binary t) => Binary (PArg' t) instance Binary InterfaceInfo where put (CI x1 x2 x3 x4 x5 x6 x7 _ x8) = do put x1 put x2 put x3 put x4 put x5 put x6 put x7 put x8 get = do x1 <- get x2 <- get x3 <- get x4 <- get x5 <- get x6 <- get x7 <- get x8 <- get return (CI x1 x2 x3 x4 x5 x6 x7 [] x8) instance Binary RecordInfo instance Binary OptInfo instance Binary FnInfo instance Binary TypeInfo instance Binary SynContext instance Binary Syntax instance (Binary t) => Binary (DSL' t) instance Binary SSymbol instance Binary Codegen instance Binary IRFormat
uuhan/Idris-dev
src/Idris/IBC.hs
bsd-3-clause
42,794
0
21
16,245
13,518
6,647
6,871
1,005
17
{-# LANGUAGE OverloadedStrings #-} import Data.Text (Text) import qualified Data.Text as T (pack) import Shelly ( Sh, StdHandle(InHandle, OutHandle, ErrorHandle) , StdStream(CreatePipe, Inherit, UseHandle), liftIO, echo_err, errExit, exit , lastExitCode, runHandles, shelly, silently ) import System.Environment (getArgs) import System.IO ( Handle, IOMode(WriteMode), hClose, hGetContents, hPutStr, openFile ) import BinSrc.GitUtils (exit_if_not_in_git_repo) default (Text) main :: IO () main = shelly $ silently $ do exit_if_not_in_git_repo cmdArgs <- liftIO getArgs case cmdArgs of [] -> do echo_err "Given a list of git commits, output their commit time" echo_err "Usage: <commit1> [commit2 commit3 ...]" exit 1 _ -> do commitTimeList <- get_commit_time_list cmdArgs liftIO ( mapM_ (\(commitSha1, mbCommitTime) -> case mbCommitTime of Just commitTime -> putStr $ "commit " ++ commitSha1 ++ " was made on " ++ commitTime _ -> putStrLn $ commitSha1 ++ " is not a commit" ) $ zip cmdArgs commitTimeList ) return () get_commit_time_list :: [String] -> Sh [Maybe String] get_commit_time_list commitSha1List = do junkOutputHandle <- liftIO $ openFile "/dev/null" WriteMode ret <- mapM (get_commit_time junkOutputHandle) commitSha1List liftIO $ hClose junkOutputHandle return ret where get_commit_time :: Handle -> String -> Sh (Maybe String) get_commit_time junkOutputHandle commitSha1 = shelly $ errExit False $ silently $ do devNullHandle <- liftIO $ openFile "/dev/null" WriteMode let devNullStdStream = UseHandle devNullHandle outText <- runHandles "git" [ "show", "-s", "--format=%ci" , T.pack commitSha1 ] [ InHandle Inherit, OutHandle CreatePipe , ErrorHandle devNullStdStream ] (\_ outHand _ -> do t <- liftIO $ hGetContents outHand -- force evaluation of hGetContents above liftIO $ hPutStr junkOutputHandle t return t ) exitCode <- lastExitCode liftIO $ hClose devNullHandle if exitCode == 0 then return $ Just outText else do return Nothing
yanhan/bin-src
hs-src/git-commit-time.hs
bsd-3-clause
2,399
0
25
725
602
308
294
58
3
module Main where import Hack.Handler.Hyena import Hack.Contrib.Middleware.ContentLength import Hack.Frontend.Happstack import Network.Gitit main = do conf <- getDefaultConfig createStaticIfMissing conf createTemplateIfMissing conf createRepoIfMissing conf initializeGititState conf run . content_length $ serverPartToApp (wiki conf)
nfjinjing/hack-handler-hyena
src/gitit.hs
bsd-3-clause
347
0
10
45
84
42
42
12
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.Duration.PT.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Duration.PT.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "PT Tests" [ makeCorpusTest [This Duration] corpus ]
rfranek/duckling
tests/Duckling/Duration/PT/Tests.hs
bsd-3-clause
603
0
9
96
80
51
29
11
1
{-# LANGUAGE ViewPatterns #-} module FizzBuzz where import Control.Monad import Control.Monad.Trans.State data FizzBuzz = FizzBuzz | Fizz | Buzz fb :: Integer -> Maybe FizzBuzz fb n | n `mod` 15 == 0 = Just FizzBuzz | n `mod` 5 == 0 = Just Fizz | n `mod` 3 == 0 = Just Buzz | otherwise = Nothing fizzBuzz :: Integer -> String fizzBuzz (fb -> Just FizzBuzz) = "FizzBuzz" fizzBuzz (fb -> Just Fizz) = "Fizz" fizzBuzz (fb -> Just Buzz) = "Buzz" fizzBuzz n = show n fizzBuzzList :: [Integer] -> [String] fizzBuzzList list = execState (mapM_ addResult list) [] fizzBuzzFromTo :: Integer -> Integer -> [String] fizzBuzzFromTo from to = fizzBuzzList [to, to - 1..from] addResult :: Integer -> State [String] () addResult n = do xs <- get let result = fizzBuzz n put (result : xs) main :: IO () main = mapM_ putStrLn $ fizzBuzzFromTo 1 100
vasily-kirichenko/haskell-book
src/FizzBuzz.hs
bsd-3-clause
882
0
10
203
361
185
176
26
1
-- | This module exposes a function which can relativize URL's on a webpage. -- -- This means that one can deploy the resulting site on -- @http:\/\/example.com\/@, but also on @http:\/\/example.com\/some-folder\/@ -- without having to change anything (simply copy over the files). -- -- To use it, you should use absolute URL's from the site root everywhere. For -- example, use -- -- > <img src="/images/lolcat.png" alt="Funny zomgroflcopter" /> -- -- in a blogpost. When running this through the relativize URL's module, this -- will result in (suppose your blogpost is located at @\/posts\/foo.html@: -- -- > <img src="../images/lolcat.png" alt="Funny zomgroflcopter" /> -- module Hakyll.Web.Urls.Relativize ( relativizeUrlsCompiler , relativizeUrls ) where import Prelude hiding (id) import Control.Category (id) import Control.Arrow ((&&&), (>>^)) import Data.List (isPrefixOf) import Hakyll.Core.Compiler import Hakyll.Web.Page import Hakyll.Web.Urls -- | Compiler form of 'relativizeUrls' which automatically picks the right root -- path -- relativizeUrlsCompiler :: Compiler (Page String) (Page String) relativizeUrlsCompiler = getRoute &&& id >>^ uncurry relativize where relativize Nothing = id relativize (Just r) = fmap (relativizeUrls $ toSiteRoot r) -- | Relativize URL's in HTML -- relativizeUrls :: String -- ^ Path to the site root -> String -- ^ HTML to relativize -> String -- ^ Resulting HTML relativizeUrls root = withUrls rel where isRel x = "/" `isPrefixOf` x && not ("//" `isPrefixOf` x) rel x = if isRel x then root ++ x else x
sol/hakyll
src/Hakyll/Web/Urls/Relativize.hs
bsd-3-clause
1,624
0
10
305
258
156
102
20
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Rogue.Types where import Control.Lens hiding (Level) import Control.Lens.TH (declareLenses,declarePrisms) import Data.Array (Array,bounds) import qualified Data.Map.Strict as Map import System.Random (StdGen,split) type Position = (Int,Int) data Level = Level (Array Position Cell) deriving (Show) data Seed = Seed Int Int StdGen deriving (Show) type Depth = Int type Levels = Array Depth (Either Seed Level) data Cell = Floor | Wall | Door | Void deriving (Eq,Show,Ord) type Health = Int class HasHealth a where health :: Lens' a Health declareLenses [d| data Weapon = Weapon deriving (Show) data Scroll = Scroll deriving (Show) |] declarePrisms [d| data ItemInfo = IWeapon Weapon | IScroll Scroll deriving (Show) |] declareLenses [d| data Item = Item { iName :: String , iInfo :: ItemInfo } deriving (Show) |] type Inventory = [Item] class HasInventory a where inventory :: Lens' a Inventory posX, posY :: HasPosition a => Lens' a Int posX = position . _1 posY = position . _2 class HasPosition a where position :: Lens' a Position instance HasPosition Position where position = lens id (\_ p -> p) data Direction = North | NorthEast | East | SouthEast | South | SouthWest | West | NorthWest deriving (Eq,Ord,Show) move :: HasPosition a => Direction -> a -> a move North = over posY (subtract 1) move NorthEast = over posY (subtract 1) . over posX (+ 1) move East = over posX (+ 1) move SouthEast = over posY (+ 1) . over posX (+ 1) move South = over posY (+ 1) move SouthWest = over posY (+ 1) . over posX (subtract 1) move West = over posX (subtract 1) move NorthWest = over posY (subtract 1) . over posX (subtract 1) declareLenses [d| data Character = Character { cHealth :: !Health , cPos :: !Position , cItems :: !Inventory } deriving (Show) instance HasHealth Character where health = cHealth instance HasPosition Character where position = cPos instance HasInventory Character where inventory = cItems data MonsterType = MonsterType { mtName :: String } deriving (Show) data Monster = Monster { mType :: MonsterType , mHealth :: !Health , mPos :: !Position , mItems :: !Inventory } deriving (Show) instance HasHealth Monster where health = mHealth instance HasPosition Monster where position = mPos instance HasInventory Monster where inventory = mItems type MonsterId = Int data State = State { sMonsters :: Map.Map MonsterId Monster , sCharacter :: !Character , sAbove :: [Level] , sLevel :: Level , sBelow :: [Level] , sGen :: !StdGen } deriving (Show) |] splitGen :: State -> (State,StdGen) splitGen s = (set sGen l s, r) where (l,r) = split (view sGen s)
elliottt/rogue
src/Rogue/Types.hs
bsd-3-clause
3,519
0
9
1,260
683
376
307
105
1
{-# LANGUAGE NoImplicitPrelude #-} module Mafia.Twine.Queue ( Queue , newQueue , readQueue , tryReadQueue , writeQueue , isQueueEmpty ) where import Control.Concurrent.STM.TBQueue (TBQueue, newTBQueue, tryReadTBQueue , readTBQueue, writeTBQueue, isEmptyTBQueue) import GHC.Conc (atomically) import Mafia.P import System.IO newtype Queue a = Queue { queue :: TBQueue a } newQueue :: Int -> IO (Queue a) newQueue i = atomically $ Queue <$> newTBQueue i readQueue :: Queue a -> IO a readQueue = atomically . readTBQueue . queue tryReadQueue :: Queue a -> IO (Maybe a) tryReadQueue = atomically . tryReadTBQueue . queue writeQueue :: Queue a -> a -> IO () writeQueue q = atomically . writeTBQueue (queue q) isQueueEmpty :: Queue a -> IO Bool isQueueEmpty = atomically . isEmptyTBQueue . queue
ambiata/mafia
src/Mafia/Twine/Queue.hs
bsd-3-clause
925
0
8
259
261
143
118
31
1
-- | Example: -- -- @ -- {-\# LANGUAGE QuasiQuotes \#-} -- module Main where -- -- import Control.Monad (when) -- import Data.Char (toUpper) -- import System.Environment (getArgs) -- import System.Console.Docopt -- -- patterns :: Docopt -- patterns = [docopt| -- docopt-sample version 0.1.0 -- -- Usage: -- docopt-sample cat \<file\> -- docopt-sample echo [--caps] \<string\> -- -- Options: -- -c, --caps Caps-lock the echoed argument -- |] -- -- getArgOrExit = getArgOrExitWith patterns -- -- main :: IO () -- main = do -- args <- parseArgsOrExit patterns =<< getArgs -- -- when (args \`isPresent\` (command \"cat\")) $ do -- file <- args \`getArgOrExit\` (argument \"file\") -- putStr =<< readFile file -- -- when (args \`isPresent\` (command \"echo\")) $ do -- let charTransform = if args \`isPresent\` (longOption \"caps\") -- then toUpper -- else id -- string <- args \`getArgOrExit\` (argument \"string\") -- putStrLn $ map charTransform string -- @ module System.Console.Docopt ( module System.Console.Docopt.QQ, module System.Console.Docopt.Public ) where import System.Console.Docopt.QQ import System.Console.Docopt.Public
docopt/docopt.hs
System/Console/Docopt.hs
mit
1,230
0
5
262
79
68
11
6
0
{- Bloop, Copyright (C) 2005, Jaap Weel -- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} module ParseBloop ( parseBloop ) where import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Expr import qualified Text.ParserCombinators.Parsec.Token as P import Text.ParserCombinators.Parsec.Language import Text.Regex import AstBloop -- Drive the parser -------------------------------------------------- parseBloop filename program_text = parse program filename program_text -- Syntax ------------------------------------------------------------ program = do whiteSpace ps <- sepBy (procedure <|> top_expr) semi symbol "." return (Program ps) <?> "FLooP program" procedure = do reserved "DEFINE" reserved "PROCEDURE" symbol "\"" name <- atom symbol "\"" args <- brackets (commaSep atom) <?> "argument list" symbol ":" body <- block return (Procedure (s name) (Var name) (map Var args) body) <?> "procedure" where s (Symbol n) = case matchRegex (mkRegex ".*\\?$") n of Just _ -> Boolean False Nothing -> Number 0 top_expr = do e <- expr return (TopExp e) <?> "expression" -- Blocks ----------------------------------------------------------- block = do reserved "BLOCK" b1 <- fixnum symbol ":" reserved "BEGIN" statements <- endBy statement semi reserved "BLOCK" b2 <- fixnum symbol ":" reserved "END" if (b1 /= b2) then fail $ "Block mismatch "++show b1++" "++show b2 else return (Block b1 statements) <?> "block" -- Statements ------------------------------------------------------- statement = try block <|> quit <|> abort <|> loop <|> muloop <|> ifthen <|> assignment quit = do reserved "QUIT" reserved "BLOCK" n <- fixnum return (Quit n) <?> "quit statement" abort = do reserved "ABORT" reserved "LOOP" n <- fixnum return (Abort n) <?> "abort statement" muloop = do reserved "MU-LOOP" symbol ":" b@(Block n _) <- block return (Muloop n b) <?> "mu loop statement" -- Note that "AT MOST" is not required on p.410 of GEB... loop = do reserved "LOOP" option () (do reserved "AT"; reserved "MOST") e <- expr whiteSpace reserved "TIMES" symbol ":" b@(Block n _) <- block return (Loop e n b) <?> "bounded loop statement" ifthen = do reserved "IF" e <- expr symbol "," reserved "THEN" symbol ":" s <- statement return (Ifthen e s) <?> "if-then statement" assignment = do left <- lvalue symbol "<=" right <- expr return (Assign left right) <?> "assignment" -- Expressions ------------------------------------------------------ expr = infix_expr <|> simple_expr simple_expr = braces expr <|> cell <|> output <|> number <|> boolean <|> try funcall <|> var infix_expr = buildExpressionParser operators simple_expr operators = [[ op "*" AssocLeft ], [ op "+" AssocLeft ], [ op "=" AssocNone, op "<" AssocNone, op ">" AssocNone ], [ op "AND" AssocRight ], [ op "OR" AssocRight ]] where op name = Infix (reservedOp name >> return (\x y -> Binop name x y)) funcall = do a <- atom argl <- brackets (commaSep expr) return (Funcall a argl) <?> "function call" output = do reserved "OUTPUT" return (Output) <?> "output identifier" boolean = (do reserved "YES"; return (Boolean True)) <|> (do reserved "NO"; return (Boolean False)) <?> "boolean constant" number = do n <- fixnum return (Number n) <?> "decimal number" var = do a <- atom return (Var a) <?> "variable name" cell = do reserved "CELL" n <- parens fixnum return (Cell $ CellNumber n) <?> "cell identifier" lvalue = output <|> cell <|> var <?> "valid lvalue" -- Lexical structure ------------------------------------------------ ident_chars = oneOf "?-" <|> upper lexer = P.makeTokenParser $ emptyDef { P.commentStart = "/*", P.commentEnd = "*/", P.commentLine = "==", P.identStart = ident_chars, P.identLetter = ident_chars, P.reservedNames = ["DEFINE", "PROCEDURE", "CELL", "OUTPUT", "BLOCK", "BEGIN", "END", "QUIT", "IF", "THEN", "MU-LOOP", "YES", "NO", "LOOP", "AT", "MOST", "TIMES", "ABORT", "LOOP"], P.reservedOpNames= ["<=","=","<",">","\"",":",";",",",".","*","+", "AND","OR"] } whiteSpace = P.whiteSpace lexer identifier = P.identifier lexer symbol = P.symbol lexer reservedOp = P.reservedOp lexer decimal = P.decimal lexer reserved = P.reserved lexer semi = P.semi lexer commaSep = P.commaSep lexer semiSep = P.semiSep lexer braces = P.braces lexer parens = P.parens lexer brackets = P.brackets lexer -- Some tokens wrapped in a little sugar ----------------------------- fixnum = do n <- decimal whiteSpace return n <?> "decimal number" atom = do i <- identifier return (Symbol i) <?> "symbol"
jaapweel/bloop
ParseBloop.hs
gpl-2.0
6,628
0
13
2,306
1,565
767
798
129
2
module Sound.Tidal.Params where -- Please note, this file is generated by bin/generate-params.hs -- Submit any pull requests against that file and/or params-header.hs -- in the same folder, thanks. {- Params.hs - Provides the basic control patterns available to TidalCycles by default Copyright (C) 2021, Alex McLean and contributors This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. -} import qualified Data.Map.Strict as Map import Sound.Tidal.Pattern import Sound.Tidal.Core ((#)) import Sound.Tidal.Utils import Data.Maybe (fromMaybe) import Data.Word (Word8) import Data.Fixed (mod') -- | group multiple params into one grp :: [String -> ValueMap] -> Pattern String -> ControlPattern grp [] _ = empty grp fs p = splitby <$> p where splitby name = Map.unions $ map (\(v, f) -> f v) $ zip (split name) fs split :: String -> [String] split = wordsBy (==':') mF :: String -> String -> ValueMap mF name v = fromMaybe Map.empty $ do f <- readMaybe v return $ Map.singleton name (VF f) mI :: String -> String -> ValueMap mI name v = fromMaybe Map.empty $ do i <- readMaybe v return $ Map.singleton name (VI i) mS :: String -> String -> ValueMap mS name v = Map.singleton name (VS v) -- | Param makers pF :: String -> Pattern Double -> ControlPattern pF name = fmap (Map.singleton name . VF) pI :: String -> Pattern Int -> ControlPattern pI name = fmap (Map.singleton name . VI) pB :: String -> Pattern Bool -> ControlPattern pB name = fmap (Map.singleton name . VB) pR :: String -> Pattern Rational -> ControlPattern pR name = fmap (Map.singleton name . VR) pN :: String -> Pattern Note -> ControlPattern pN name = fmap (Map.singleton name . VN) pS :: String -> Pattern String -> ControlPattern pS name = fmap (Map.singleton name . VS) pX :: String -> Pattern [Word8] -> ControlPattern pX name = fmap (Map.singleton name . VX) pStateF :: String -> String -> (Maybe Double -> Double) -> ControlPattern pStateF name sName update = pure $ Map.singleton name $ VState statef where statef :: ValueMap -> (ValueMap, Value) statef sMap = (Map.insert sName v sMap, v) where v = VF $ update $ (Map.lookup sName sMap) >>= getF pStateList :: String -> String -> [Value] -> ControlPattern pStateList name sName xs = pure $ Map.singleton name $ VState statef where statef :: ValueMap -> (ValueMap, Value) statef sMap = (Map.insert sName (VList $ tail looped) sMap, head looped) where xs' = fromMaybe xs ((Map.lookup sName sMap) >>= getList) -- do this instead of a cycle, so it can get updated with the a list looped | null xs' = xs | otherwise = xs' pStateListF :: String -> String -> [Double] -> ControlPattern pStateListF name sName = pStateList name sName . map VF pStateListS :: String -> String -> [String] -> ControlPattern pStateListS name sName = pStateList name sName . map VS -- | Grouped params sound :: Pattern String -> ControlPattern sound = grp [mS "s", mF "n"] sTake :: String -> [String] -> ControlPattern sTake name xs = pStateListS "s" name xs cc :: Pattern String -> ControlPattern cc = grp [mF "ccn", mF "ccv"] nrpn :: Pattern String -> ControlPattern nrpn = grp [mI "nrpn", mI "val"] nrpnn :: Pattern Int -> ControlPattern nrpnn = pI "nrpn" nrpnv :: Pattern Int -> ControlPattern nrpnv = pI "val" grain' :: Pattern String -> ControlPattern grain' = grp [mF "begin", mF "end"] midinote :: Pattern Note -> ControlPattern midinote = note . (subtract 60 <$>) drum :: Pattern String -> ControlPattern drum = n . (subtract 60 . drumN <$>) drumN :: Num a => String -> a drumN "hq" = 27 drumN "sl" = 28 drumN "ps" = 29 drumN "pl" = 30 drumN "st" = 31 drumN "sq" = 32 drumN "ml" = 33 drumN "mb" = 34 drumN "ab" = 35 drumN "bd" = 36 drumN "rm" = 37 drumN "sn" = 38 drumN "cp" = 39 drumN "es" = 40 drumN "lf" = 41 drumN "ch" = 42 drumN "lt" = 43 drumN "hh" = 44 drumN "ft" = 45 drumN "oh" = 46 drumN "mt" = 47 drumN "hm" = 48 drumN "cr" = 49 drumN "ht" = 50 drumN "ri" = 51 drumN "cy" = 52 drumN "be" = 53 drumN "ta" = 54 drumN "sc" = 55 drumN "cb" = 56 drumN "cs" = 57 drumN "vi" = 58 drumN "rc" = 59 drumN "hb" = 60 drumN "lb" = 61 drumN "mh" = 62 drumN "hc" = 63 drumN "lc" = 64 drumN "he" = 65 drumN "le" = 66 drumN "ag" = 67 drumN "la" = 68 drumN "ca" = 69 drumN "ma" = 70 drumN "sw" = 71 drumN "lw" = 72 drumN "sg" = 73 drumN "lg" = 74 drumN "cl" = 75 drumN "hi" = 76 drumN "li" = 77 drumN "mc" = 78 drumN "oc" = 79 drumN "tr" = 80 drumN "ot" = 81 drumN "sh" = 82 drumN "jb" = 83 drumN "bt" = 84 drumN "ct" = 85 drumN "ms" = 86 drumN "os" = 87 drumN _ = 0 -- Generated params -- | a pattern of numbers that speed up (or slow down) samples while they play. accelerate :: Pattern Double -> ControlPattern accelerate = pF "accelerate" accelerateTake :: String -> [Double] -> ControlPattern accelerateTake name xs = pStateListF "accelerate" name xs accelerateCount :: String -> ControlPattern accelerateCount name = pStateF "accelerate" name (maybe 0 (+1)) accelerateCountTo :: String -> Pattern Double -> Pattern ValueMap accelerateCountTo name ipat = innerJoin $ (\i -> pStateF "accelerate" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat acceleratebus :: Pattern Int -> Pattern Double -> ControlPattern acceleratebus busid pat = (pF "accelerate" pat) # (pI "^accelerate" busid) acceleraterecv :: Pattern Int -> ControlPattern acceleraterecv busid = pI "^accelerate" busid -- | like @gain@, but linear. amp :: Pattern Double -> ControlPattern amp = pF "amp" ampTake :: String -> [Double] -> ControlPattern ampTake name xs = pStateListF "amp" name xs ampCount :: String -> ControlPattern ampCount name = pStateF "amp" name (maybe 0 (+1)) ampCountTo :: String -> Pattern Double -> Pattern ValueMap ampCountTo name ipat = innerJoin $ (\i -> pStateF "amp" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat ampbus :: Pattern Int -> Pattern Double -> ControlPattern ampbus busid pat = (pF "amp" pat) # (pI "^amp" busid) amprecv :: Pattern Int -> ControlPattern amprecv busid = pI "^amp" busid -- | array :: Pattern [Word8] -> ControlPattern array = pX "array" arrayTake :: String -> [Double] -> ControlPattern arrayTake name xs = pStateListF "array" name xs arraybus :: Pattern Int -> Pattern [Word8] -> ControlPattern arraybus _ _ = error $ "Control parameter 'array' can't be sent to a bus." -- | a pattern of numbers to specify the attack time (in seconds) of an envelope applied to each sample. attack :: Pattern Double -> ControlPattern attack = pF "attack" attackTake :: String -> [Double] -> ControlPattern attackTake name xs = pStateListF "attack" name xs attackCount :: String -> ControlPattern attackCount name = pStateF "attack" name (maybe 0 (+1)) attackCountTo :: String -> Pattern Double -> Pattern ValueMap attackCountTo name ipat = innerJoin $ (\i -> pStateF "attack" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat attackbus :: Pattern Int -> Pattern Double -> ControlPattern attackbus busid pat = (pF "attack" pat) # (pI "^attack" busid) attackrecv :: Pattern Int -> ControlPattern attackrecv busid = pI "^attack" busid -- | a pattern of numbers from 0 to 1. Sets the center frequency of the band-pass filter. bandf :: Pattern Double -> ControlPattern bandf = pF "bandf" bandfTake :: String -> [Double] -> ControlPattern bandfTake name xs = pStateListF "bandf" name xs bandfCount :: String -> ControlPattern bandfCount name = pStateF "bandf" name (maybe 0 (+1)) bandfCountTo :: String -> Pattern Double -> Pattern ValueMap bandfCountTo name ipat = innerJoin $ (\i -> pStateF "bandf" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat bandfbus :: Pattern Int -> Pattern Double -> ControlPattern bandfbus busid pat = (pF "bandf" pat) # (pI "^bandf" busid) bandfrecv :: Pattern Int -> ControlPattern bandfrecv busid = pI "^bandf" busid -- | a pattern of anumbers from 0 to 1. Sets the q-factor of the band-pass filter. bandq :: Pattern Double -> ControlPattern bandq = pF "bandq" bandqTake :: String -> [Double] -> ControlPattern bandqTake name xs = pStateListF "bandq" name xs bandqCount :: String -> ControlPattern bandqCount name = pStateF "bandq" name (maybe 0 (+1)) bandqCountTo :: String -> Pattern Double -> Pattern ValueMap bandqCountTo name ipat = innerJoin $ (\i -> pStateF "bandq" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat bandqbus :: Pattern Int -> Pattern Double -> ControlPattern bandqbus busid pat = (pF "bandq" pat) # (pI "^bandq" busid) bandqrecv :: Pattern Int -> ControlPattern bandqrecv busid = pI "^bandq" busid -- | a pattern of numbers from 0 to 1. Skips the beginning of each sample, e.g. `0.25` to cut off the first quarter from each sample. begin :: Pattern Double -> ControlPattern begin = pF "begin" beginTake :: String -> [Double] -> ControlPattern beginTake name xs = pStateListF "begin" name xs beginCount :: String -> ControlPattern beginCount name = pStateF "begin" name (maybe 0 (+1)) beginCountTo :: String -> Pattern Double -> Pattern ValueMap beginCountTo name ipat = innerJoin $ (\i -> pStateF "begin" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat beginbus :: Pattern Int -> Pattern Double -> ControlPattern beginbus busid pat = (pF "begin" pat) # (pI "^begin" busid) beginrecv :: Pattern Int -> ControlPattern beginrecv busid = pI "^begin" busid -- | Spectral binshift binshift :: Pattern Double -> ControlPattern binshift = pF "binshift" binshiftTake :: String -> [Double] -> ControlPattern binshiftTake name xs = pStateListF "binshift" name xs binshiftCount :: String -> ControlPattern binshiftCount name = pStateF "binshift" name (maybe 0 (+1)) binshiftCountTo :: String -> Pattern Double -> Pattern ValueMap binshiftCountTo name ipat = innerJoin $ (\i -> pStateF "binshift" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat binshiftbus :: Pattern Int -> Pattern Double -> ControlPattern binshiftbus busid pat = (pF "binshift" pat) # (pI "^binshift" busid) binshiftrecv :: Pattern Int -> ControlPattern binshiftrecv busid = pI "^binshift" busid -- | button0 :: Pattern Double -> ControlPattern button0 = pF "button0" button0Take :: String -> [Double] -> ControlPattern button0Take name xs = pStateListF "button0" name xs button0Count :: String -> ControlPattern button0Count name = pStateF "button0" name (maybe 0 (+1)) button0CountTo :: String -> Pattern Double -> Pattern ValueMap button0CountTo name ipat = innerJoin $ (\i -> pStateF "button0" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button0bus :: Pattern Int -> Pattern Double -> ControlPattern button0bus busid pat = (pF "button0" pat) # (pI "^button0" busid) button0recv :: Pattern Int -> ControlPattern button0recv busid = pI "^button0" busid -- | button1 :: Pattern Double -> ControlPattern button1 = pF "button1" button1Take :: String -> [Double] -> ControlPattern button1Take name xs = pStateListF "button1" name xs button1Count :: String -> ControlPattern button1Count name = pStateF "button1" name (maybe 0 (+1)) button1CountTo :: String -> Pattern Double -> Pattern ValueMap button1CountTo name ipat = innerJoin $ (\i -> pStateF "button1" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button1bus :: Pattern Int -> Pattern Double -> ControlPattern button1bus busid pat = (pF "button1" pat) # (pI "^button1" busid) button1recv :: Pattern Int -> ControlPattern button1recv busid = pI "^button1" busid -- | button10 :: Pattern Double -> ControlPattern button10 = pF "button10" button10Take :: String -> [Double] -> ControlPattern button10Take name xs = pStateListF "button10" name xs button10Count :: String -> ControlPattern button10Count name = pStateF "button10" name (maybe 0 (+1)) button10CountTo :: String -> Pattern Double -> Pattern ValueMap button10CountTo name ipat = innerJoin $ (\i -> pStateF "button10" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button10bus :: Pattern Int -> Pattern Double -> ControlPattern button10bus busid pat = (pF "button10" pat) # (pI "^button10" busid) button10recv :: Pattern Int -> ControlPattern button10recv busid = pI "^button10" busid -- | button11 :: Pattern Double -> ControlPattern button11 = pF "button11" button11Take :: String -> [Double] -> ControlPattern button11Take name xs = pStateListF "button11" name xs button11Count :: String -> ControlPattern button11Count name = pStateF "button11" name (maybe 0 (+1)) button11CountTo :: String -> Pattern Double -> Pattern ValueMap button11CountTo name ipat = innerJoin $ (\i -> pStateF "button11" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button11bus :: Pattern Int -> Pattern Double -> ControlPattern button11bus busid pat = (pF "button11" pat) # (pI "^button11" busid) button11recv :: Pattern Int -> ControlPattern button11recv busid = pI "^button11" busid -- | button12 :: Pattern Double -> ControlPattern button12 = pF "button12" button12Take :: String -> [Double] -> ControlPattern button12Take name xs = pStateListF "button12" name xs button12Count :: String -> ControlPattern button12Count name = pStateF "button12" name (maybe 0 (+1)) button12CountTo :: String -> Pattern Double -> Pattern ValueMap button12CountTo name ipat = innerJoin $ (\i -> pStateF "button12" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button12bus :: Pattern Int -> Pattern Double -> ControlPattern button12bus busid pat = (pF "button12" pat) # (pI "^button12" busid) button12recv :: Pattern Int -> ControlPattern button12recv busid = pI "^button12" busid -- | button13 :: Pattern Double -> ControlPattern button13 = pF "button13" button13Take :: String -> [Double] -> ControlPattern button13Take name xs = pStateListF "button13" name xs button13Count :: String -> ControlPattern button13Count name = pStateF "button13" name (maybe 0 (+1)) button13CountTo :: String -> Pattern Double -> Pattern ValueMap button13CountTo name ipat = innerJoin $ (\i -> pStateF "button13" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button13bus :: Pattern Int -> Pattern Double -> ControlPattern button13bus busid pat = (pF "button13" pat) # (pI "^button13" busid) button13recv :: Pattern Int -> ControlPattern button13recv busid = pI "^button13" busid -- | button14 :: Pattern Double -> ControlPattern button14 = pF "button14" button14Take :: String -> [Double] -> ControlPattern button14Take name xs = pStateListF "button14" name xs button14Count :: String -> ControlPattern button14Count name = pStateF "button14" name (maybe 0 (+1)) button14CountTo :: String -> Pattern Double -> Pattern ValueMap button14CountTo name ipat = innerJoin $ (\i -> pStateF "button14" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button14bus :: Pattern Int -> Pattern Double -> ControlPattern button14bus busid pat = (pF "button14" pat) # (pI "^button14" busid) button14recv :: Pattern Int -> ControlPattern button14recv busid = pI "^button14" busid -- | button15 :: Pattern Double -> ControlPattern button15 = pF "button15" button15Take :: String -> [Double] -> ControlPattern button15Take name xs = pStateListF "button15" name xs button15Count :: String -> ControlPattern button15Count name = pStateF "button15" name (maybe 0 (+1)) button15CountTo :: String -> Pattern Double -> Pattern ValueMap button15CountTo name ipat = innerJoin $ (\i -> pStateF "button15" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button15bus :: Pattern Int -> Pattern Double -> ControlPattern button15bus busid pat = (pF "button15" pat) # (pI "^button15" busid) button15recv :: Pattern Int -> ControlPattern button15recv busid = pI "^button15" busid -- | button2 :: Pattern Double -> ControlPattern button2 = pF "button2" button2Take :: String -> [Double] -> ControlPattern button2Take name xs = pStateListF "button2" name xs button2Count :: String -> ControlPattern button2Count name = pStateF "button2" name (maybe 0 (+1)) button2CountTo :: String -> Pattern Double -> Pattern ValueMap button2CountTo name ipat = innerJoin $ (\i -> pStateF "button2" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button2bus :: Pattern Int -> Pattern Double -> ControlPattern button2bus busid pat = (pF "button2" pat) # (pI "^button2" busid) button2recv :: Pattern Int -> ControlPattern button2recv busid = pI "^button2" busid -- | button3 :: Pattern Double -> ControlPattern button3 = pF "button3" button3Take :: String -> [Double] -> ControlPattern button3Take name xs = pStateListF "button3" name xs button3Count :: String -> ControlPattern button3Count name = pStateF "button3" name (maybe 0 (+1)) button3CountTo :: String -> Pattern Double -> Pattern ValueMap button3CountTo name ipat = innerJoin $ (\i -> pStateF "button3" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button3bus :: Pattern Int -> Pattern Double -> ControlPattern button3bus busid pat = (pF "button3" pat) # (pI "^button3" busid) button3recv :: Pattern Int -> ControlPattern button3recv busid = pI "^button3" busid -- | button4 :: Pattern Double -> ControlPattern button4 = pF "button4" button4Take :: String -> [Double] -> ControlPattern button4Take name xs = pStateListF "button4" name xs button4Count :: String -> ControlPattern button4Count name = pStateF "button4" name (maybe 0 (+1)) button4CountTo :: String -> Pattern Double -> Pattern ValueMap button4CountTo name ipat = innerJoin $ (\i -> pStateF "button4" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button4bus :: Pattern Int -> Pattern Double -> ControlPattern button4bus busid pat = (pF "button4" pat) # (pI "^button4" busid) button4recv :: Pattern Int -> ControlPattern button4recv busid = pI "^button4" busid -- | button5 :: Pattern Double -> ControlPattern button5 = pF "button5" button5Take :: String -> [Double] -> ControlPattern button5Take name xs = pStateListF "button5" name xs button5Count :: String -> ControlPattern button5Count name = pStateF "button5" name (maybe 0 (+1)) button5CountTo :: String -> Pattern Double -> Pattern ValueMap button5CountTo name ipat = innerJoin $ (\i -> pStateF "button5" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button5bus :: Pattern Int -> Pattern Double -> ControlPattern button5bus busid pat = (pF "button5" pat) # (pI "^button5" busid) button5recv :: Pattern Int -> ControlPattern button5recv busid = pI "^button5" busid -- | button6 :: Pattern Double -> ControlPattern button6 = pF "button6" button6Take :: String -> [Double] -> ControlPattern button6Take name xs = pStateListF "button6" name xs button6Count :: String -> ControlPattern button6Count name = pStateF "button6" name (maybe 0 (+1)) button6CountTo :: String -> Pattern Double -> Pattern ValueMap button6CountTo name ipat = innerJoin $ (\i -> pStateF "button6" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button6bus :: Pattern Int -> Pattern Double -> ControlPattern button6bus busid pat = (pF "button6" pat) # (pI "^button6" busid) button6recv :: Pattern Int -> ControlPattern button6recv busid = pI "^button6" busid -- | button7 :: Pattern Double -> ControlPattern button7 = pF "button7" button7Take :: String -> [Double] -> ControlPattern button7Take name xs = pStateListF "button7" name xs button7Count :: String -> ControlPattern button7Count name = pStateF "button7" name (maybe 0 (+1)) button7CountTo :: String -> Pattern Double -> Pattern ValueMap button7CountTo name ipat = innerJoin $ (\i -> pStateF "button7" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button7bus :: Pattern Int -> Pattern Double -> ControlPattern button7bus busid pat = (pF "button7" pat) # (pI "^button7" busid) button7recv :: Pattern Int -> ControlPattern button7recv busid = pI "^button7" busid -- | button8 :: Pattern Double -> ControlPattern button8 = pF "button8" button8Take :: String -> [Double] -> ControlPattern button8Take name xs = pStateListF "button8" name xs button8Count :: String -> ControlPattern button8Count name = pStateF "button8" name (maybe 0 (+1)) button8CountTo :: String -> Pattern Double -> Pattern ValueMap button8CountTo name ipat = innerJoin $ (\i -> pStateF "button8" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button8bus :: Pattern Int -> Pattern Double -> ControlPattern button8bus busid pat = (pF "button8" pat) # (pI "^button8" busid) button8recv :: Pattern Int -> ControlPattern button8recv busid = pI "^button8" busid -- | button9 :: Pattern Double -> ControlPattern button9 = pF "button9" button9Take :: String -> [Double] -> ControlPattern button9Take name xs = pStateListF "button9" name xs button9Count :: String -> ControlPattern button9Count name = pStateF "button9" name (maybe 0 (+1)) button9CountTo :: String -> Pattern Double -> Pattern ValueMap button9CountTo name ipat = innerJoin $ (\i -> pStateF "button9" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat button9bus :: Pattern Int -> Pattern Double -> ControlPattern button9bus busid pat = (pF "button9" pat) # (pI "^button9" busid) button9recv :: Pattern Int -> ControlPattern button9recv busid = pI "^button9" busid -- | ccn :: Pattern Double -> ControlPattern ccn = pF "ccn" ccnTake :: String -> [Double] -> ControlPattern ccnTake name xs = pStateListF "ccn" name xs ccnCount :: String -> ControlPattern ccnCount name = pStateF "ccn" name (maybe 0 (+1)) ccnCountTo :: String -> Pattern Double -> Pattern ValueMap ccnCountTo name ipat = innerJoin $ (\i -> pStateF "ccn" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat ccnbus :: Pattern Int -> Pattern Double -> ControlPattern ccnbus _ _ = error $ "Control parameter 'ccn' can't be sent to a bus." -- | ccv :: Pattern Double -> ControlPattern ccv = pF "ccv" ccvTake :: String -> [Double] -> ControlPattern ccvTake name xs = pStateListF "ccv" name xs ccvCount :: String -> ControlPattern ccvCount name = pStateF "ccv" name (maybe 0 (+1)) ccvCountTo :: String -> Pattern Double -> Pattern ValueMap ccvCountTo name ipat = innerJoin $ (\i -> pStateF "ccv" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat ccvbus :: Pattern Int -> Pattern Double -> ControlPattern ccvbus _ _ = error $ "Control parameter 'ccv' can't be sent to a bus." -- | choose the channel the pattern is sent to in superdirt channel :: Pattern Int -> ControlPattern channel = pI "channel" channelTake :: String -> [Double] -> ControlPattern channelTake name xs = pStateListF "channel" name xs channelCount :: String -> ControlPattern channelCount name = pStateF "channel" name (maybe 0 (+1)) channelCountTo :: String -> Pattern Double -> Pattern ValueMap channelCountTo name ipat = innerJoin $ (\i -> pStateF "channel" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat channelbus :: Pattern Int -> Pattern Int -> ControlPattern channelbus _ _ = error $ "Control parameter 'channel' can't be sent to a bus." -- | clhatdecay :: Pattern Double -> ControlPattern clhatdecay = pF "clhatdecay" clhatdecayTake :: String -> [Double] -> ControlPattern clhatdecayTake name xs = pStateListF "clhatdecay" name xs clhatdecayCount :: String -> ControlPattern clhatdecayCount name = pStateF "clhatdecay" name (maybe 0 (+1)) clhatdecayCountTo :: String -> Pattern Double -> Pattern ValueMap clhatdecayCountTo name ipat = innerJoin $ (\i -> pStateF "clhatdecay" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat clhatdecaybus :: Pattern Int -> Pattern Double -> ControlPattern clhatdecaybus busid pat = (pF "clhatdecay" pat) # (pI "^clhatdecay" busid) clhatdecayrecv :: Pattern Int -> ControlPattern clhatdecayrecv busid = pI "^clhatdecay" busid -- | fake-resampling, a pattern of numbers for lowering the sample rate, i.e. 1 for original 2 for half, 3 for a third and so on. coarse :: Pattern Double -> ControlPattern coarse = pF "coarse" coarseTake :: String -> [Double] -> ControlPattern coarseTake name xs = pStateListF "coarse" name xs coarseCount :: String -> ControlPattern coarseCount name = pStateF "coarse" name (maybe 0 (+1)) coarseCountTo :: String -> Pattern Double -> Pattern ValueMap coarseCountTo name ipat = innerJoin $ (\i -> pStateF "coarse" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat coarsebus :: Pattern Int -> Pattern Double -> ControlPattern coarsebus busid pat = (pF "coarse" pat) # (pI "^coarse" busid) coarserecv :: Pattern Int -> ControlPattern coarserecv busid = pI "^coarse" busid -- | Spectral comb comb :: Pattern Double -> ControlPattern comb = pF "comb" combTake :: String -> [Double] -> ControlPattern combTake name xs = pStateListF "comb" name xs combCount :: String -> ControlPattern combCount name = pStateF "comb" name (maybe 0 (+1)) combCountTo :: String -> Pattern Double -> Pattern ValueMap combCountTo name ipat = innerJoin $ (\i -> pStateF "comb" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat combbus :: Pattern Int -> Pattern Double -> ControlPattern combbus busid pat = (pF "comb" pat) # (pI "^comb" busid) combrecv :: Pattern Int -> ControlPattern combrecv busid = pI "^comb" busid -- | control :: Pattern Double -> ControlPattern control = pF "control" controlTake :: String -> [Double] -> ControlPattern controlTake name xs = pStateListF "control" name xs controlCount :: String -> ControlPattern controlCount name = pStateF "control" name (maybe 0 (+1)) controlCountTo :: String -> Pattern Double -> Pattern ValueMap controlCountTo name ipat = innerJoin $ (\i -> pStateF "control" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat controlbus :: Pattern Int -> Pattern Double -> ControlPattern controlbus _ _ = error $ "Control parameter 'control' can't be sent to a bus." -- | cps :: Pattern Double -> ControlPattern cps = pF "cps" cpsTake :: String -> [Double] -> ControlPattern cpsTake name xs = pStateListF "cps" name xs cpsCount :: String -> ControlPattern cpsCount name = pStateF "cps" name (maybe 0 (+1)) cpsCountTo :: String -> Pattern Double -> Pattern ValueMap cpsCountTo name ipat = innerJoin $ (\i -> pStateF "cps" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat cpsbus :: Pattern Int -> Pattern Double -> ControlPattern cpsbus busid pat = (pF "cps" pat) # (pI "^cps" busid) cpsrecv :: Pattern Int -> ControlPattern cpsrecv busid = pI "^cps" busid -- | bit crushing, a pattern of numbers from 1 (for drastic reduction in bit-depth) to 16 (for barely no reduction). crush :: Pattern Double -> ControlPattern crush = pF "crush" crushTake :: String -> [Double] -> ControlPattern crushTake name xs = pStateListF "crush" name xs crushCount :: String -> ControlPattern crushCount name = pStateF "crush" name (maybe 0 (+1)) crushCountTo :: String -> Pattern Double -> Pattern ValueMap crushCountTo name ipat = innerJoin $ (\i -> pStateF "crush" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat crushbus :: Pattern Int -> Pattern Double -> ControlPattern crushbus busid pat = (pF "crush" pat) # (pI "^crush" busid) crushrecv :: Pattern Int -> ControlPattern crushrecv busid = pI "^crush" busid -- | ctlNum :: Pattern Double -> ControlPattern ctlNum = pF "ctlNum" ctlNumTake :: String -> [Double] -> ControlPattern ctlNumTake name xs = pStateListF "ctlNum" name xs ctlNumCount :: String -> ControlPattern ctlNumCount name = pStateF "ctlNum" name (maybe 0 (+1)) ctlNumCountTo :: String -> Pattern Double -> Pattern ValueMap ctlNumCountTo name ipat = innerJoin $ (\i -> pStateF "ctlNum" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat ctlNumbus :: Pattern Int -> Pattern Double -> ControlPattern ctlNumbus _ _ = error $ "Control parameter 'ctlNum' can't be sent to a bus." -- | ctranspose :: Pattern Double -> ControlPattern ctranspose = pF "ctranspose" ctransposeTake :: String -> [Double] -> ControlPattern ctransposeTake name xs = pStateListF "ctranspose" name xs ctransposeCount :: String -> ControlPattern ctransposeCount name = pStateF "ctranspose" name (maybe 0 (+1)) ctransposeCountTo :: String -> Pattern Double -> Pattern ValueMap ctransposeCountTo name ipat = innerJoin $ (\i -> pStateF "ctranspose" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat ctransposebus :: Pattern Int -> Pattern Double -> ControlPattern ctransposebus busid pat = (pF "ctranspose" pat) # (pI "^ctranspose" busid) ctransposerecv :: Pattern Int -> ControlPattern ctransposerecv busid = pI "^ctranspose" busid -- | In the style of classic drum-machines, `cut` will stop a playing sample as soon as another samples with in same cutgroup is to be played. An example would be an open hi-hat followed by a closed one, essentially muting the open. cut :: Pattern Int -> ControlPattern cut = pI "cut" cutTake :: String -> [Double] -> ControlPattern cutTake name xs = pStateListF "cut" name xs cutCount :: String -> ControlPattern cutCount name = pStateF "cut" name (maybe 0 (+1)) cutCountTo :: String -> Pattern Double -> Pattern ValueMap cutCountTo name ipat = innerJoin $ (\i -> pStateF "cut" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat cutbus :: Pattern Int -> Pattern Int -> ControlPattern cutbus busid pat = (pI "cut" pat) # (pI "^cut" busid) cutrecv :: Pattern Int -> ControlPattern cutrecv busid = pI "^cut" busid -- | a pattern of numbers from 0 to 1. Applies the cutoff frequency of the low-pass filter. cutoff :: Pattern Double -> ControlPattern cutoff = pF "cutoff" cutoffTake :: String -> [Double] -> ControlPattern cutoffTake name xs = pStateListF "cutoff" name xs cutoffCount :: String -> ControlPattern cutoffCount name = pStateF "cutoff" name (maybe 0 (+1)) cutoffCountTo :: String -> Pattern Double -> Pattern ValueMap cutoffCountTo name ipat = innerJoin $ (\i -> pStateF "cutoff" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat cutoffbus :: Pattern Int -> Pattern Double -> ControlPattern cutoffbus busid pat = (pF "cutoff" pat) # (pI "^cutoff" busid) cutoffrecv :: Pattern Int -> ControlPattern cutoffrecv busid = pI "^cutoff" busid -- | cutoffegint :: Pattern Double -> ControlPattern cutoffegint = pF "cutoffegint" cutoffegintTake :: String -> [Double] -> ControlPattern cutoffegintTake name xs = pStateListF "cutoffegint" name xs cutoffegintCount :: String -> ControlPattern cutoffegintCount name = pStateF "cutoffegint" name (maybe 0 (+1)) cutoffegintCountTo :: String -> Pattern Double -> Pattern ValueMap cutoffegintCountTo name ipat = innerJoin $ (\i -> pStateF "cutoffegint" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat cutoffegintbus :: Pattern Int -> Pattern Double -> ControlPattern cutoffegintbus busid pat = (pF "cutoffegint" pat) # (pI "^cutoffegint" busid) cutoffegintrecv :: Pattern Int -> ControlPattern cutoffegintrecv busid = pI "^cutoffegint" busid -- | decay :: Pattern Double -> ControlPattern decay = pF "decay" decayTake :: String -> [Double] -> ControlPattern decayTake name xs = pStateListF "decay" name xs decayCount :: String -> ControlPattern decayCount name = pStateF "decay" name (maybe 0 (+1)) decayCountTo :: String -> Pattern Double -> Pattern ValueMap decayCountTo name ipat = innerJoin $ (\i -> pStateF "decay" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat decaybus :: Pattern Int -> Pattern Double -> ControlPattern decaybus busid pat = (pF "decay" pat) # (pI "^decay" busid) decayrecv :: Pattern Int -> ControlPattern decayrecv busid = pI "^decay" busid -- | degree :: Pattern Double -> ControlPattern degree = pF "degree" degreeTake :: String -> [Double] -> ControlPattern degreeTake name xs = pStateListF "degree" name xs degreeCount :: String -> ControlPattern degreeCount name = pStateF "degree" name (maybe 0 (+1)) degreeCountTo :: String -> Pattern Double -> Pattern ValueMap degreeCountTo name ipat = innerJoin $ (\i -> pStateF "degree" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat degreebus :: Pattern Int -> Pattern Double -> ControlPattern degreebus busid pat = (pF "degree" pat) # (pI "^degree" busid) degreerecv :: Pattern Int -> ControlPattern degreerecv busid = pI "^degree" busid -- | a pattern of numbers from 0 to 1. Sets the level of the delay signal. delay :: Pattern Double -> ControlPattern delay = pF "delay" delayTake :: String -> [Double] -> ControlPattern delayTake name xs = pStateListF "delay" name xs delayCount :: String -> ControlPattern delayCount name = pStateF "delay" name (maybe 0 (+1)) delayCountTo :: String -> Pattern Double -> Pattern ValueMap delayCountTo name ipat = innerJoin $ (\i -> pStateF "delay" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat delaybus :: Pattern Int -> Pattern Double -> ControlPattern delaybus busid pat = (pF "delay" pat) # (pI "^delay" busid) delayrecv :: Pattern Int -> ControlPattern delayrecv busid = pI "^delay" busid -- | a pattern of numbers from 0 to 1. Sets the amount of delay feedback. delayfeedback :: Pattern Double -> ControlPattern delayfeedback = pF "delayfeedback" delayfeedbackTake :: String -> [Double] -> ControlPattern delayfeedbackTake name xs = pStateListF "delayfeedback" name xs delayfeedbackCount :: String -> ControlPattern delayfeedbackCount name = pStateF "delayfeedback" name (maybe 0 (+1)) delayfeedbackCountTo :: String -> Pattern Double -> Pattern ValueMap delayfeedbackCountTo name ipat = innerJoin $ (\i -> pStateF "delayfeedback" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat delayfeedbackbus :: Pattern Int -> Pattern Double -> ControlPattern delayfeedbackbus busid pat = (pF "delayfeedback" pat) # (pI "^delayfeedback" busid) delayfeedbackrecv :: Pattern Int -> ControlPattern delayfeedbackrecv busid = pI "^delayfeedback" busid -- | a pattern of numbers from 0 to 1. Sets the length of the delay. delaytime :: Pattern Double -> ControlPattern delaytime = pF "delaytime" delaytimeTake :: String -> [Double] -> ControlPattern delaytimeTake name xs = pStateListF "delaytime" name xs delaytimeCount :: String -> ControlPattern delaytimeCount name = pStateF "delaytime" name (maybe 0 (+1)) delaytimeCountTo :: String -> Pattern Double -> Pattern ValueMap delaytimeCountTo name ipat = innerJoin $ (\i -> pStateF "delaytime" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat delaytimebus :: Pattern Int -> Pattern Double -> ControlPattern delaytimebus busid pat = (pF "delaytime" pat) # (pI "^delaytime" busid) delaytimerecv :: Pattern Int -> ControlPattern delaytimerecv busid = pI "^delaytime" busid -- | detune :: Pattern Double -> ControlPattern detune = pF "detune" detuneTake :: String -> [Double] -> ControlPattern detuneTake name xs = pStateListF "detune" name xs detuneCount :: String -> ControlPattern detuneCount name = pStateF "detune" name (maybe 0 (+1)) detuneCountTo :: String -> Pattern Double -> Pattern ValueMap detuneCountTo name ipat = innerJoin $ (\i -> pStateF "detune" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat detunebus :: Pattern Int -> Pattern Double -> ControlPattern detunebus busid pat = (pF "detune" pat) # (pI "^detune" busid) detunerecv :: Pattern Int -> ControlPattern detunerecv busid = pI "^detune" busid -- | noisy fuzzy distortion distort :: Pattern Double -> ControlPattern distort = pF "distort" distortTake :: String -> [Double] -> ControlPattern distortTake name xs = pStateListF "distort" name xs distortCount :: String -> ControlPattern distortCount name = pStateF "distort" name (maybe 0 (+1)) distortCountTo :: String -> Pattern Double -> Pattern ValueMap distortCountTo name ipat = innerJoin $ (\i -> pStateF "distort" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat distortbus :: Pattern Int -> Pattern Double -> ControlPattern distortbus busid pat = (pF "distort" pat) # (pI "^distort" busid) distortrecv :: Pattern Int -> ControlPattern distortrecv busid = pI "^distort" busid -- | DJ filter, below 0.5 is low pass filter, above is high pass filter. djf :: Pattern Double -> ControlPattern djf = pF "djf" djfTake :: String -> [Double] -> ControlPattern djfTake name xs = pStateListF "djf" name xs djfCount :: String -> ControlPattern djfCount name = pStateF "djf" name (maybe 0 (+1)) djfCountTo :: String -> Pattern Double -> Pattern ValueMap djfCountTo name ipat = innerJoin $ (\i -> pStateF "djf" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat djfbus :: Pattern Int -> Pattern Double -> ControlPattern djfbus busid pat = (pF "djf" pat) # (pI "^djf" busid) djfrecv :: Pattern Int -> ControlPattern djfrecv busid = pI "^djf" busid -- | when set to `1` will disable all reverb for this pattern. See `room` and `size` for more information about reverb. dry :: Pattern Double -> ControlPattern dry = pF "dry" dryTake :: String -> [Double] -> ControlPattern dryTake name xs = pStateListF "dry" name xs dryCount :: String -> ControlPattern dryCount name = pStateF "dry" name (maybe 0 (+1)) dryCountTo :: String -> Pattern Double -> Pattern ValueMap dryCountTo name ipat = innerJoin $ (\i -> pStateF "dry" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat drybus :: Pattern Int -> Pattern Double -> ControlPattern drybus busid pat = (pF "dry" pat) # (pI "^dry" busid) dryrecv :: Pattern Int -> ControlPattern dryrecv busid = pI "^dry" busid -- | dur :: Pattern Double -> ControlPattern dur = pF "dur" durTake :: String -> [Double] -> ControlPattern durTake name xs = pStateListF "dur" name xs durCount :: String -> ControlPattern durCount name = pStateF "dur" name (maybe 0 (+1)) durCountTo :: String -> Pattern Double -> Pattern ValueMap durCountTo name ipat = innerJoin $ (\i -> pStateF "dur" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat durbus :: Pattern Int -> Pattern Double -> ControlPattern durbus busid pat = (pF "dur" pat) # (pI "^dur" busid) durrecv :: Pattern Int -> ControlPattern durrecv busid = pI "^dur" busid -- | the same as `begin`, but cuts the end off samples, shortening them; e.g. `0.75` to cut off the last quarter of each sample. end :: Pattern Double -> ControlPattern end = pF "end" endTake :: String -> [Double] -> ControlPattern endTake name xs = pStateListF "end" name xs endCount :: String -> ControlPattern endCount name = pStateF "end" name (maybe 0 (+1)) endCountTo :: String -> Pattern Double -> Pattern ValueMap endCountTo name ipat = innerJoin $ (\i -> pStateF "end" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat endbus :: Pattern Int -> Pattern Double -> ControlPattern endbus _ _ = error $ "Control parameter 'end' can't be sent to a bus." -- | Spectral enhance enhance :: Pattern Double -> ControlPattern enhance = pF "enhance" enhanceTake :: String -> [Double] -> ControlPattern enhanceTake name xs = pStateListF "enhance" name xs enhanceCount :: String -> ControlPattern enhanceCount name = pStateF "enhance" name (maybe 0 (+1)) enhanceCountTo :: String -> Pattern Double -> Pattern ValueMap enhanceCountTo name ipat = innerJoin $ (\i -> pStateF "enhance" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat enhancebus :: Pattern Int -> Pattern Double -> ControlPattern enhancebus busid pat = (pF "enhance" pat) # (pI "^enhance" busid) enhancerecv :: Pattern Int -> ControlPattern enhancerecv busid = pI "^enhance" busid -- | expression :: Pattern Double -> ControlPattern expression = pF "expression" expressionTake :: String -> [Double] -> ControlPattern expressionTake name xs = pStateListF "expression" name xs expressionCount :: String -> ControlPattern expressionCount name = pStateF "expression" name (maybe 0 (+1)) expressionCountTo :: String -> Pattern Double -> Pattern ValueMap expressionCountTo name ipat = innerJoin $ (\i -> pStateF "expression" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat expressionbus :: Pattern Int -> Pattern Double -> ControlPattern expressionbus busid pat = (pF "expression" pat) # (pI "^expression" busid) expressionrecv :: Pattern Int -> ControlPattern expressionrecv busid = pI "^expression" busid -- | As with fadeTime, but controls the fade in time of the grain envelope. Not used if the grain begins at position 0 in the sample. fadeInTime :: Pattern Double -> ControlPattern fadeInTime = pF "fadeInTime" fadeInTimeTake :: String -> [Double] -> ControlPattern fadeInTimeTake name xs = pStateListF "fadeInTime" name xs fadeInTimeCount :: String -> ControlPattern fadeInTimeCount name = pStateF "fadeInTime" name (maybe 0 (+1)) fadeInTimeCountTo :: String -> Pattern Double -> Pattern ValueMap fadeInTimeCountTo name ipat = innerJoin $ (\i -> pStateF "fadeInTime" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat fadeInTimebus :: Pattern Int -> Pattern Double -> ControlPattern fadeInTimebus _ _ = error $ "Control parameter 'fadeInTime' can't be sent to a bus." -- | Used when using begin/end or chop/striate and friends, to change the fade out time of the 'grain' envelope. fadeTime :: Pattern Double -> ControlPattern fadeTime = pF "fadeTime" fadeTimeTake :: String -> [Double] -> ControlPattern fadeTimeTake name xs = pStateListF "fadeTime" name xs fadeTimeCount :: String -> ControlPattern fadeTimeCount name = pStateF "fadeTime" name (maybe 0 (+1)) fadeTimeCountTo :: String -> Pattern Double -> Pattern ValueMap fadeTimeCountTo name ipat = innerJoin $ (\i -> pStateF "fadeTime" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat fadeTimebus :: Pattern Int -> Pattern Double -> ControlPattern fadeTimebus _ _ = error $ "Control parameter 'fadeTime' can't be sent to a bus." -- | frameRate :: Pattern Double -> ControlPattern frameRate = pF "frameRate" frameRateTake :: String -> [Double] -> ControlPattern frameRateTake name xs = pStateListF "frameRate" name xs frameRateCount :: String -> ControlPattern frameRateCount name = pStateF "frameRate" name (maybe 0 (+1)) frameRateCountTo :: String -> Pattern Double -> Pattern ValueMap frameRateCountTo name ipat = innerJoin $ (\i -> pStateF "frameRate" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat frameRatebus :: Pattern Int -> Pattern Double -> ControlPattern frameRatebus _ _ = error $ "Control parameter 'frameRate' can't be sent to a bus." -- | frames :: Pattern Double -> ControlPattern frames = pF "frames" framesTake :: String -> [Double] -> ControlPattern framesTake name xs = pStateListF "frames" name xs framesCount :: String -> ControlPattern framesCount name = pStateF "frames" name (maybe 0 (+1)) framesCountTo :: String -> Pattern Double -> Pattern ValueMap framesCountTo name ipat = innerJoin $ (\i -> pStateF "frames" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat framesbus :: Pattern Int -> Pattern Double -> ControlPattern framesbus _ _ = error $ "Control parameter 'frames' can't be sent to a bus." -- | Spectral freeze freeze :: Pattern Double -> ControlPattern freeze = pF "freeze" freezeTake :: String -> [Double] -> ControlPattern freezeTake name xs = pStateListF "freeze" name xs freezeCount :: String -> ControlPattern freezeCount name = pStateF "freeze" name (maybe 0 (+1)) freezeCountTo :: String -> Pattern Double -> Pattern ValueMap freezeCountTo name ipat = innerJoin $ (\i -> pStateF "freeze" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat freezebus :: Pattern Int -> Pattern Double -> ControlPattern freezebus busid pat = (pF "freeze" pat) # (pI "^freeze" busid) freezerecv :: Pattern Int -> ControlPattern freezerecv busid = pI "^freeze" busid -- | freq :: Pattern Double -> ControlPattern freq = pF "freq" freqTake :: String -> [Double] -> ControlPattern freqTake name xs = pStateListF "freq" name xs freqCount :: String -> ControlPattern freqCount name = pStateF "freq" name (maybe 0 (+1)) freqCountTo :: String -> Pattern Double -> Pattern ValueMap freqCountTo name ipat = innerJoin $ (\i -> pStateF "freq" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat freqbus :: Pattern Int -> Pattern Double -> ControlPattern freqbus busid pat = (pF "freq" pat) # (pI "^freq" busid) freqrecv :: Pattern Int -> ControlPattern freqrecv busid = pI "^freq" busid -- | for internal sound routing from :: Pattern Double -> ControlPattern from = pF "from" fromTake :: String -> [Double] -> ControlPattern fromTake name xs = pStateListF "from" name xs fromCount :: String -> ControlPattern fromCount name = pStateF "from" name (maybe 0 (+1)) fromCountTo :: String -> Pattern Double -> Pattern ValueMap fromCountTo name ipat = innerJoin $ (\i -> pStateF "from" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat frombus :: Pattern Int -> Pattern Double -> ControlPattern frombus busid pat = (pF "from" pat) # (pI "^from" busid) fromrecv :: Pattern Int -> ControlPattern fromrecv busid = pI "^from" busid -- | frequency shifter fshift :: Pattern Double -> ControlPattern fshift = pF "fshift" fshiftTake :: String -> [Double] -> ControlPattern fshiftTake name xs = pStateListF "fshift" name xs fshiftCount :: String -> ControlPattern fshiftCount name = pStateF "fshift" name (maybe 0 (+1)) fshiftCountTo :: String -> Pattern Double -> Pattern ValueMap fshiftCountTo name ipat = innerJoin $ (\i -> pStateF "fshift" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat fshiftbus :: Pattern Int -> Pattern Double -> ControlPattern fshiftbus busid pat = (pF "fshift" pat) # (pI "^fshift" busid) fshiftrecv :: Pattern Int -> ControlPattern fshiftrecv busid = pI "^fshift" busid -- | frequency shifter fshiftnote :: Pattern Double -> ControlPattern fshiftnote = pF "fshiftnote" fshiftnoteTake :: String -> [Double] -> ControlPattern fshiftnoteTake name xs = pStateListF "fshiftnote" name xs fshiftnoteCount :: String -> ControlPattern fshiftnoteCount name = pStateF "fshiftnote" name (maybe 0 (+1)) fshiftnoteCountTo :: String -> Pattern Double -> Pattern ValueMap fshiftnoteCountTo name ipat = innerJoin $ (\i -> pStateF "fshiftnote" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat fshiftnotebus :: Pattern Int -> Pattern Double -> ControlPattern fshiftnotebus busid pat = (pF "fshiftnote" pat) # (pI "^fshiftnote" busid) fshiftnoterecv :: Pattern Int -> ControlPattern fshiftnoterecv busid = pI "^fshiftnote" busid -- | frequency shifter fshiftphase :: Pattern Double -> ControlPattern fshiftphase = pF "fshiftphase" fshiftphaseTake :: String -> [Double] -> ControlPattern fshiftphaseTake name xs = pStateListF "fshiftphase" name xs fshiftphaseCount :: String -> ControlPattern fshiftphaseCount name = pStateF "fshiftphase" name (maybe 0 (+1)) fshiftphaseCountTo :: String -> Pattern Double -> Pattern ValueMap fshiftphaseCountTo name ipat = innerJoin $ (\i -> pStateF "fshiftphase" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat fshiftphasebus :: Pattern Int -> Pattern Double -> ControlPattern fshiftphasebus busid pat = (pF "fshiftphase" pat) # (pI "^fshiftphase" busid) fshiftphaserecv :: Pattern Int -> ControlPattern fshiftphaserecv busid = pI "^fshiftphase" busid -- | a pattern of numbers that specify volume. Values less than 1 make the sound quieter. Values greater than 1 make the sound louder. For the linear equivalent, see @amp@. gain :: Pattern Double -> ControlPattern gain = pF "gain" gainTake :: String -> [Double] -> ControlPattern gainTake name xs = pStateListF "gain" name xs gainCount :: String -> ControlPattern gainCount name = pStateF "gain" name (maybe 0 (+1)) gainCountTo :: String -> Pattern Double -> Pattern ValueMap gainCountTo name ipat = innerJoin $ (\i -> pStateF "gain" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat gainbus :: Pattern Int -> Pattern Double -> ControlPattern gainbus _ _ = error $ "Control parameter 'gain' can't be sent to a bus." -- | gate :: Pattern Double -> ControlPattern gate = pF "gate" gateTake :: String -> [Double] -> ControlPattern gateTake name xs = pStateListF "gate" name xs gateCount :: String -> ControlPattern gateCount name = pStateF "gate" name (maybe 0 (+1)) gateCountTo :: String -> Pattern Double -> Pattern ValueMap gateCountTo name ipat = innerJoin $ (\i -> pStateF "gate" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat gatebus :: Pattern Int -> Pattern Double -> ControlPattern gatebus busid pat = (pF "gate" pat) # (pI "^gate" busid) gaterecv :: Pattern Int -> ControlPattern gaterecv busid = pI "^gate" busid -- | harmonic :: Pattern Double -> ControlPattern harmonic = pF "harmonic" harmonicTake :: String -> [Double] -> ControlPattern harmonicTake name xs = pStateListF "harmonic" name xs harmonicCount :: String -> ControlPattern harmonicCount name = pStateF "harmonic" name (maybe 0 (+1)) harmonicCountTo :: String -> Pattern Double -> Pattern ValueMap harmonicCountTo name ipat = innerJoin $ (\i -> pStateF "harmonic" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat harmonicbus :: Pattern Int -> Pattern Double -> ControlPattern harmonicbus busid pat = (pF "harmonic" pat) # (pI "^harmonic" busid) harmonicrecv :: Pattern Int -> ControlPattern harmonicrecv busid = pI "^harmonic" busid -- | hatgrain :: Pattern Double -> ControlPattern hatgrain = pF "hatgrain" hatgrainTake :: String -> [Double] -> ControlPattern hatgrainTake name xs = pStateListF "hatgrain" name xs hatgrainCount :: String -> ControlPattern hatgrainCount name = pStateF "hatgrain" name (maybe 0 (+1)) hatgrainCountTo :: String -> Pattern Double -> Pattern ValueMap hatgrainCountTo name ipat = innerJoin $ (\i -> pStateF "hatgrain" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat hatgrainbus :: Pattern Int -> Pattern Double -> ControlPattern hatgrainbus busid pat = (pF "hatgrain" pat) # (pI "^hatgrain" busid) hatgrainrecv :: Pattern Int -> ControlPattern hatgrainrecv busid = pI "^hatgrain" busid -- | High pass sort of spectral filter hbrick :: Pattern Double -> ControlPattern hbrick = pF "hbrick" hbrickTake :: String -> [Double] -> ControlPattern hbrickTake name xs = pStateListF "hbrick" name xs hbrickCount :: String -> ControlPattern hbrickCount name = pStateF "hbrick" name (maybe 0 (+1)) hbrickCountTo :: String -> Pattern Double -> Pattern ValueMap hbrickCountTo name ipat = innerJoin $ (\i -> pStateF "hbrick" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat hbrickbus :: Pattern Int -> Pattern Double -> ControlPattern hbrickbus busid pat = (pF "hbrick" pat) # (pI "^hbrick" busid) hbrickrecv :: Pattern Int -> ControlPattern hbrickrecv busid = pI "^hbrick" busid -- | a pattern of numbers from 0 to 1. Applies the cutoff frequency of the high-pass filter. Also has alias @hpf@ hcutoff :: Pattern Double -> ControlPattern hcutoff = pF "hcutoff" hcutoffTake :: String -> [Double] -> ControlPattern hcutoffTake name xs = pStateListF "hcutoff" name xs hcutoffCount :: String -> ControlPattern hcutoffCount name = pStateF "hcutoff" name (maybe 0 (+1)) hcutoffCountTo :: String -> Pattern Double -> Pattern ValueMap hcutoffCountTo name ipat = innerJoin $ (\i -> pStateF "hcutoff" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat hcutoffbus :: Pattern Int -> Pattern Double -> ControlPattern hcutoffbus busid pat = (pF "hcutoff" pat) # (pI "^hcutoff" busid) hcutoffrecv :: Pattern Int -> ControlPattern hcutoffrecv busid = pI "^hcutoff" busid -- | a pattern of numbers to specify the hold time (in seconds) of an envelope applied to each sample. Only takes effect if `attack` and `release` are also specified. hold :: Pattern Double -> ControlPattern hold = pF "hold" holdTake :: String -> [Double] -> ControlPattern holdTake name xs = pStateListF "hold" name xs holdCount :: String -> ControlPattern holdCount name = pStateF "hold" name (maybe 0 (+1)) holdCountTo :: String -> Pattern Double -> Pattern ValueMap holdCountTo name ipat = innerJoin $ (\i -> pStateF "hold" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat holdbus :: Pattern Int -> Pattern Double -> ControlPattern holdbus busid pat = (pF "hold" pat) # (pI "^hold" busid) holdrecv :: Pattern Int -> ControlPattern holdrecv busid = pI "^hold" busid -- | hours :: Pattern Double -> ControlPattern hours = pF "hours" hoursTake :: String -> [Double] -> ControlPattern hoursTake name xs = pStateListF "hours" name xs hoursCount :: String -> ControlPattern hoursCount name = pStateF "hours" name (maybe 0 (+1)) hoursCountTo :: String -> Pattern Double -> Pattern ValueMap hoursCountTo name ipat = innerJoin $ (\i -> pStateF "hours" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat hoursbus :: Pattern Int -> Pattern Double -> ControlPattern hoursbus _ _ = error $ "Control parameter 'hours' can't be sent to a bus." -- | a pattern of numbers from 0 to 1. Applies the resonance of the high-pass filter. Has alias @hpq@ hresonance :: Pattern Double -> ControlPattern hresonance = pF "hresonance" hresonanceTake :: String -> [Double] -> ControlPattern hresonanceTake name xs = pStateListF "hresonance" name xs hresonanceCount :: String -> ControlPattern hresonanceCount name = pStateF "hresonance" name (maybe 0 (+1)) hresonanceCountTo :: String -> Pattern Double -> Pattern ValueMap hresonanceCountTo name ipat = innerJoin $ (\i -> pStateF "hresonance" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat hresonancebus :: Pattern Int -> Pattern Double -> ControlPattern hresonancebus busid pat = (pF "hresonance" pat) # (pI "^hresonance" busid) hresonancerecv :: Pattern Int -> ControlPattern hresonancerecv busid = pI "^hresonance" busid -- | imag :: Pattern Double -> ControlPattern imag = pF "imag" imagTake :: String -> [Double] -> ControlPattern imagTake name xs = pStateListF "imag" name xs imagCount :: String -> ControlPattern imagCount name = pStateF "imag" name (maybe 0 (+1)) imagCountTo :: String -> Pattern Double -> Pattern ValueMap imagCountTo name ipat = innerJoin $ (\i -> pStateF "imag" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat imagbus :: Pattern Int -> Pattern Double -> ControlPattern imagbus busid pat = (pF "imag" pat) # (pI "^imag" busid) imagrecv :: Pattern Int -> ControlPattern imagrecv busid = pI "^imag" busid -- | kcutoff :: Pattern Double -> ControlPattern kcutoff = pF "kcutoff" kcutoffTake :: String -> [Double] -> ControlPattern kcutoffTake name xs = pStateListF "kcutoff" name xs kcutoffCount :: String -> ControlPattern kcutoffCount name = pStateF "kcutoff" name (maybe 0 (+1)) kcutoffCountTo :: String -> Pattern Double -> Pattern ValueMap kcutoffCountTo name ipat = innerJoin $ (\i -> pStateF "kcutoff" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat kcutoffbus :: Pattern Int -> Pattern Double -> ControlPattern kcutoffbus busid pat = (pF "kcutoff" pat) # (pI "^kcutoff" busid) kcutoffrecv :: Pattern Int -> ControlPattern kcutoffrecv busid = pI "^kcutoff" busid -- | shape/bass enhancer krush :: Pattern Double -> ControlPattern krush = pF "krush" krushTake :: String -> [Double] -> ControlPattern krushTake name xs = pStateListF "krush" name xs krushCount :: String -> ControlPattern krushCount name = pStateF "krush" name (maybe 0 (+1)) krushCountTo :: String -> Pattern Double -> Pattern ValueMap krushCountTo name ipat = innerJoin $ (\i -> pStateF "krush" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat krushbus :: Pattern Int -> Pattern Double -> ControlPattern krushbus busid pat = (pF "krush" pat) # (pI "^krush" busid) krushrecv :: Pattern Int -> ControlPattern krushrecv busid = pI "^krush" busid -- | lagogo :: Pattern Double -> ControlPattern lagogo = pF "lagogo" lagogoTake :: String -> [Double] -> ControlPattern lagogoTake name xs = pStateListF "lagogo" name xs lagogoCount :: String -> ControlPattern lagogoCount name = pStateF "lagogo" name (maybe 0 (+1)) lagogoCountTo :: String -> Pattern Double -> Pattern ValueMap lagogoCountTo name ipat = innerJoin $ (\i -> pStateF "lagogo" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lagogobus :: Pattern Int -> Pattern Double -> ControlPattern lagogobus busid pat = (pF "lagogo" pat) # (pI "^lagogo" busid) lagogorecv :: Pattern Int -> ControlPattern lagogorecv busid = pI "^lagogo" busid -- | Low pass sort of spectral filter lbrick :: Pattern Double -> ControlPattern lbrick = pF "lbrick" lbrickTake :: String -> [Double] -> ControlPattern lbrickTake name xs = pStateListF "lbrick" name xs lbrickCount :: String -> ControlPattern lbrickCount name = pStateF "lbrick" name (maybe 0 (+1)) lbrickCountTo :: String -> Pattern Double -> Pattern ValueMap lbrickCountTo name ipat = innerJoin $ (\i -> pStateF "lbrick" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lbrickbus :: Pattern Int -> Pattern Double -> ControlPattern lbrickbus busid pat = (pF "lbrick" pat) # (pI "^lbrick" busid) lbrickrecv :: Pattern Int -> ControlPattern lbrickrecv busid = pI "^lbrick" busid -- | lclap :: Pattern Double -> ControlPattern lclap = pF "lclap" lclapTake :: String -> [Double] -> ControlPattern lclapTake name xs = pStateListF "lclap" name xs lclapCount :: String -> ControlPattern lclapCount name = pStateF "lclap" name (maybe 0 (+1)) lclapCountTo :: String -> Pattern Double -> Pattern ValueMap lclapCountTo name ipat = innerJoin $ (\i -> pStateF "lclap" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lclapbus :: Pattern Int -> Pattern Double -> ControlPattern lclapbus busid pat = (pF "lclap" pat) # (pI "^lclap" busid) lclaprecv :: Pattern Int -> ControlPattern lclaprecv busid = pI "^lclap" busid -- | lclaves :: Pattern Double -> ControlPattern lclaves = pF "lclaves" lclavesTake :: String -> [Double] -> ControlPattern lclavesTake name xs = pStateListF "lclaves" name xs lclavesCount :: String -> ControlPattern lclavesCount name = pStateF "lclaves" name (maybe 0 (+1)) lclavesCountTo :: String -> Pattern Double -> Pattern ValueMap lclavesCountTo name ipat = innerJoin $ (\i -> pStateF "lclaves" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lclavesbus :: Pattern Int -> Pattern Double -> ControlPattern lclavesbus busid pat = (pF "lclaves" pat) # (pI "^lclaves" busid) lclavesrecv :: Pattern Int -> ControlPattern lclavesrecv busid = pI "^lclaves" busid -- | lclhat :: Pattern Double -> ControlPattern lclhat = pF "lclhat" lclhatTake :: String -> [Double] -> ControlPattern lclhatTake name xs = pStateListF "lclhat" name xs lclhatCount :: String -> ControlPattern lclhatCount name = pStateF "lclhat" name (maybe 0 (+1)) lclhatCountTo :: String -> Pattern Double -> Pattern ValueMap lclhatCountTo name ipat = innerJoin $ (\i -> pStateF "lclhat" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lclhatbus :: Pattern Int -> Pattern Double -> ControlPattern lclhatbus busid pat = (pF "lclhat" pat) # (pI "^lclhat" busid) lclhatrecv :: Pattern Int -> ControlPattern lclhatrecv busid = pI "^lclhat" busid -- | lcrash :: Pattern Double -> ControlPattern lcrash = pF "lcrash" lcrashTake :: String -> [Double] -> ControlPattern lcrashTake name xs = pStateListF "lcrash" name xs lcrashCount :: String -> ControlPattern lcrashCount name = pStateF "lcrash" name (maybe 0 (+1)) lcrashCountTo :: String -> Pattern Double -> Pattern ValueMap lcrashCountTo name ipat = innerJoin $ (\i -> pStateF "lcrash" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lcrashbus :: Pattern Int -> Pattern Double -> ControlPattern lcrashbus busid pat = (pF "lcrash" pat) # (pI "^lcrash" busid) lcrashrecv :: Pattern Int -> ControlPattern lcrashrecv busid = pI "^lcrash" busid -- | controls the amount of overlap between two adjacent sounds legato :: Pattern Double -> ControlPattern legato = pF "legato" legatoTake :: String -> [Double] -> ControlPattern legatoTake name xs = pStateListF "legato" name xs legatoCount :: String -> ControlPattern legatoCount name = pStateF "legato" name (maybe 0 (+1)) legatoCountTo :: String -> Pattern Double -> Pattern ValueMap legatoCountTo name ipat = innerJoin $ (\i -> pStateF "legato" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat legatobus :: Pattern Int -> Pattern Double -> ControlPattern legatobus _ _ = error $ "Control parameter 'legato' can't be sent to a bus." -- | leslie :: Pattern Double -> ControlPattern leslie = pF "leslie" leslieTake :: String -> [Double] -> ControlPattern leslieTake name xs = pStateListF "leslie" name xs leslieCount :: String -> ControlPattern leslieCount name = pStateF "leslie" name (maybe 0 (+1)) leslieCountTo :: String -> Pattern Double -> Pattern ValueMap leslieCountTo name ipat = innerJoin $ (\i -> pStateF "leslie" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lesliebus :: Pattern Int -> Pattern Double -> ControlPattern lesliebus busid pat = (pF "leslie" pat) # (pI "^leslie" busid) leslierecv :: Pattern Int -> ControlPattern leslierecv busid = pI "^leslie" busid -- | lfo :: Pattern Double -> ControlPattern lfo = pF "lfo" lfoTake :: String -> [Double] -> ControlPattern lfoTake name xs = pStateListF "lfo" name xs lfoCount :: String -> ControlPattern lfoCount name = pStateF "lfo" name (maybe 0 (+1)) lfoCountTo :: String -> Pattern Double -> Pattern ValueMap lfoCountTo name ipat = innerJoin $ (\i -> pStateF "lfo" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lfobus :: Pattern Int -> Pattern Double -> ControlPattern lfobus busid pat = (pF "lfo" pat) # (pI "^lfo" busid) lforecv :: Pattern Int -> ControlPattern lforecv busid = pI "^lfo" busid -- | lfocutoffint :: Pattern Double -> ControlPattern lfocutoffint = pF "lfocutoffint" lfocutoffintTake :: String -> [Double] -> ControlPattern lfocutoffintTake name xs = pStateListF "lfocutoffint" name xs lfocutoffintCount :: String -> ControlPattern lfocutoffintCount name = pStateF "lfocutoffint" name (maybe 0 (+1)) lfocutoffintCountTo :: String -> Pattern Double -> Pattern ValueMap lfocutoffintCountTo name ipat = innerJoin $ (\i -> pStateF "lfocutoffint" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lfocutoffintbus :: Pattern Int -> Pattern Double -> ControlPattern lfocutoffintbus busid pat = (pF "lfocutoffint" pat) # (pI "^lfocutoffint" busid) lfocutoffintrecv :: Pattern Int -> ControlPattern lfocutoffintrecv busid = pI "^lfocutoffint" busid -- | lfodelay :: Pattern Double -> ControlPattern lfodelay = pF "lfodelay" lfodelayTake :: String -> [Double] -> ControlPattern lfodelayTake name xs = pStateListF "lfodelay" name xs lfodelayCount :: String -> ControlPattern lfodelayCount name = pStateF "lfodelay" name (maybe 0 (+1)) lfodelayCountTo :: String -> Pattern Double -> Pattern ValueMap lfodelayCountTo name ipat = innerJoin $ (\i -> pStateF "lfodelay" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lfodelaybus :: Pattern Int -> Pattern Double -> ControlPattern lfodelaybus busid pat = (pF "lfodelay" pat) # (pI "^lfodelay" busid) lfodelayrecv :: Pattern Int -> ControlPattern lfodelayrecv busid = pI "^lfodelay" busid -- | lfoint :: Pattern Double -> ControlPattern lfoint = pF "lfoint" lfointTake :: String -> [Double] -> ControlPattern lfointTake name xs = pStateListF "lfoint" name xs lfointCount :: String -> ControlPattern lfointCount name = pStateF "lfoint" name (maybe 0 (+1)) lfointCountTo :: String -> Pattern Double -> Pattern ValueMap lfointCountTo name ipat = innerJoin $ (\i -> pStateF "lfoint" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lfointbus :: Pattern Int -> Pattern Double -> ControlPattern lfointbus busid pat = (pF "lfoint" pat) # (pI "^lfoint" busid) lfointrecv :: Pattern Int -> ControlPattern lfointrecv busid = pI "^lfoint" busid -- | lfopitchint :: Pattern Double -> ControlPattern lfopitchint = pF "lfopitchint" lfopitchintTake :: String -> [Double] -> ControlPattern lfopitchintTake name xs = pStateListF "lfopitchint" name xs lfopitchintCount :: String -> ControlPattern lfopitchintCount name = pStateF "lfopitchint" name (maybe 0 (+1)) lfopitchintCountTo :: String -> Pattern Double -> Pattern ValueMap lfopitchintCountTo name ipat = innerJoin $ (\i -> pStateF "lfopitchint" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lfopitchintbus :: Pattern Int -> Pattern Double -> ControlPattern lfopitchintbus busid pat = (pF "lfopitchint" pat) # (pI "^lfopitchint" busid) lfopitchintrecv :: Pattern Int -> ControlPattern lfopitchintrecv busid = pI "^lfopitchint" busid -- | lfoshape :: Pattern Double -> ControlPattern lfoshape = pF "lfoshape" lfoshapeTake :: String -> [Double] -> ControlPattern lfoshapeTake name xs = pStateListF "lfoshape" name xs lfoshapeCount :: String -> ControlPattern lfoshapeCount name = pStateF "lfoshape" name (maybe 0 (+1)) lfoshapeCountTo :: String -> Pattern Double -> Pattern ValueMap lfoshapeCountTo name ipat = innerJoin $ (\i -> pStateF "lfoshape" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lfoshapebus :: Pattern Int -> Pattern Double -> ControlPattern lfoshapebus busid pat = (pF "lfoshape" pat) # (pI "^lfoshape" busid) lfoshaperecv :: Pattern Int -> ControlPattern lfoshaperecv busid = pI "^lfoshape" busid -- | lfosync :: Pattern Double -> ControlPattern lfosync = pF "lfosync" lfosyncTake :: String -> [Double] -> ControlPattern lfosyncTake name xs = pStateListF "lfosync" name xs lfosyncCount :: String -> ControlPattern lfosyncCount name = pStateF "lfosync" name (maybe 0 (+1)) lfosyncCountTo :: String -> Pattern Double -> Pattern ValueMap lfosyncCountTo name ipat = innerJoin $ (\i -> pStateF "lfosync" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lfosyncbus :: Pattern Int -> Pattern Double -> ControlPattern lfosyncbus busid pat = (pF "lfosync" pat) # (pI "^lfosync" busid) lfosyncrecv :: Pattern Int -> ControlPattern lfosyncrecv busid = pI "^lfosync" busid -- | lhitom :: Pattern Double -> ControlPattern lhitom = pF "lhitom" lhitomTake :: String -> [Double] -> ControlPattern lhitomTake name xs = pStateListF "lhitom" name xs lhitomCount :: String -> ControlPattern lhitomCount name = pStateF "lhitom" name (maybe 0 (+1)) lhitomCountTo :: String -> Pattern Double -> Pattern ValueMap lhitomCountTo name ipat = innerJoin $ (\i -> pStateF "lhitom" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lhitombus :: Pattern Int -> Pattern Double -> ControlPattern lhitombus busid pat = (pF "lhitom" pat) # (pI "^lhitom" busid) lhitomrecv :: Pattern Int -> ControlPattern lhitomrecv busid = pI "^lhitom" busid -- | lkick :: Pattern Double -> ControlPattern lkick = pF "lkick" lkickTake :: String -> [Double] -> ControlPattern lkickTake name xs = pStateListF "lkick" name xs lkickCount :: String -> ControlPattern lkickCount name = pStateF "lkick" name (maybe 0 (+1)) lkickCountTo :: String -> Pattern Double -> Pattern ValueMap lkickCountTo name ipat = innerJoin $ (\i -> pStateF "lkick" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lkickbus :: Pattern Int -> Pattern Double -> ControlPattern lkickbus busid pat = (pF "lkick" pat) # (pI "^lkick" busid) lkickrecv :: Pattern Int -> ControlPattern lkickrecv busid = pI "^lkick" busid -- | llotom :: Pattern Double -> ControlPattern llotom = pF "llotom" llotomTake :: String -> [Double] -> ControlPattern llotomTake name xs = pStateListF "llotom" name xs llotomCount :: String -> ControlPattern llotomCount name = pStateF "llotom" name (maybe 0 (+1)) llotomCountTo :: String -> Pattern Double -> Pattern ValueMap llotomCountTo name ipat = innerJoin $ (\i -> pStateF "llotom" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat llotombus :: Pattern Int -> Pattern Double -> ControlPattern llotombus busid pat = (pF "llotom" pat) # (pI "^llotom" busid) llotomrecv :: Pattern Int -> ControlPattern llotomrecv busid = pI "^llotom" busid -- | A pattern of numbers. Specifies whether delaytime is calculated relative to cps. When set to 1, delaytime is a direct multiple of a cycle. lock :: Pattern Double -> ControlPattern lock = pF "lock" lockTake :: String -> [Double] -> ControlPattern lockTake name xs = pStateListF "lock" name xs lockCount :: String -> ControlPattern lockCount name = pStateF "lock" name (maybe 0 (+1)) lockCountTo :: String -> Pattern Double -> Pattern ValueMap lockCountTo name ipat = innerJoin $ (\i -> pStateF "lock" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lockbus :: Pattern Int -> Pattern Double -> ControlPattern lockbus busid pat = (pF "lock" pat) # (pI "^lock" busid) lockrecv :: Pattern Int -> ControlPattern lockrecv busid = pI "^lock" busid -- | loops the sample (from `begin` to `end`) the specified number of times. loop :: Pattern Double -> ControlPattern loop = pF "loop" loopTake :: String -> [Double] -> ControlPattern loopTake name xs = pStateListF "loop" name xs loopCount :: String -> ControlPattern loopCount name = pStateF "loop" name (maybe 0 (+1)) loopCountTo :: String -> Pattern Double -> Pattern ValueMap loopCountTo name ipat = innerJoin $ (\i -> pStateF "loop" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat loopbus :: Pattern Int -> Pattern Double -> ControlPattern loopbus _ _ = error $ "Control parameter 'loop' can't be sent to a bus." -- | lophat :: Pattern Double -> ControlPattern lophat = pF "lophat" lophatTake :: String -> [Double] -> ControlPattern lophatTake name xs = pStateListF "lophat" name xs lophatCount :: String -> ControlPattern lophatCount name = pStateF "lophat" name (maybe 0 (+1)) lophatCountTo :: String -> Pattern Double -> Pattern ValueMap lophatCountTo name ipat = innerJoin $ (\i -> pStateF "lophat" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lophatbus :: Pattern Int -> Pattern Double -> ControlPattern lophatbus busid pat = (pF "lophat" pat) # (pI "^lophat" busid) lophatrecv :: Pattern Int -> ControlPattern lophatrecv busid = pI "^lophat" busid -- | lrate :: Pattern Double -> ControlPattern lrate = pF "lrate" lrateTake :: String -> [Double] -> ControlPattern lrateTake name xs = pStateListF "lrate" name xs lrateCount :: String -> ControlPattern lrateCount name = pStateF "lrate" name (maybe 0 (+1)) lrateCountTo :: String -> Pattern Double -> Pattern ValueMap lrateCountTo name ipat = innerJoin $ (\i -> pStateF "lrate" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lratebus :: Pattern Int -> Pattern Double -> ControlPattern lratebus busid pat = (pF "lrate" pat) # (pI "^lrate" busid) lraterecv :: Pattern Int -> ControlPattern lraterecv busid = pI "^lrate" busid -- | lsize :: Pattern Double -> ControlPattern lsize = pF "lsize" lsizeTake :: String -> [Double] -> ControlPattern lsizeTake name xs = pStateListF "lsize" name xs lsizeCount :: String -> ControlPattern lsizeCount name = pStateF "lsize" name (maybe 0 (+1)) lsizeCountTo :: String -> Pattern Double -> Pattern ValueMap lsizeCountTo name ipat = innerJoin $ (\i -> pStateF "lsize" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lsizebus :: Pattern Int -> Pattern Double -> ControlPattern lsizebus busid pat = (pF "lsize" pat) # (pI "^lsize" busid) lsizerecv :: Pattern Int -> ControlPattern lsizerecv busid = pI "^lsize" busid -- | lsnare :: Pattern Double -> ControlPattern lsnare = pF "lsnare" lsnareTake :: String -> [Double] -> ControlPattern lsnareTake name xs = pStateListF "lsnare" name xs lsnareCount :: String -> ControlPattern lsnareCount name = pStateF "lsnare" name (maybe 0 (+1)) lsnareCountTo :: String -> Pattern Double -> Pattern ValueMap lsnareCountTo name ipat = innerJoin $ (\i -> pStateF "lsnare" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat lsnarebus :: Pattern Int -> Pattern Double -> ControlPattern lsnarebus busid pat = (pF "lsnare" pat) # (pI "^lsnare" busid) lsnarerecv :: Pattern Int -> ControlPattern lsnarerecv busid = pI "^lsnare" busid -- | midibend :: Pattern Double -> ControlPattern midibend = pF "midibend" midibendTake :: String -> [Double] -> ControlPattern midibendTake name xs = pStateListF "midibend" name xs midibendCount :: String -> ControlPattern midibendCount name = pStateF "midibend" name (maybe 0 (+1)) midibendCountTo :: String -> Pattern Double -> Pattern ValueMap midibendCountTo name ipat = innerJoin $ (\i -> pStateF "midibend" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat midibendbus :: Pattern Int -> Pattern Double -> ControlPattern midibendbus _ _ = error $ "Control parameter 'midibend' can't be sent to a bus." -- | midichan :: Pattern Double -> ControlPattern midichan = pF "midichan" midichanTake :: String -> [Double] -> ControlPattern midichanTake name xs = pStateListF "midichan" name xs midichanCount :: String -> ControlPattern midichanCount name = pStateF "midichan" name (maybe 0 (+1)) midichanCountTo :: String -> Pattern Double -> Pattern ValueMap midichanCountTo name ipat = innerJoin $ (\i -> pStateF "midichan" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat midichanbus :: Pattern Int -> Pattern Double -> ControlPattern midichanbus _ _ = error $ "Control parameter 'midichan' can't be sent to a bus." -- | midicmd :: Pattern String -> ControlPattern midicmd = pS "midicmd" midicmdTake :: String -> [Double] -> ControlPattern midicmdTake name xs = pStateListF "midicmd" name xs midicmdbus :: Pattern Int -> Pattern String -> ControlPattern midicmdbus _ _ = error $ "Control parameter 'midicmd' can't be sent to a bus." -- | miditouch :: Pattern Double -> ControlPattern miditouch = pF "miditouch" miditouchTake :: String -> [Double] -> ControlPattern miditouchTake name xs = pStateListF "miditouch" name xs miditouchCount :: String -> ControlPattern miditouchCount name = pStateF "miditouch" name (maybe 0 (+1)) miditouchCountTo :: String -> Pattern Double -> Pattern ValueMap miditouchCountTo name ipat = innerJoin $ (\i -> pStateF "miditouch" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat miditouchbus :: Pattern Int -> Pattern Double -> ControlPattern miditouchbus _ _ = error $ "Control parameter 'miditouch' can't be sent to a bus." -- | minutes :: Pattern Double -> ControlPattern minutes = pF "minutes" minutesTake :: String -> [Double] -> ControlPattern minutesTake name xs = pStateListF "minutes" name xs minutesCount :: String -> ControlPattern minutesCount name = pStateF "minutes" name (maybe 0 (+1)) minutesCountTo :: String -> Pattern Double -> Pattern ValueMap minutesCountTo name ipat = innerJoin $ (\i -> pStateF "minutes" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat minutesbus :: Pattern Int -> Pattern Double -> ControlPattern minutesbus _ _ = error $ "Control parameter 'minutes' can't be sent to a bus." -- | modwheel :: Pattern Double -> ControlPattern modwheel = pF "modwheel" modwheelTake :: String -> [Double] -> ControlPattern modwheelTake name xs = pStateListF "modwheel" name xs modwheelCount :: String -> ControlPattern modwheelCount name = pStateF "modwheel" name (maybe 0 (+1)) modwheelCountTo :: String -> Pattern Double -> Pattern ValueMap modwheelCountTo name ipat = innerJoin $ (\i -> pStateF "modwheel" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat modwheelbus :: Pattern Int -> Pattern Double -> ControlPattern modwheelbus busid pat = (pF "modwheel" pat) # (pI "^modwheel" busid) modwheelrecv :: Pattern Int -> ControlPattern modwheelrecv busid = pI "^modwheel" busid -- | mtranspose :: Pattern Double -> ControlPattern mtranspose = pF "mtranspose" mtransposeTake :: String -> [Double] -> ControlPattern mtransposeTake name xs = pStateListF "mtranspose" name xs mtransposeCount :: String -> ControlPattern mtransposeCount name = pStateF "mtranspose" name (maybe 0 (+1)) mtransposeCountTo :: String -> Pattern Double -> Pattern ValueMap mtransposeCountTo name ipat = innerJoin $ (\i -> pStateF "mtranspose" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat mtransposebus :: Pattern Int -> Pattern Double -> ControlPattern mtransposebus busid pat = (pF "mtranspose" pat) # (pI "^mtranspose" busid) mtransposerecv :: Pattern Int -> ControlPattern mtransposerecv busid = pI "^mtranspose" busid -- | The note or sample number to choose for a synth or sampleset n :: Pattern Note -> ControlPattern n = pN "n" nTake :: String -> [Double] -> ControlPattern nTake name xs = pStateListF "n" name xs nCount :: String -> ControlPattern nCount name = pStateF "n" name (maybe 0 (+1)) nCountTo :: String -> Pattern Double -> Pattern ValueMap nCountTo name ipat = innerJoin $ (\i -> pStateF "n" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat nbus :: Pattern Int -> Pattern Note -> ControlPattern nbus _ _ = error $ "Control parameter 'n' can't be sent to a bus." -- | The note or pitch to play a sound or synth with note :: Pattern Note -> ControlPattern note = pN "note" noteTake :: String -> [Double] -> ControlPattern noteTake name xs = pStateListF "note" name xs noteCount :: String -> ControlPattern noteCount name = pStateF "note" name (maybe 0 (+1)) noteCountTo :: String -> Pattern Double -> Pattern ValueMap noteCountTo name ipat = innerJoin $ (\i -> pStateF "note" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat notebus :: Pattern Int -> Pattern Note -> ControlPattern notebus _ _ = error $ "Control parameter 'note' can't be sent to a bus." -- | Nudges events into the future by the specified number of seconds. Negative numbers work up to a point as well (due to internal latency) nudge :: Pattern Double -> ControlPattern nudge = pF "nudge" nudgeTake :: String -> [Double] -> ControlPattern nudgeTake name xs = pStateListF "nudge" name xs nudgeCount :: String -> ControlPattern nudgeCount name = pStateF "nudge" name (maybe 0 (+1)) nudgeCountTo :: String -> Pattern Double -> Pattern ValueMap nudgeCountTo name ipat = innerJoin $ (\i -> pStateF "nudge" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat nudgebus :: Pattern Int -> Pattern Double -> ControlPattern nudgebus busid pat = (pF "nudge" pat) # (pI "^nudge" busid) nudgerecv :: Pattern Int -> ControlPattern nudgerecv busid = pI "^nudge" busid -- | octave :: Pattern Int -> ControlPattern octave = pI "octave" octaveTake :: String -> [Double] -> ControlPattern octaveTake name xs = pStateListF "octave" name xs octaveCount :: String -> ControlPattern octaveCount name = pStateF "octave" name (maybe 0 (+1)) octaveCountTo :: String -> Pattern Double -> Pattern ValueMap octaveCountTo name ipat = innerJoin $ (\i -> pStateF "octave" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat octavebus :: Pattern Int -> Pattern Int -> ControlPattern octavebus _ _ = error $ "Control parameter 'octave' can't be sent to a bus." -- | octaveR :: Pattern Double -> ControlPattern octaveR = pF "octaveR" octaveRTake :: String -> [Double] -> ControlPattern octaveRTake name xs = pStateListF "octaveR" name xs octaveRCount :: String -> ControlPattern octaveRCount name = pStateF "octaveR" name (maybe 0 (+1)) octaveRCountTo :: String -> Pattern Double -> Pattern ValueMap octaveRCountTo name ipat = innerJoin $ (\i -> pStateF "octaveR" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat octaveRbus :: Pattern Int -> Pattern Double -> ControlPattern octaveRbus busid pat = (pF "octaveR" pat) # (pI "^octaveR" busid) octaveRrecv :: Pattern Int -> ControlPattern octaveRrecv busid = pI "^octaveR" busid -- | octaver effect octer :: Pattern Double -> ControlPattern octer = pF "octer" octerTake :: String -> [Double] -> ControlPattern octerTake name xs = pStateListF "octer" name xs octerCount :: String -> ControlPattern octerCount name = pStateF "octer" name (maybe 0 (+1)) octerCountTo :: String -> Pattern Double -> Pattern ValueMap octerCountTo name ipat = innerJoin $ (\i -> pStateF "octer" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat octerbus :: Pattern Int -> Pattern Double -> ControlPattern octerbus busid pat = (pF "octer" pat) # (pI "^octer" busid) octerrecv :: Pattern Int -> ControlPattern octerrecv busid = pI "^octer" busid -- | octaver effect octersub :: Pattern Double -> ControlPattern octersub = pF "octersub" octersubTake :: String -> [Double] -> ControlPattern octersubTake name xs = pStateListF "octersub" name xs octersubCount :: String -> ControlPattern octersubCount name = pStateF "octersub" name (maybe 0 (+1)) octersubCountTo :: String -> Pattern Double -> Pattern ValueMap octersubCountTo name ipat = innerJoin $ (\i -> pStateF "octersub" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat octersubbus :: Pattern Int -> Pattern Double -> ControlPattern octersubbus busid pat = (pF "octersub" pat) # (pI "^octersub" busid) octersubrecv :: Pattern Int -> ControlPattern octersubrecv busid = pI "^octersub" busid -- | octaver effect octersubsub :: Pattern Double -> ControlPattern octersubsub = pF "octersubsub" octersubsubTake :: String -> [Double] -> ControlPattern octersubsubTake name xs = pStateListF "octersubsub" name xs octersubsubCount :: String -> ControlPattern octersubsubCount name = pStateF "octersubsub" name (maybe 0 (+1)) octersubsubCountTo :: String -> Pattern Double -> Pattern ValueMap octersubsubCountTo name ipat = innerJoin $ (\i -> pStateF "octersubsub" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat octersubsubbus :: Pattern Int -> Pattern Double -> ControlPattern octersubsubbus busid pat = (pF "octersubsub" pat) # (pI "^octersubsub" busid) octersubsubrecv :: Pattern Int -> ControlPattern octersubsubrecv busid = pI "^octersubsub" busid -- | offset :: Pattern Double -> ControlPattern offset = pF "offset" offsetTake :: String -> [Double] -> ControlPattern offsetTake name xs = pStateListF "offset" name xs offsetCount :: String -> ControlPattern offsetCount name = pStateF "offset" name (maybe 0 (+1)) offsetCountTo :: String -> Pattern Double -> Pattern ValueMap offsetCountTo name ipat = innerJoin $ (\i -> pStateF "offset" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat offsetbus :: Pattern Int -> Pattern Double -> ControlPattern offsetbus _ _ = error $ "Control parameter 'offset' can't be sent to a bus." -- | ophatdecay :: Pattern Double -> ControlPattern ophatdecay = pF "ophatdecay" ophatdecayTake :: String -> [Double] -> ControlPattern ophatdecayTake name xs = pStateListF "ophatdecay" name xs ophatdecayCount :: String -> ControlPattern ophatdecayCount name = pStateF "ophatdecay" name (maybe 0 (+1)) ophatdecayCountTo :: String -> Pattern Double -> Pattern ValueMap ophatdecayCountTo name ipat = innerJoin $ (\i -> pStateF "ophatdecay" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat ophatdecaybus :: Pattern Int -> Pattern Double -> ControlPattern ophatdecaybus busid pat = (pF "ophatdecay" pat) # (pI "^ophatdecay" busid) ophatdecayrecv :: Pattern Int -> ControlPattern ophatdecayrecv busid = pI "^ophatdecay" busid -- | a pattern of numbers. An `orbit` is a global parameter context for patterns. Patterns with the same orbit will share hardware output bus offset and global effects, e.g. reverb and delay. The maximum number of orbits is specified in the superdirt startup, numbers higher than maximum will wrap around. orbit :: Pattern Int -> ControlPattern orbit = pI "orbit" orbitTake :: String -> [Double] -> ControlPattern orbitTake name xs = pStateListF "orbit" name xs orbitCount :: String -> ControlPattern orbitCount name = pStateF "orbit" name (maybe 0 (+1)) orbitCountTo :: String -> Pattern Double -> Pattern ValueMap orbitCountTo name ipat = innerJoin $ (\i -> pStateF "orbit" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat orbitbus :: Pattern Int -> Pattern Int -> ControlPattern orbitbus busid pat = (pI "orbit" pat) # (pI "^orbit" busid) orbitrecv :: Pattern Int -> ControlPattern orbitrecv busid = pI "^orbit" busid -- | overgain :: Pattern Double -> ControlPattern overgain = pF "overgain" overgainTake :: String -> [Double] -> ControlPattern overgainTake name xs = pStateListF "overgain" name xs overgainCount :: String -> ControlPattern overgainCount name = pStateF "overgain" name (maybe 0 (+1)) overgainCountTo :: String -> Pattern Double -> Pattern ValueMap overgainCountTo name ipat = innerJoin $ (\i -> pStateF "overgain" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat overgainbus :: Pattern Int -> Pattern Double -> ControlPattern overgainbus _ _ = error $ "Control parameter 'overgain' can't be sent to a bus." -- | overshape :: Pattern Double -> ControlPattern overshape = pF "overshape" overshapeTake :: String -> [Double] -> ControlPattern overshapeTake name xs = pStateListF "overshape" name xs overshapeCount :: String -> ControlPattern overshapeCount name = pStateF "overshape" name (maybe 0 (+1)) overshapeCountTo :: String -> Pattern Double -> Pattern ValueMap overshapeCountTo name ipat = innerJoin $ (\i -> pStateF "overshape" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat overshapebus :: Pattern Int -> Pattern Double -> ControlPattern overshapebus busid pat = (pF "overshape" pat) # (pI "^overshape" busid) overshaperecv :: Pattern Int -> ControlPattern overshaperecv busid = pI "^overshape" busid -- | a pattern of numbers between 0 and 1, from left to right (assuming stereo), once round a circle (assuming multichannel) pan :: Pattern Double -> ControlPattern pan = pF "pan" panTake :: String -> [Double] -> ControlPattern panTake name xs = pStateListF "pan" name xs panCount :: String -> ControlPattern panCount name = pStateF "pan" name (maybe 0 (+1)) panCountTo :: String -> Pattern Double -> Pattern ValueMap panCountTo name ipat = innerJoin $ (\i -> pStateF "pan" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat panbus :: Pattern Int -> Pattern Double -> ControlPattern panbus busid pat = (pF "pan" pat) # (pI "^pan" busid) panrecv :: Pattern Int -> ControlPattern panrecv busid = pI "^pan" busid -- | a pattern of numbers between -1.0 and 1.0, which controls the relative position of the centre pan in a pair of adjacent speakers (multichannel only) panorient :: Pattern Double -> ControlPattern panorient = pF "panorient" panorientTake :: String -> [Double] -> ControlPattern panorientTake name xs = pStateListF "panorient" name xs panorientCount :: String -> ControlPattern panorientCount name = pStateF "panorient" name (maybe 0 (+1)) panorientCountTo :: String -> Pattern Double -> Pattern ValueMap panorientCountTo name ipat = innerJoin $ (\i -> pStateF "panorient" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat panorientbus :: Pattern Int -> Pattern Double -> ControlPattern panorientbus busid pat = (pF "panorient" pat) # (pI "^panorient" busid) panorientrecv :: Pattern Int -> ControlPattern panorientrecv busid = pI "^panorient" busid -- | a pattern of numbers between -inf and inf, which controls how much multichannel output is fanned out (negative is backwards ordering) panspan :: Pattern Double -> ControlPattern panspan = pF "panspan" panspanTake :: String -> [Double] -> ControlPattern panspanTake name xs = pStateListF "panspan" name xs panspanCount :: String -> ControlPattern panspanCount name = pStateF "panspan" name (maybe 0 (+1)) panspanCountTo :: String -> Pattern Double -> Pattern ValueMap panspanCountTo name ipat = innerJoin $ (\i -> pStateF "panspan" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat panspanbus :: Pattern Int -> Pattern Double -> ControlPattern panspanbus busid pat = (pF "panspan" pat) # (pI "^panspan" busid) panspanrecv :: Pattern Int -> ControlPattern panspanrecv busid = pI "^panspan" busid -- | a pattern of numbers between 0.0 and 1.0, which controls the multichannel spread range (multichannel only) pansplay :: Pattern Double -> ControlPattern pansplay = pF "pansplay" pansplayTake :: String -> [Double] -> ControlPattern pansplayTake name xs = pStateListF "pansplay" name xs pansplayCount :: String -> ControlPattern pansplayCount name = pStateF "pansplay" name (maybe 0 (+1)) pansplayCountTo :: String -> Pattern Double -> Pattern ValueMap pansplayCountTo name ipat = innerJoin $ (\i -> pStateF "pansplay" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat pansplaybus :: Pattern Int -> Pattern Double -> ControlPattern pansplaybus busid pat = (pF "pansplay" pat) # (pI "^pansplay" busid) pansplayrecv :: Pattern Int -> ControlPattern pansplayrecv busid = pI "^pansplay" busid -- | a pattern of numbers between 0.0 and inf, which controls how much each channel is distributed over neighbours (multichannel only) panwidth :: Pattern Double -> ControlPattern panwidth = pF "panwidth" panwidthTake :: String -> [Double] -> ControlPattern panwidthTake name xs = pStateListF "panwidth" name xs panwidthCount :: String -> ControlPattern panwidthCount name = pStateF "panwidth" name (maybe 0 (+1)) panwidthCountTo :: String -> Pattern Double -> Pattern ValueMap panwidthCountTo name ipat = innerJoin $ (\i -> pStateF "panwidth" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat panwidthbus :: Pattern Int -> Pattern Double -> ControlPattern panwidthbus busid pat = (pF "panwidth" pat) # (pI "^panwidth" busid) panwidthrecv :: Pattern Int -> ControlPattern panwidthrecv busid = pI "^panwidth" busid -- | partials :: Pattern Double -> ControlPattern partials = pF "partials" partialsTake :: String -> [Double] -> ControlPattern partialsTake name xs = pStateListF "partials" name xs partialsCount :: String -> ControlPattern partialsCount name = pStateF "partials" name (maybe 0 (+1)) partialsCountTo :: String -> Pattern Double -> Pattern ValueMap partialsCountTo name ipat = innerJoin $ (\i -> pStateF "partials" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat partialsbus :: Pattern Int -> Pattern Double -> ControlPattern partialsbus busid pat = (pF "partials" pat) # (pI "^partials" busid) partialsrecv :: Pattern Int -> ControlPattern partialsrecv busid = pI "^partials" busid -- | Phaser Audio DSP effect | params are 'phaserrate' and 'phaserdepth' phaserdepth :: Pattern Double -> ControlPattern phaserdepth = pF "phaserdepth" phaserdepthTake :: String -> [Double] -> ControlPattern phaserdepthTake name xs = pStateListF "phaserdepth" name xs phaserdepthCount :: String -> ControlPattern phaserdepthCount name = pStateF "phaserdepth" name (maybe 0 (+1)) phaserdepthCountTo :: String -> Pattern Double -> Pattern ValueMap phaserdepthCountTo name ipat = innerJoin $ (\i -> pStateF "phaserdepth" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat phaserdepthbus :: Pattern Int -> Pattern Double -> ControlPattern phaserdepthbus busid pat = (pF "phaserdepth" pat) # (pI "^phaserdepth" busid) phaserdepthrecv :: Pattern Int -> ControlPattern phaserdepthrecv busid = pI "^phaserdepth" busid -- | Phaser Audio DSP effect | params are 'phaserrate' and 'phaserdepth' phaserrate :: Pattern Double -> ControlPattern phaserrate = pF "phaserrate" phaserrateTake :: String -> [Double] -> ControlPattern phaserrateTake name xs = pStateListF "phaserrate" name xs phaserrateCount :: String -> ControlPattern phaserrateCount name = pStateF "phaserrate" name (maybe 0 (+1)) phaserrateCountTo :: String -> Pattern Double -> Pattern ValueMap phaserrateCountTo name ipat = innerJoin $ (\i -> pStateF "phaserrate" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat phaserratebus :: Pattern Int -> Pattern Double -> ControlPattern phaserratebus busid pat = (pF "phaserrate" pat) # (pI "^phaserrate" busid) phaserraterecv :: Pattern Int -> ControlPattern phaserraterecv busid = pI "^phaserrate" busid -- | pitch1 :: Pattern Double -> ControlPattern pitch1 = pF "pitch1" pitch1Take :: String -> [Double] -> ControlPattern pitch1Take name xs = pStateListF "pitch1" name xs pitch1Count :: String -> ControlPattern pitch1Count name = pStateF "pitch1" name (maybe 0 (+1)) pitch1CountTo :: String -> Pattern Double -> Pattern ValueMap pitch1CountTo name ipat = innerJoin $ (\i -> pStateF "pitch1" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat pitch1bus :: Pattern Int -> Pattern Double -> ControlPattern pitch1bus busid pat = (pF "pitch1" pat) # (pI "^pitch1" busid) pitch1recv :: Pattern Int -> ControlPattern pitch1recv busid = pI "^pitch1" busid -- | pitch2 :: Pattern Double -> ControlPattern pitch2 = pF "pitch2" pitch2Take :: String -> [Double] -> ControlPattern pitch2Take name xs = pStateListF "pitch2" name xs pitch2Count :: String -> ControlPattern pitch2Count name = pStateF "pitch2" name (maybe 0 (+1)) pitch2CountTo :: String -> Pattern Double -> Pattern ValueMap pitch2CountTo name ipat = innerJoin $ (\i -> pStateF "pitch2" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat pitch2bus :: Pattern Int -> Pattern Double -> ControlPattern pitch2bus busid pat = (pF "pitch2" pat) # (pI "^pitch2" busid) pitch2recv :: Pattern Int -> ControlPattern pitch2recv busid = pI "^pitch2" busid -- | pitch3 :: Pattern Double -> ControlPattern pitch3 = pF "pitch3" pitch3Take :: String -> [Double] -> ControlPattern pitch3Take name xs = pStateListF "pitch3" name xs pitch3Count :: String -> ControlPattern pitch3Count name = pStateF "pitch3" name (maybe 0 (+1)) pitch3CountTo :: String -> Pattern Double -> Pattern ValueMap pitch3CountTo name ipat = innerJoin $ (\i -> pStateF "pitch3" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat pitch3bus :: Pattern Int -> Pattern Double -> ControlPattern pitch3bus busid pat = (pF "pitch3" pat) # (pI "^pitch3" busid) pitch3recv :: Pattern Int -> ControlPattern pitch3recv busid = pI "^pitch3" busid -- | polyTouch :: Pattern Double -> ControlPattern polyTouch = pF "polyTouch" polyTouchTake :: String -> [Double] -> ControlPattern polyTouchTake name xs = pStateListF "polyTouch" name xs polyTouchCount :: String -> ControlPattern polyTouchCount name = pStateF "polyTouch" name (maybe 0 (+1)) polyTouchCountTo :: String -> Pattern Double -> Pattern ValueMap polyTouchCountTo name ipat = innerJoin $ (\i -> pStateF "polyTouch" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat polyTouchbus :: Pattern Int -> Pattern Double -> ControlPattern polyTouchbus _ _ = error $ "Control parameter 'polyTouch' can't be sent to a bus." -- | portamento :: Pattern Double -> ControlPattern portamento = pF "portamento" portamentoTake :: String -> [Double] -> ControlPattern portamentoTake name xs = pStateListF "portamento" name xs portamentoCount :: String -> ControlPattern portamentoCount name = pStateF "portamento" name (maybe 0 (+1)) portamentoCountTo :: String -> Pattern Double -> Pattern ValueMap portamentoCountTo name ipat = innerJoin $ (\i -> pStateF "portamento" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat portamentobus :: Pattern Int -> Pattern Double -> ControlPattern portamentobus busid pat = (pF "portamento" pat) # (pI "^portamento" busid) portamentorecv :: Pattern Int -> ControlPattern portamentorecv busid = pI "^portamento" busid -- | progNum :: Pattern Double -> ControlPattern progNum = pF "progNum" progNumTake :: String -> [Double] -> ControlPattern progNumTake name xs = pStateListF "progNum" name xs progNumCount :: String -> ControlPattern progNumCount name = pStateF "progNum" name (maybe 0 (+1)) progNumCountTo :: String -> Pattern Double -> Pattern ValueMap progNumCountTo name ipat = innerJoin $ (\i -> pStateF "progNum" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat progNumbus :: Pattern Int -> Pattern Double -> ControlPattern progNumbus _ _ = error $ "Control parameter 'progNum' can't be sent to a bus." -- | used in SuperDirt softsynths as a control rate or 'speed' rate :: Pattern Double -> ControlPattern rate = pF "rate" rateTake :: String -> [Double] -> ControlPattern rateTake name xs = pStateListF "rate" name xs rateCount :: String -> ControlPattern rateCount name = pStateF "rate" name (maybe 0 (+1)) rateCountTo :: String -> Pattern Double -> Pattern ValueMap rateCountTo name ipat = innerJoin $ (\i -> pStateF "rate" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat ratebus :: Pattern Int -> Pattern Double -> ControlPattern ratebus busid pat = (pF "rate" pat) # (pI "^rate" busid) raterecv :: Pattern Int -> ControlPattern raterecv busid = pI "^rate" busid -- | Spectral conform real :: Pattern Double -> ControlPattern real = pF "real" realTake :: String -> [Double] -> ControlPattern realTake name xs = pStateListF "real" name xs realCount :: String -> ControlPattern realCount name = pStateF "real" name (maybe 0 (+1)) realCountTo :: String -> Pattern Double -> Pattern ValueMap realCountTo name ipat = innerJoin $ (\i -> pStateF "real" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat realbus :: Pattern Int -> Pattern Double -> ControlPattern realbus busid pat = (pF "real" pat) # (pI "^real" busid) realrecv :: Pattern Int -> ControlPattern realrecv busid = pI "^real" busid -- | a pattern of numbers to specify the release time (in seconds) of an envelope applied to each sample. release :: Pattern Double -> ControlPattern release = pF "release" releaseTake :: String -> [Double] -> ControlPattern releaseTake name xs = pStateListF "release" name xs releaseCount :: String -> ControlPattern releaseCount name = pStateF "release" name (maybe 0 (+1)) releaseCountTo :: String -> Pattern Double -> Pattern ValueMap releaseCountTo name ipat = innerJoin $ (\i -> pStateF "release" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat releasebus :: Pattern Int -> Pattern Double -> ControlPattern releasebus busid pat = (pF "release" pat) # (pI "^release" busid) releaserecv :: Pattern Int -> ControlPattern releaserecv busid = pI "^release" busid -- | a pattern of numbers from 0 to 1. Specifies the resonance of the low-pass filter. resonance :: Pattern Double -> ControlPattern resonance = pF "resonance" resonanceTake :: String -> [Double] -> ControlPattern resonanceTake name xs = pStateListF "resonance" name xs resonanceCount :: String -> ControlPattern resonanceCount name = pStateF "resonance" name (maybe 0 (+1)) resonanceCountTo :: String -> Pattern Double -> Pattern ValueMap resonanceCountTo name ipat = innerJoin $ (\i -> pStateF "resonance" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat resonancebus :: Pattern Int -> Pattern Double -> ControlPattern resonancebus busid pat = (pF "resonance" pat) # (pI "^resonance" busid) resonancerecv :: Pattern Int -> ControlPattern resonancerecv busid = pI "^resonance" busid -- | ring modulation ring :: Pattern Double -> ControlPattern ring = pF "ring" ringTake :: String -> [Double] -> ControlPattern ringTake name xs = pStateListF "ring" name xs ringCount :: String -> ControlPattern ringCount name = pStateF "ring" name (maybe 0 (+1)) ringCountTo :: String -> Pattern Double -> Pattern ValueMap ringCountTo name ipat = innerJoin $ (\i -> pStateF "ring" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat ringbus :: Pattern Int -> Pattern Double -> ControlPattern ringbus busid pat = (pF "ring" pat) # (pI "^ring" busid) ringrecv :: Pattern Int -> ControlPattern ringrecv busid = pI "^ring" busid -- | ring modulation ringdf :: Pattern Double -> ControlPattern ringdf = pF "ringdf" ringdfTake :: String -> [Double] -> ControlPattern ringdfTake name xs = pStateListF "ringdf" name xs ringdfCount :: String -> ControlPattern ringdfCount name = pStateF "ringdf" name (maybe 0 (+1)) ringdfCountTo :: String -> Pattern Double -> Pattern ValueMap ringdfCountTo name ipat = innerJoin $ (\i -> pStateF "ringdf" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat ringdfbus :: Pattern Int -> Pattern Double -> ControlPattern ringdfbus busid pat = (pF "ringdf" pat) # (pI "^ringdf" busid) ringdfrecv :: Pattern Int -> ControlPattern ringdfrecv busid = pI "^ringdf" busid -- | ring modulation ringf :: Pattern Double -> ControlPattern ringf = pF "ringf" ringfTake :: String -> [Double] -> ControlPattern ringfTake name xs = pStateListF "ringf" name xs ringfCount :: String -> ControlPattern ringfCount name = pStateF "ringf" name (maybe 0 (+1)) ringfCountTo :: String -> Pattern Double -> Pattern ValueMap ringfCountTo name ipat = innerJoin $ (\i -> pStateF "ringf" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat ringfbus :: Pattern Int -> Pattern Double -> ControlPattern ringfbus busid pat = (pF "ringf" pat) # (pI "^ringf" busid) ringfrecv :: Pattern Int -> ControlPattern ringfrecv busid = pI "^ringf" busid -- | a pattern of numbers from 0 to 1. Sets the level of reverb. room :: Pattern Double -> ControlPattern room = pF "room" roomTake :: String -> [Double] -> ControlPattern roomTake name xs = pStateListF "room" name xs roomCount :: String -> ControlPattern roomCount name = pStateF "room" name (maybe 0 (+1)) roomCountTo :: String -> Pattern Double -> Pattern ValueMap roomCountTo name ipat = innerJoin $ (\i -> pStateF "room" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat roombus :: Pattern Int -> Pattern Double -> ControlPattern roombus busid pat = (pF "room" pat) # (pI "^room" busid) roomrecv :: Pattern Int -> ControlPattern roomrecv busid = pI "^room" busid -- | sagogo :: Pattern Double -> ControlPattern sagogo = pF "sagogo" sagogoTake :: String -> [Double] -> ControlPattern sagogoTake name xs = pStateListF "sagogo" name xs sagogoCount :: String -> ControlPattern sagogoCount name = pStateF "sagogo" name (maybe 0 (+1)) sagogoCountTo :: String -> Pattern Double -> Pattern ValueMap sagogoCountTo name ipat = innerJoin $ (\i -> pStateF "sagogo" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat sagogobus :: Pattern Int -> Pattern Double -> ControlPattern sagogobus busid pat = (pF "sagogo" pat) # (pI "^sagogo" busid) sagogorecv :: Pattern Int -> ControlPattern sagogorecv busid = pI "^sagogo" busid -- | sclap :: Pattern Double -> ControlPattern sclap = pF "sclap" sclapTake :: String -> [Double] -> ControlPattern sclapTake name xs = pStateListF "sclap" name xs sclapCount :: String -> ControlPattern sclapCount name = pStateF "sclap" name (maybe 0 (+1)) sclapCountTo :: String -> Pattern Double -> Pattern ValueMap sclapCountTo name ipat = innerJoin $ (\i -> pStateF "sclap" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat sclapbus :: Pattern Int -> Pattern Double -> ControlPattern sclapbus busid pat = (pF "sclap" pat) # (pI "^sclap" busid) sclaprecv :: Pattern Int -> ControlPattern sclaprecv busid = pI "^sclap" busid -- | sclaves :: Pattern Double -> ControlPattern sclaves = pF "sclaves" sclavesTake :: String -> [Double] -> ControlPattern sclavesTake name xs = pStateListF "sclaves" name xs sclavesCount :: String -> ControlPattern sclavesCount name = pStateF "sclaves" name (maybe 0 (+1)) sclavesCountTo :: String -> Pattern Double -> Pattern ValueMap sclavesCountTo name ipat = innerJoin $ (\i -> pStateF "sclaves" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat sclavesbus :: Pattern Int -> Pattern Double -> ControlPattern sclavesbus busid pat = (pF "sclaves" pat) # (pI "^sclaves" busid) sclavesrecv :: Pattern Int -> ControlPattern sclavesrecv busid = pI "^sclaves" busid -- | Spectral scramble scram :: Pattern Double -> ControlPattern scram = pF "scram" scramTake :: String -> [Double] -> ControlPattern scramTake name xs = pStateListF "scram" name xs scramCount :: String -> ControlPattern scramCount name = pStateF "scram" name (maybe 0 (+1)) scramCountTo :: String -> Pattern Double -> Pattern ValueMap scramCountTo name ipat = innerJoin $ (\i -> pStateF "scram" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat scrambus :: Pattern Int -> Pattern Double -> ControlPattern scrambus busid pat = (pF "scram" pat) # (pI "^scram" busid) scramrecv :: Pattern Int -> ControlPattern scramrecv busid = pI "^scram" busid -- | scrash :: Pattern Double -> ControlPattern scrash = pF "scrash" scrashTake :: String -> [Double] -> ControlPattern scrashTake name xs = pStateListF "scrash" name xs scrashCount :: String -> ControlPattern scrashCount name = pStateF "scrash" name (maybe 0 (+1)) scrashCountTo :: String -> Pattern Double -> Pattern ValueMap scrashCountTo name ipat = innerJoin $ (\i -> pStateF "scrash" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat scrashbus :: Pattern Int -> Pattern Double -> ControlPattern scrashbus busid pat = (pF "scrash" pat) # (pI "^scrash" busid) scrashrecv :: Pattern Int -> ControlPattern scrashrecv busid = pI "^scrash" busid -- | seconds :: Pattern Double -> ControlPattern seconds = pF "seconds" secondsTake :: String -> [Double] -> ControlPattern secondsTake name xs = pStateListF "seconds" name xs secondsCount :: String -> ControlPattern secondsCount name = pStateF "seconds" name (maybe 0 (+1)) secondsCountTo :: String -> Pattern Double -> Pattern ValueMap secondsCountTo name ipat = innerJoin $ (\i -> pStateF "seconds" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat secondsbus :: Pattern Int -> Pattern Double -> ControlPattern secondsbus _ _ = error $ "Control parameter 'seconds' can't be sent to a bus." -- | semitone :: Pattern Double -> ControlPattern semitone = pF "semitone" semitoneTake :: String -> [Double] -> ControlPattern semitoneTake name xs = pStateListF "semitone" name xs semitoneCount :: String -> ControlPattern semitoneCount name = pStateF "semitone" name (maybe 0 (+1)) semitoneCountTo :: String -> Pattern Double -> Pattern ValueMap semitoneCountTo name ipat = innerJoin $ (\i -> pStateF "semitone" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat semitonebus :: Pattern Int -> Pattern Double -> ControlPattern semitonebus busid pat = (pF "semitone" pat) # (pI "^semitone" busid) semitonerecv :: Pattern Int -> ControlPattern semitonerecv busid = pI "^semitone" busid -- | wave shaping distortion, a pattern of numbers from 0 for no distortion up to 1 for loads of distortion. shape :: Pattern Double -> ControlPattern shape = pF "shape" shapeTake :: String -> [Double] -> ControlPattern shapeTake name xs = pStateListF "shape" name xs shapeCount :: String -> ControlPattern shapeCount name = pStateF "shape" name (maybe 0 (+1)) shapeCountTo :: String -> Pattern Double -> Pattern ValueMap shapeCountTo name ipat = innerJoin $ (\i -> pStateF "shape" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat shapebus :: Pattern Int -> Pattern Double -> ControlPattern shapebus busid pat = (pF "shape" pat) # (pI "^shape" busid) shaperecv :: Pattern Int -> ControlPattern shaperecv busid = pI "^shape" busid -- | a pattern of numbers from 0 to 1. Sets the perceptual size (reverb time) of the `room` to be used in reverb. size :: Pattern Double -> ControlPattern size = pF "size" sizeTake :: String -> [Double] -> ControlPattern sizeTake name xs = pStateListF "size" name xs sizeCount :: String -> ControlPattern sizeCount name = pStateF "size" name (maybe 0 (+1)) sizeCountTo :: String -> Pattern Double -> Pattern ValueMap sizeCountTo name ipat = innerJoin $ (\i -> pStateF "size" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat sizebus :: Pattern Int -> Pattern Double -> ControlPattern sizebus busid pat = (pF "size" pat) # (pI "^size" busid) sizerecv :: Pattern Int -> ControlPattern sizerecv busid = pI "^size" busid -- | slide :: Pattern Double -> ControlPattern slide = pF "slide" slideTake :: String -> [Double] -> ControlPattern slideTake name xs = pStateListF "slide" name xs slideCount :: String -> ControlPattern slideCount name = pStateF "slide" name (maybe 0 (+1)) slideCountTo :: String -> Pattern Double -> Pattern ValueMap slideCountTo name ipat = innerJoin $ (\i -> pStateF "slide" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slidebus :: Pattern Int -> Pattern Double -> ControlPattern slidebus busid pat = (pF "slide" pat) # (pI "^slide" busid) sliderecv :: Pattern Int -> ControlPattern sliderecv busid = pI "^slide" busid -- | slider0 :: Pattern Double -> ControlPattern slider0 = pF "slider0" slider0Take :: String -> [Double] -> ControlPattern slider0Take name xs = pStateListF "slider0" name xs slider0Count :: String -> ControlPattern slider0Count name = pStateF "slider0" name (maybe 0 (+1)) slider0CountTo :: String -> Pattern Double -> Pattern ValueMap slider0CountTo name ipat = innerJoin $ (\i -> pStateF "slider0" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider0bus :: Pattern Int -> Pattern Double -> ControlPattern slider0bus busid pat = (pF "slider0" pat) # (pI "^slider0" busid) slider0recv :: Pattern Int -> ControlPattern slider0recv busid = pI "^slider0" busid -- | slider1 :: Pattern Double -> ControlPattern slider1 = pF "slider1" slider1Take :: String -> [Double] -> ControlPattern slider1Take name xs = pStateListF "slider1" name xs slider1Count :: String -> ControlPattern slider1Count name = pStateF "slider1" name (maybe 0 (+1)) slider1CountTo :: String -> Pattern Double -> Pattern ValueMap slider1CountTo name ipat = innerJoin $ (\i -> pStateF "slider1" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider1bus :: Pattern Int -> Pattern Double -> ControlPattern slider1bus busid pat = (pF "slider1" pat) # (pI "^slider1" busid) slider1recv :: Pattern Int -> ControlPattern slider1recv busid = pI "^slider1" busid -- | slider10 :: Pattern Double -> ControlPattern slider10 = pF "slider10" slider10Take :: String -> [Double] -> ControlPattern slider10Take name xs = pStateListF "slider10" name xs slider10Count :: String -> ControlPattern slider10Count name = pStateF "slider10" name (maybe 0 (+1)) slider10CountTo :: String -> Pattern Double -> Pattern ValueMap slider10CountTo name ipat = innerJoin $ (\i -> pStateF "slider10" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider10bus :: Pattern Int -> Pattern Double -> ControlPattern slider10bus busid pat = (pF "slider10" pat) # (pI "^slider10" busid) slider10recv :: Pattern Int -> ControlPattern slider10recv busid = pI "^slider10" busid -- | slider11 :: Pattern Double -> ControlPattern slider11 = pF "slider11" slider11Take :: String -> [Double] -> ControlPattern slider11Take name xs = pStateListF "slider11" name xs slider11Count :: String -> ControlPattern slider11Count name = pStateF "slider11" name (maybe 0 (+1)) slider11CountTo :: String -> Pattern Double -> Pattern ValueMap slider11CountTo name ipat = innerJoin $ (\i -> pStateF "slider11" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider11bus :: Pattern Int -> Pattern Double -> ControlPattern slider11bus busid pat = (pF "slider11" pat) # (pI "^slider11" busid) slider11recv :: Pattern Int -> ControlPattern slider11recv busid = pI "^slider11" busid -- | slider12 :: Pattern Double -> ControlPattern slider12 = pF "slider12" slider12Take :: String -> [Double] -> ControlPattern slider12Take name xs = pStateListF "slider12" name xs slider12Count :: String -> ControlPattern slider12Count name = pStateF "slider12" name (maybe 0 (+1)) slider12CountTo :: String -> Pattern Double -> Pattern ValueMap slider12CountTo name ipat = innerJoin $ (\i -> pStateF "slider12" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider12bus :: Pattern Int -> Pattern Double -> ControlPattern slider12bus busid pat = (pF "slider12" pat) # (pI "^slider12" busid) slider12recv :: Pattern Int -> ControlPattern slider12recv busid = pI "^slider12" busid -- | slider13 :: Pattern Double -> ControlPattern slider13 = pF "slider13" slider13Take :: String -> [Double] -> ControlPattern slider13Take name xs = pStateListF "slider13" name xs slider13Count :: String -> ControlPattern slider13Count name = pStateF "slider13" name (maybe 0 (+1)) slider13CountTo :: String -> Pattern Double -> Pattern ValueMap slider13CountTo name ipat = innerJoin $ (\i -> pStateF "slider13" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider13bus :: Pattern Int -> Pattern Double -> ControlPattern slider13bus busid pat = (pF "slider13" pat) # (pI "^slider13" busid) slider13recv :: Pattern Int -> ControlPattern slider13recv busid = pI "^slider13" busid -- | slider14 :: Pattern Double -> ControlPattern slider14 = pF "slider14" slider14Take :: String -> [Double] -> ControlPattern slider14Take name xs = pStateListF "slider14" name xs slider14Count :: String -> ControlPattern slider14Count name = pStateF "slider14" name (maybe 0 (+1)) slider14CountTo :: String -> Pattern Double -> Pattern ValueMap slider14CountTo name ipat = innerJoin $ (\i -> pStateF "slider14" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider14bus :: Pattern Int -> Pattern Double -> ControlPattern slider14bus busid pat = (pF "slider14" pat) # (pI "^slider14" busid) slider14recv :: Pattern Int -> ControlPattern slider14recv busid = pI "^slider14" busid -- | slider15 :: Pattern Double -> ControlPattern slider15 = pF "slider15" slider15Take :: String -> [Double] -> ControlPattern slider15Take name xs = pStateListF "slider15" name xs slider15Count :: String -> ControlPattern slider15Count name = pStateF "slider15" name (maybe 0 (+1)) slider15CountTo :: String -> Pattern Double -> Pattern ValueMap slider15CountTo name ipat = innerJoin $ (\i -> pStateF "slider15" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider15bus :: Pattern Int -> Pattern Double -> ControlPattern slider15bus busid pat = (pF "slider15" pat) # (pI "^slider15" busid) slider15recv :: Pattern Int -> ControlPattern slider15recv busid = pI "^slider15" busid -- | slider2 :: Pattern Double -> ControlPattern slider2 = pF "slider2" slider2Take :: String -> [Double] -> ControlPattern slider2Take name xs = pStateListF "slider2" name xs slider2Count :: String -> ControlPattern slider2Count name = pStateF "slider2" name (maybe 0 (+1)) slider2CountTo :: String -> Pattern Double -> Pattern ValueMap slider2CountTo name ipat = innerJoin $ (\i -> pStateF "slider2" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider2bus :: Pattern Int -> Pattern Double -> ControlPattern slider2bus busid pat = (pF "slider2" pat) # (pI "^slider2" busid) slider2recv :: Pattern Int -> ControlPattern slider2recv busid = pI "^slider2" busid -- | slider3 :: Pattern Double -> ControlPattern slider3 = pF "slider3" slider3Take :: String -> [Double] -> ControlPattern slider3Take name xs = pStateListF "slider3" name xs slider3Count :: String -> ControlPattern slider3Count name = pStateF "slider3" name (maybe 0 (+1)) slider3CountTo :: String -> Pattern Double -> Pattern ValueMap slider3CountTo name ipat = innerJoin $ (\i -> pStateF "slider3" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider3bus :: Pattern Int -> Pattern Double -> ControlPattern slider3bus busid pat = (pF "slider3" pat) # (pI "^slider3" busid) slider3recv :: Pattern Int -> ControlPattern slider3recv busid = pI "^slider3" busid -- | slider4 :: Pattern Double -> ControlPattern slider4 = pF "slider4" slider4Take :: String -> [Double] -> ControlPattern slider4Take name xs = pStateListF "slider4" name xs slider4Count :: String -> ControlPattern slider4Count name = pStateF "slider4" name (maybe 0 (+1)) slider4CountTo :: String -> Pattern Double -> Pattern ValueMap slider4CountTo name ipat = innerJoin $ (\i -> pStateF "slider4" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider4bus :: Pattern Int -> Pattern Double -> ControlPattern slider4bus busid pat = (pF "slider4" pat) # (pI "^slider4" busid) slider4recv :: Pattern Int -> ControlPattern slider4recv busid = pI "^slider4" busid -- | slider5 :: Pattern Double -> ControlPattern slider5 = pF "slider5" slider5Take :: String -> [Double] -> ControlPattern slider5Take name xs = pStateListF "slider5" name xs slider5Count :: String -> ControlPattern slider5Count name = pStateF "slider5" name (maybe 0 (+1)) slider5CountTo :: String -> Pattern Double -> Pattern ValueMap slider5CountTo name ipat = innerJoin $ (\i -> pStateF "slider5" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider5bus :: Pattern Int -> Pattern Double -> ControlPattern slider5bus busid pat = (pF "slider5" pat) # (pI "^slider5" busid) slider5recv :: Pattern Int -> ControlPattern slider5recv busid = pI "^slider5" busid -- | slider6 :: Pattern Double -> ControlPattern slider6 = pF "slider6" slider6Take :: String -> [Double] -> ControlPattern slider6Take name xs = pStateListF "slider6" name xs slider6Count :: String -> ControlPattern slider6Count name = pStateF "slider6" name (maybe 0 (+1)) slider6CountTo :: String -> Pattern Double -> Pattern ValueMap slider6CountTo name ipat = innerJoin $ (\i -> pStateF "slider6" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider6bus :: Pattern Int -> Pattern Double -> ControlPattern slider6bus busid pat = (pF "slider6" pat) # (pI "^slider6" busid) slider6recv :: Pattern Int -> ControlPattern slider6recv busid = pI "^slider6" busid -- | slider7 :: Pattern Double -> ControlPattern slider7 = pF "slider7" slider7Take :: String -> [Double] -> ControlPattern slider7Take name xs = pStateListF "slider7" name xs slider7Count :: String -> ControlPattern slider7Count name = pStateF "slider7" name (maybe 0 (+1)) slider7CountTo :: String -> Pattern Double -> Pattern ValueMap slider7CountTo name ipat = innerJoin $ (\i -> pStateF "slider7" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider7bus :: Pattern Int -> Pattern Double -> ControlPattern slider7bus busid pat = (pF "slider7" pat) # (pI "^slider7" busid) slider7recv :: Pattern Int -> ControlPattern slider7recv busid = pI "^slider7" busid -- | slider8 :: Pattern Double -> ControlPattern slider8 = pF "slider8" slider8Take :: String -> [Double] -> ControlPattern slider8Take name xs = pStateListF "slider8" name xs slider8Count :: String -> ControlPattern slider8Count name = pStateF "slider8" name (maybe 0 (+1)) slider8CountTo :: String -> Pattern Double -> Pattern ValueMap slider8CountTo name ipat = innerJoin $ (\i -> pStateF "slider8" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider8bus :: Pattern Int -> Pattern Double -> ControlPattern slider8bus busid pat = (pF "slider8" pat) # (pI "^slider8" busid) slider8recv :: Pattern Int -> ControlPattern slider8recv busid = pI "^slider8" busid -- | slider9 :: Pattern Double -> ControlPattern slider9 = pF "slider9" slider9Take :: String -> [Double] -> ControlPattern slider9Take name xs = pStateListF "slider9" name xs slider9Count :: String -> ControlPattern slider9Count name = pStateF "slider9" name (maybe 0 (+1)) slider9CountTo :: String -> Pattern Double -> Pattern ValueMap slider9CountTo name ipat = innerJoin $ (\i -> pStateF "slider9" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat slider9bus :: Pattern Int -> Pattern Double -> ControlPattern slider9bus busid pat = (pF "slider9" pat) # (pI "^slider9" busid) slider9recv :: Pattern Int -> ControlPattern slider9recv busid = pI "^slider9" busid -- | Spectral smear smear :: Pattern Double -> ControlPattern smear = pF "smear" smearTake :: String -> [Double] -> ControlPattern smearTake name xs = pStateListF "smear" name xs smearCount :: String -> ControlPattern smearCount name = pStateF "smear" name (maybe 0 (+1)) smearCountTo :: String -> Pattern Double -> Pattern ValueMap smearCountTo name ipat = innerJoin $ (\i -> pStateF "smear" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat smearbus :: Pattern Int -> Pattern Double -> ControlPattern smearbus busid pat = (pF "smear" pat) # (pI "^smear" busid) smearrecv :: Pattern Int -> ControlPattern smearrecv busid = pI "^smear" busid -- | songPtr :: Pattern Double -> ControlPattern songPtr = pF "songPtr" songPtrTake :: String -> [Double] -> ControlPattern songPtrTake name xs = pStateListF "songPtr" name xs songPtrCount :: String -> ControlPattern songPtrCount name = pStateF "songPtr" name (maybe 0 (+1)) songPtrCountTo :: String -> Pattern Double -> Pattern ValueMap songPtrCountTo name ipat = innerJoin $ (\i -> pStateF "songPtr" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat songPtrbus :: Pattern Int -> Pattern Double -> ControlPattern songPtrbus _ _ = error $ "Control parameter 'songPtr' can't be sent to a bus." -- | a pattern of numbers which changes the speed of sample playback, i.e. a cheap way of changing pitch. Negative values will play the sample backwards! speed :: Pattern Double -> ControlPattern speed = pF "speed" speedTake :: String -> [Double] -> ControlPattern speedTake name xs = pStateListF "speed" name xs speedCount :: String -> ControlPattern speedCount name = pStateF "speed" name (maybe 0 (+1)) speedCountTo :: String -> Pattern Double -> Pattern ValueMap speedCountTo name ipat = innerJoin $ (\i -> pStateF "speed" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat speedbus :: Pattern Int -> Pattern Double -> ControlPattern speedbus _ _ = error $ "Control parameter 'speed' can't be sent to a bus." -- | squiz :: Pattern Double -> ControlPattern squiz = pF "squiz" squizTake :: String -> [Double] -> ControlPattern squizTake name xs = pStateListF "squiz" name xs squizCount :: String -> ControlPattern squizCount name = pStateF "squiz" name (maybe 0 (+1)) squizCountTo :: String -> Pattern Double -> Pattern ValueMap squizCountTo name ipat = innerJoin $ (\i -> pStateF "squiz" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat squizbus :: Pattern Int -> Pattern Double -> ControlPattern squizbus busid pat = (pF "squiz" pat) # (pI "^squiz" busid) squizrecv :: Pattern Int -> ControlPattern squizrecv busid = pI "^squiz" busid -- | stepsPerOctave :: Pattern Double -> ControlPattern stepsPerOctave = pF "stepsPerOctave" stepsPerOctaveTake :: String -> [Double] -> ControlPattern stepsPerOctaveTake name xs = pStateListF "stepsPerOctave" name xs stepsPerOctaveCount :: String -> ControlPattern stepsPerOctaveCount name = pStateF "stepsPerOctave" name (maybe 0 (+1)) stepsPerOctaveCountTo :: String -> Pattern Double -> Pattern ValueMap stepsPerOctaveCountTo name ipat = innerJoin $ (\i -> pStateF "stepsPerOctave" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat stepsPerOctavebus :: Pattern Int -> Pattern Double -> ControlPattern stepsPerOctavebus busid pat = (pF "stepsPerOctave" pat) # (pI "^stepsPerOctave" busid) stepsPerOctaverecv :: Pattern Int -> ControlPattern stepsPerOctaverecv busid = pI "^stepsPerOctave" busid -- | stutterdepth :: Pattern Double -> ControlPattern stutterdepth = pF "stutterdepth" stutterdepthTake :: String -> [Double] -> ControlPattern stutterdepthTake name xs = pStateListF "stutterdepth" name xs stutterdepthCount :: String -> ControlPattern stutterdepthCount name = pStateF "stutterdepth" name (maybe 0 (+1)) stutterdepthCountTo :: String -> Pattern Double -> Pattern ValueMap stutterdepthCountTo name ipat = innerJoin $ (\i -> pStateF "stutterdepth" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat stutterdepthbus :: Pattern Int -> Pattern Double -> ControlPattern stutterdepthbus busid pat = (pF "stutterdepth" pat) # (pI "^stutterdepth" busid) stutterdepthrecv :: Pattern Int -> ControlPattern stutterdepthrecv busid = pI "^stutterdepth" busid -- | stuttertime :: Pattern Double -> ControlPattern stuttertime = pF "stuttertime" stuttertimeTake :: String -> [Double] -> ControlPattern stuttertimeTake name xs = pStateListF "stuttertime" name xs stuttertimeCount :: String -> ControlPattern stuttertimeCount name = pStateF "stuttertime" name (maybe 0 (+1)) stuttertimeCountTo :: String -> Pattern Double -> Pattern ValueMap stuttertimeCountTo name ipat = innerJoin $ (\i -> pStateF "stuttertime" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat stuttertimebus :: Pattern Int -> Pattern Double -> ControlPattern stuttertimebus busid pat = (pF "stuttertime" pat) # (pI "^stuttertime" busid) stuttertimerecv :: Pattern Int -> ControlPattern stuttertimerecv busid = pI "^stuttertime" busid -- | sustain :: Pattern Double -> ControlPattern sustain = pF "sustain" sustainTake :: String -> [Double] -> ControlPattern sustainTake name xs = pStateListF "sustain" name xs sustainCount :: String -> ControlPattern sustainCount name = pStateF "sustain" name (maybe 0 (+1)) sustainCountTo :: String -> Pattern Double -> Pattern ValueMap sustainCountTo name ipat = innerJoin $ (\i -> pStateF "sustain" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat sustainbus :: Pattern Int -> Pattern Double -> ControlPattern sustainbus _ _ = error $ "Control parameter 'sustain' can't be sent to a bus." -- | sustainpedal :: Pattern Double -> ControlPattern sustainpedal = pF "sustainpedal" sustainpedalTake :: String -> [Double] -> ControlPattern sustainpedalTake name xs = pStateListF "sustainpedal" name xs sustainpedalCount :: String -> ControlPattern sustainpedalCount name = pStateF "sustainpedal" name (maybe 0 (+1)) sustainpedalCountTo :: String -> Pattern Double -> Pattern ValueMap sustainpedalCountTo name ipat = innerJoin $ (\i -> pStateF "sustainpedal" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat sustainpedalbus :: Pattern Int -> Pattern Double -> ControlPattern sustainpedalbus busid pat = (pF "sustainpedal" pat) # (pI "^sustainpedal" busid) sustainpedalrecv :: Pattern Int -> ControlPattern sustainpedalrecv busid = pI "^sustainpedal" busid -- | time stretch amount timescale :: Pattern Double -> ControlPattern timescale = pF "timescale" timescaleTake :: String -> [Double] -> ControlPattern timescaleTake name xs = pStateListF "timescale" name xs timescaleCount :: String -> ControlPattern timescaleCount name = pStateF "timescale" name (maybe 0 (+1)) timescaleCountTo :: String -> Pattern Double -> Pattern ValueMap timescaleCountTo name ipat = innerJoin $ (\i -> pStateF "timescale" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat timescalebus :: Pattern Int -> Pattern Double -> ControlPattern timescalebus _ _ = error $ "Control parameter 'timescale' can't be sent to a bus." -- | time stretch window size timescalewin :: Pattern Double -> ControlPattern timescalewin = pF "timescalewin" timescalewinTake :: String -> [Double] -> ControlPattern timescalewinTake name xs = pStateListF "timescalewin" name xs timescalewinCount :: String -> ControlPattern timescalewinCount name = pStateF "timescalewin" name (maybe 0 (+1)) timescalewinCountTo :: String -> Pattern Double -> Pattern ValueMap timescalewinCountTo name ipat = innerJoin $ (\i -> pStateF "timescalewin" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat timescalewinbus :: Pattern Int -> Pattern Double -> ControlPattern timescalewinbus _ _ = error $ "Control parameter 'timescalewin' can't be sent to a bus." -- | for internal sound routing to :: Pattern Double -> ControlPattern to = pF "to" toTake :: String -> [Double] -> ControlPattern toTake name xs = pStateListF "to" name xs toCount :: String -> ControlPattern toCount name = pStateF "to" name (maybe 0 (+1)) toCountTo :: String -> Pattern Double -> Pattern ValueMap toCountTo name ipat = innerJoin $ (\i -> pStateF "to" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat tobus :: Pattern Int -> Pattern Double -> ControlPattern tobus busid pat = (pF "to" pat) # (pI "^to" busid) torecv :: Pattern Int -> ControlPattern torecv busid = pI "^to" busid -- | for internal sound routing toArg :: Pattern String -> ControlPattern toArg = pS "toArg" toArgTake :: String -> [Double] -> ControlPattern toArgTake name xs = pStateListF "toArg" name xs toArgbus :: Pattern Int -> Pattern String -> ControlPattern toArgbus busid pat = (pS "toArg" pat) # (pI "^toArg" busid) toArgrecv :: Pattern Int -> ControlPattern toArgrecv busid = pI "^toArg" busid -- | tomdecay :: Pattern Double -> ControlPattern tomdecay = pF "tomdecay" tomdecayTake :: String -> [Double] -> ControlPattern tomdecayTake name xs = pStateListF "tomdecay" name xs tomdecayCount :: String -> ControlPattern tomdecayCount name = pStateF "tomdecay" name (maybe 0 (+1)) tomdecayCountTo :: String -> Pattern Double -> Pattern ValueMap tomdecayCountTo name ipat = innerJoin $ (\i -> pStateF "tomdecay" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat tomdecaybus :: Pattern Int -> Pattern Double -> ControlPattern tomdecaybus busid pat = (pF "tomdecay" pat) # (pI "^tomdecay" busid) tomdecayrecv :: Pattern Int -> ControlPattern tomdecayrecv busid = pI "^tomdecay" busid -- | Tremolo Audio DSP effect | params are 'tremolorate' and 'tremolodepth' tremolodepth :: Pattern Double -> ControlPattern tremolodepth = pF "tremolodepth" tremolodepthTake :: String -> [Double] -> ControlPattern tremolodepthTake name xs = pStateListF "tremolodepth" name xs tremolodepthCount :: String -> ControlPattern tremolodepthCount name = pStateF "tremolodepth" name (maybe 0 (+1)) tremolodepthCountTo :: String -> Pattern Double -> Pattern ValueMap tremolodepthCountTo name ipat = innerJoin $ (\i -> pStateF "tremolodepth" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat tremolodepthbus :: Pattern Int -> Pattern Double -> ControlPattern tremolodepthbus busid pat = (pF "tremolodepth" pat) # (pI "^tremolodepth" busid) tremolodepthrecv :: Pattern Int -> ControlPattern tremolodepthrecv busid = pI "^tremolodepth" busid -- | Tremolo Audio DSP effect | params are 'tremolorate' and 'tremolodepth' tremolorate :: Pattern Double -> ControlPattern tremolorate = pF "tremolorate" tremolorateTake :: String -> [Double] -> ControlPattern tremolorateTake name xs = pStateListF "tremolorate" name xs tremolorateCount :: String -> ControlPattern tremolorateCount name = pStateF "tremolorate" name (maybe 0 (+1)) tremolorateCountTo :: String -> Pattern Double -> Pattern ValueMap tremolorateCountTo name ipat = innerJoin $ (\i -> pStateF "tremolorate" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat tremoloratebus :: Pattern Int -> Pattern Double -> ControlPattern tremoloratebus busid pat = (pF "tremolorate" pat) # (pI "^tremolorate" busid) tremoloraterecv :: Pattern Int -> ControlPattern tremoloraterecv busid = pI "^tremolorate" busid -- | tube distortion triode :: Pattern Double -> ControlPattern triode = pF "triode" triodeTake :: String -> [Double] -> ControlPattern triodeTake name xs = pStateListF "triode" name xs triodeCount :: String -> ControlPattern triodeCount name = pStateF "triode" name (maybe 0 (+1)) triodeCountTo :: String -> Pattern Double -> Pattern ValueMap triodeCountTo name ipat = innerJoin $ (\i -> pStateF "triode" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat triodebus :: Pattern Int -> Pattern Double -> ControlPattern triodebus busid pat = (pF "triode" pat) # (pI "^triode" busid) trioderecv :: Pattern Int -> ControlPattern trioderecv busid = pI "^triode" busid -- | tsdelay :: Pattern Double -> ControlPattern tsdelay = pF "tsdelay" tsdelayTake :: String -> [Double] -> ControlPattern tsdelayTake name xs = pStateListF "tsdelay" name xs tsdelayCount :: String -> ControlPattern tsdelayCount name = pStateF "tsdelay" name (maybe 0 (+1)) tsdelayCountTo :: String -> Pattern Double -> Pattern ValueMap tsdelayCountTo name ipat = innerJoin $ (\i -> pStateF "tsdelay" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat tsdelaybus :: Pattern Int -> Pattern Double -> ControlPattern tsdelaybus busid pat = (pF "tsdelay" pat) # (pI "^tsdelay" busid) tsdelayrecv :: Pattern Int -> ControlPattern tsdelayrecv busid = pI "^tsdelay" busid -- | uid :: Pattern Double -> ControlPattern uid = pF "uid" uidTake :: String -> [Double] -> ControlPattern uidTake name xs = pStateListF "uid" name xs uidCount :: String -> ControlPattern uidCount name = pStateF "uid" name (maybe 0 (+1)) uidCountTo :: String -> Pattern Double -> Pattern ValueMap uidCountTo name ipat = innerJoin $ (\i -> pStateF "uid" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat uidbus :: Pattern Int -> Pattern Double -> ControlPattern uidbus _ _ = error $ "Control parameter 'uid' can't be sent to a bus." -- | used in conjunction with `speed`, accepts values of "r" (rate, default behavior), "c" (cycles), or "s" (seconds). Using `unit "c"` means `speed` will be interpreted in units of cycles, e.g. `speed "1"` means samples will be stretched to fill a cycle. Using `unit "s"` means the playback speed will be adjusted so that the duration is the number of seconds specified by `speed`. unit :: Pattern String -> ControlPattern unit = pS "unit" unitTake :: String -> [Double] -> ControlPattern unitTake name xs = pStateListF "unit" name xs unitbus :: Pattern Int -> Pattern String -> ControlPattern unitbus _ _ = error $ "Control parameter 'unit' can't be sent to a bus." -- | val :: Pattern Double -> ControlPattern val = pF "val" valTake :: String -> [Double] -> ControlPattern valTake name xs = pStateListF "val" name xs valCount :: String -> ControlPattern valCount name = pStateF "val" name (maybe 0 (+1)) valCountTo :: String -> Pattern Double -> Pattern ValueMap valCountTo name ipat = innerJoin $ (\i -> pStateF "val" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat valbus :: Pattern Int -> Pattern Double -> ControlPattern valbus _ _ = error $ "Control parameter 'val' can't be sent to a bus." -- | vcfegint :: Pattern Double -> ControlPattern vcfegint = pF "vcfegint" vcfegintTake :: String -> [Double] -> ControlPattern vcfegintTake name xs = pStateListF "vcfegint" name xs vcfegintCount :: String -> ControlPattern vcfegintCount name = pStateF "vcfegint" name (maybe 0 (+1)) vcfegintCountTo :: String -> Pattern Double -> Pattern ValueMap vcfegintCountTo name ipat = innerJoin $ (\i -> pStateF "vcfegint" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat vcfegintbus :: Pattern Int -> Pattern Double -> ControlPattern vcfegintbus busid pat = (pF "vcfegint" pat) # (pI "^vcfegint" busid) vcfegintrecv :: Pattern Int -> ControlPattern vcfegintrecv busid = pI "^vcfegint" busid -- | vcoegint :: Pattern Double -> ControlPattern vcoegint = pF "vcoegint" vcoegintTake :: String -> [Double] -> ControlPattern vcoegintTake name xs = pStateListF "vcoegint" name xs vcoegintCount :: String -> ControlPattern vcoegintCount name = pStateF "vcoegint" name (maybe 0 (+1)) vcoegintCountTo :: String -> Pattern Double -> Pattern ValueMap vcoegintCountTo name ipat = innerJoin $ (\i -> pStateF "vcoegint" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat vcoegintbus :: Pattern Int -> Pattern Double -> ControlPattern vcoegintbus busid pat = (pF "vcoegint" pat) # (pI "^vcoegint" busid) vcoegintrecv :: Pattern Int -> ControlPattern vcoegintrecv busid = pI "^vcoegint" busid -- | velocity :: Pattern Double -> ControlPattern velocity = pF "velocity" velocityTake :: String -> [Double] -> ControlPattern velocityTake name xs = pStateListF "velocity" name xs velocityCount :: String -> ControlPattern velocityCount name = pStateF "velocity" name (maybe 0 (+1)) velocityCountTo :: String -> Pattern Double -> Pattern ValueMap velocityCountTo name ipat = innerJoin $ (\i -> pStateF "velocity" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat velocitybus :: Pattern Int -> Pattern Double -> ControlPattern velocitybus busid pat = (pF "velocity" pat) # (pI "^velocity" busid) velocityrecv :: Pattern Int -> ControlPattern velocityrecv busid = pI "^velocity" busid -- | voice :: Pattern Double -> ControlPattern voice = pF "voice" voiceTake :: String -> [Double] -> ControlPattern voiceTake name xs = pStateListF "voice" name xs voiceCount :: String -> ControlPattern voiceCount name = pStateF "voice" name (maybe 0 (+1)) voiceCountTo :: String -> Pattern Double -> Pattern ValueMap voiceCountTo name ipat = innerJoin $ (\i -> pStateF "voice" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat voicebus :: Pattern Int -> Pattern Double -> ControlPattern voicebus busid pat = (pF "voice" pat) # (pI "^voice" busid) voicerecv :: Pattern Int -> ControlPattern voicerecv busid = pI "^voice" busid -- | formant filter to make things sound like vowels, a pattern of either `a`, `e`, `i`, `o` or `u`. Use a rest (`~`) for no effect. vowel :: Pattern String -> ControlPattern vowel = pS "vowel" vowelTake :: String -> [Double] -> ControlPattern vowelTake name xs = pStateListF "vowel" name xs vowelbus :: Pattern Int -> Pattern String -> ControlPattern vowelbus busid pat = (pS "vowel" pat) # (pI "^vowel" busid) vowelrecv :: Pattern Int -> ControlPattern vowelrecv busid = pI "^vowel" busid -- | waveloss :: Pattern Double -> ControlPattern waveloss = pF "waveloss" wavelossTake :: String -> [Double] -> ControlPattern wavelossTake name xs = pStateListF "waveloss" name xs wavelossCount :: String -> ControlPattern wavelossCount name = pStateF "waveloss" name (maybe 0 (+1)) wavelossCountTo :: String -> Pattern Double -> Pattern ValueMap wavelossCountTo name ipat = innerJoin $ (\i -> pStateF "waveloss" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat wavelossbus :: Pattern Int -> Pattern Double -> ControlPattern wavelossbus busid pat = (pF "waveloss" pat) # (pI "^waveloss" busid) wavelossrecv :: Pattern Int -> ControlPattern wavelossrecv busid = pI "^waveloss" busid -- | xsdelay :: Pattern Double -> ControlPattern xsdelay = pF "xsdelay" xsdelayTake :: String -> [Double] -> ControlPattern xsdelayTake name xs = pStateListF "xsdelay" name xs xsdelayCount :: String -> ControlPattern xsdelayCount name = pStateF "xsdelay" name (maybe 0 (+1)) xsdelayCountTo :: String -> Pattern Double -> Pattern ValueMap xsdelayCountTo name ipat = innerJoin $ (\i -> pStateF "xsdelay" name (maybe 0 ((`mod'` i) . (+1)))) <$> ipat xsdelaybus :: Pattern Int -> Pattern Double -> ControlPattern xsdelaybus busid pat = (pF "xsdelay" pat) # (pI "^xsdelay" busid) xsdelayrecv :: Pattern Int -> ControlPattern xsdelayrecv busid = pI "^xsdelay" busid -- aliases voi :: Pattern Double -> ControlPattern voi = voice voibus :: Pattern Int -> Pattern Double -> ControlPattern voibus = voicebus voirecv :: Pattern Int -> ControlPattern voirecv = voicerecv vco :: Pattern Double -> ControlPattern vco = vcoegint vcobus :: Pattern Int -> Pattern Double -> ControlPattern vcobus = vcoegintbus vcorecv :: Pattern Int -> ControlPattern vcorecv = vcoegintrecv vcf :: Pattern Double -> ControlPattern vcf = vcfegint vcfbus :: Pattern Int -> Pattern Double -> ControlPattern vcfbus = vcfegintbus vcfrecv :: Pattern Int -> ControlPattern vcfrecv = vcfegintrecv up :: Pattern Note -> ControlPattern up = note tremr :: Pattern Double -> ControlPattern tremr = tremolorate tremrbus :: Pattern Int -> Pattern Double -> ControlPattern tremrbus = tremoloratebus tremrrecv :: Pattern Int -> ControlPattern tremrrecv = tremoloraterecv tremdp :: Pattern Double -> ControlPattern tremdp = tremolodepth tremdpbus :: Pattern Int -> Pattern Double -> ControlPattern tremdpbus = tremolodepthbus tremdprecv :: Pattern Int -> ControlPattern tremdprecv = tremolodepthrecv tdecay :: Pattern Double -> ControlPattern tdecay = tomdecay tdecaybus :: Pattern Int -> Pattern Double -> ControlPattern tdecaybus = tomdecaybus tdecayrecv :: Pattern Int -> ControlPattern tdecayrecv = tomdecayrecv sz :: Pattern Double -> ControlPattern sz = size szbus :: Pattern Int -> Pattern Double -> ControlPattern szbus = sizebus szrecv :: Pattern Int -> ControlPattern szrecv = sizerecv sus :: Pattern Double -> ControlPattern sus = sustain stt :: Pattern Double -> ControlPattern stt = stuttertime sttbus :: Pattern Int -> Pattern Double -> ControlPattern sttbus = stuttertimebus sttrecv :: Pattern Int -> ControlPattern sttrecv = stuttertimerecv std :: Pattern Double -> ControlPattern std = stutterdepth stdbus :: Pattern Int -> Pattern Double -> ControlPattern stdbus = stutterdepthbus stdrecv :: Pattern Int -> ControlPattern stdrecv = stutterdepthrecv sld :: Pattern Double -> ControlPattern sld = slide sldbus :: Pattern Int -> Pattern Double -> ControlPattern sldbus = slidebus sldrecv :: Pattern Int -> ControlPattern sldrecv = sliderecv scr :: Pattern Double -> ControlPattern scr = scrash scrbus :: Pattern Int -> Pattern Double -> ControlPattern scrbus = scrashbus scrrecv :: Pattern Int -> ControlPattern scrrecv = scrashrecv scp :: Pattern Double -> ControlPattern scp = sclap scpbus :: Pattern Int -> Pattern Double -> ControlPattern scpbus = sclapbus scprecv :: Pattern Int -> ControlPattern scprecv = sclaprecv scl :: Pattern Double -> ControlPattern scl = sclaves sclbus :: Pattern Int -> Pattern Double -> ControlPattern sclbus = sclavesbus sclrecv :: Pattern Int -> ControlPattern sclrecv = sclavesrecv sag :: Pattern Double -> ControlPattern sag = sagogo sagbus :: Pattern Int -> Pattern Double -> ControlPattern sagbus = sagogobus sagrecv :: Pattern Int -> ControlPattern sagrecv = sagogorecv s :: Pattern String -> ControlPattern s = sound rel :: Pattern Double -> ControlPattern rel = release relbus :: Pattern Int -> Pattern Double -> ControlPattern relbus = releasebus relrecv :: Pattern Int -> ControlPattern relrecv = releaserecv por :: Pattern Double -> ControlPattern por = portamento porbus :: Pattern Int -> Pattern Double -> ControlPattern porbus = portamentobus porrecv :: Pattern Int -> ControlPattern porrecv = portamentorecv pit3 :: Pattern Double -> ControlPattern pit3 = pitch3 pit3bus :: Pattern Int -> Pattern Double -> ControlPattern pit3bus = pitch3bus pit3recv :: Pattern Int -> ControlPattern pit3recv = pitch3recv pit2 :: Pattern Double -> ControlPattern pit2 = pitch2 pit2bus :: Pattern Int -> Pattern Double -> ControlPattern pit2bus = pitch2bus pit2recv :: Pattern Int -> ControlPattern pit2recv = pitch2recv pit1 :: Pattern Double -> ControlPattern pit1 = pitch1 pit1bus :: Pattern Int -> Pattern Double -> ControlPattern pit1bus = pitch1bus pit1recv :: Pattern Int -> ControlPattern pit1recv = pitch1recv phasr :: Pattern Double -> ControlPattern phasr = phaserrate phasrbus :: Pattern Int -> Pattern Double -> ControlPattern phasrbus = phaserratebus phasrrecv :: Pattern Int -> ControlPattern phasrrecv = phaserraterecv phasdp :: Pattern Double -> ControlPattern phasdp = phaserdepth phasdpbus :: Pattern Int -> Pattern Double -> ControlPattern phasdpbus = phaserdepthbus phasdprecv :: Pattern Int -> ControlPattern phasdprecv = phaserdepthrecv ohdecay :: Pattern Double -> ControlPattern ohdecay = ophatdecay ohdecaybus :: Pattern Int -> Pattern Double -> ControlPattern ohdecaybus = ophatdecaybus ohdecayrecv :: Pattern Int -> ControlPattern ohdecayrecv = ophatdecayrecv number :: Pattern Note -> ControlPattern number = n lsn :: Pattern Double -> ControlPattern lsn = lsnare lsnbus :: Pattern Int -> Pattern Double -> ControlPattern lsnbus = lsnarebus lsnrecv :: Pattern Int -> ControlPattern lsnrecv = lsnarerecv lpq :: Pattern Double -> ControlPattern lpq = resonance lpqbus :: Pattern Int -> Pattern Double -> ControlPattern lpqbus = resonancebus lpqrecv :: Pattern Int -> ControlPattern lpqrecv = resonancerecv lpf :: Pattern Double -> ControlPattern lpf = cutoff lpfbus :: Pattern Int -> Pattern Double -> ControlPattern lpfbus = cutoffbus lpfrecv :: Pattern Int -> ControlPattern lpfrecv = cutoffrecv loh :: Pattern Double -> ControlPattern loh = lophat lohbus :: Pattern Int -> Pattern Double -> ControlPattern lohbus = lophatbus lohrecv :: Pattern Int -> ControlPattern lohrecv = lophatrecv llt :: Pattern Double -> ControlPattern llt = llotom lltbus :: Pattern Int -> Pattern Double -> ControlPattern lltbus = llotombus lltrecv :: Pattern Int -> ControlPattern lltrecv = llotomrecv lht :: Pattern Double -> ControlPattern lht = lhitom lhtbus :: Pattern Int -> Pattern Double -> ControlPattern lhtbus = lhitombus lhtrecv :: Pattern Int -> ControlPattern lhtrecv = lhitomrecv lfop :: Pattern Double -> ControlPattern lfop = lfopitchint lfopbus :: Pattern Int -> Pattern Double -> ControlPattern lfopbus = lfopitchintbus lfoprecv :: Pattern Int -> ControlPattern lfoprecv = lfopitchintrecv lfoi :: Pattern Double -> ControlPattern lfoi = lfoint lfoibus :: Pattern Int -> Pattern Double -> ControlPattern lfoibus = lfointbus lfoirecv :: Pattern Int -> ControlPattern lfoirecv = lfointrecv lfoc :: Pattern Double -> ControlPattern lfoc = lfocutoffint lfocbus :: Pattern Int -> Pattern Double -> ControlPattern lfocbus = lfocutoffintbus lfocrecv :: Pattern Int -> ControlPattern lfocrecv = lfocutoffintrecv lcr :: Pattern Double -> ControlPattern lcr = lcrash lcrbus :: Pattern Int -> Pattern Double -> ControlPattern lcrbus = lcrashbus lcrrecv :: Pattern Int -> ControlPattern lcrrecv = lcrashrecv lcp :: Pattern Double -> ControlPattern lcp = lclap lcpbus :: Pattern Int -> Pattern Double -> ControlPattern lcpbus = lclapbus lcprecv :: Pattern Int -> ControlPattern lcprecv = lclaprecv lcl :: Pattern Double -> ControlPattern lcl = lclaves lclbus :: Pattern Int -> Pattern Double -> ControlPattern lclbus = lclavesbus lclrecv :: Pattern Int -> ControlPattern lclrecv = lclavesrecv lch :: Pattern Double -> ControlPattern lch = lclhat lchbus :: Pattern Int -> Pattern Double -> ControlPattern lchbus = lclhatbus lchrecv :: Pattern Int -> ControlPattern lchrecv = lclhatrecv lbd :: Pattern Double -> ControlPattern lbd = lkick lbdbus :: Pattern Int -> Pattern Double -> ControlPattern lbdbus = lkickbus lbdrecv :: Pattern Int -> ControlPattern lbdrecv = lkickrecv lag :: Pattern Double -> ControlPattern lag = lagogo lagbus :: Pattern Int -> Pattern Double -> ControlPattern lagbus = lagogobus lagrecv :: Pattern Int -> ControlPattern lagrecv = lagogorecv hpq :: Pattern Double -> ControlPattern hpq = hresonance hpqbus :: Pattern Int -> Pattern Double -> ControlPattern hpqbus = hresonancebus hpqrecv :: Pattern Int -> ControlPattern hpqrecv = hresonancerecv hpf :: Pattern Double -> ControlPattern hpf = hcutoff hpfbus :: Pattern Int -> Pattern Double -> ControlPattern hpfbus = hcutoffbus hpfrecv :: Pattern Int -> ControlPattern hpfrecv = hcutoffrecv hg :: Pattern Double -> ControlPattern hg = hatgrain hgbus :: Pattern Int -> Pattern Double -> ControlPattern hgbus = hatgrainbus hgrecv :: Pattern Int -> ControlPattern hgrecv = hatgrainrecv gat :: Pattern Double -> ControlPattern gat = gate gatbus :: Pattern Int -> Pattern Double -> ControlPattern gatbus = gatebus gatrecv :: Pattern Int -> ControlPattern gatrecv = gaterecv fadeOutTime :: Pattern Double -> ControlPattern fadeOutTime = fadeTime dt :: Pattern Double -> ControlPattern dt = delaytime dtbus :: Pattern Int -> Pattern Double -> ControlPattern dtbus = delaytimebus dtrecv :: Pattern Int -> ControlPattern dtrecv = delaytimerecv dfb :: Pattern Double -> ControlPattern dfb = delayfeedback dfbbus :: Pattern Int -> Pattern Double -> ControlPattern dfbbus = delayfeedbackbus dfbrecv :: Pattern Int -> ControlPattern dfbrecv = delayfeedbackrecv det :: Pattern Double -> ControlPattern det = detune detbus :: Pattern Int -> Pattern Double -> ControlPattern detbus = detunebus detrecv :: Pattern Int -> ControlPattern detrecv = detunerecv delayt :: Pattern Double -> ControlPattern delayt = delaytime delaytbus :: Pattern Int -> Pattern Double -> ControlPattern delaytbus = delaytimebus delaytrecv :: Pattern Int -> ControlPattern delaytrecv = delaytimerecv delayfb :: Pattern Double -> ControlPattern delayfb = delayfeedback delayfbbus :: Pattern Int -> Pattern Double -> ControlPattern delayfbbus = delayfeedbackbus delayfbrecv :: Pattern Int -> ControlPattern delayfbrecv = delayfeedbackrecv ctfg :: Pattern Double -> ControlPattern ctfg = cutoffegint ctfgbus :: Pattern Int -> Pattern Double -> ControlPattern ctfgbus = cutoffegintbus ctfgrecv :: Pattern Int -> ControlPattern ctfgrecv = cutoffegintrecv ctf :: Pattern Double -> ControlPattern ctf = cutoff ctfbus :: Pattern Int -> Pattern Double -> ControlPattern ctfbus = cutoffbus ctfrecv :: Pattern Int -> ControlPattern ctfrecv = cutoffrecv chdecay :: Pattern Double -> ControlPattern chdecay = clhatdecay chdecaybus :: Pattern Int -> Pattern Double -> ControlPattern chdecaybus = clhatdecaybus chdecayrecv :: Pattern Int -> ControlPattern chdecayrecv = clhatdecayrecv bpq :: Pattern Double -> ControlPattern bpq = bandq bpqbus :: Pattern Int -> Pattern Double -> ControlPattern bpqbus = bandqbus bpqrecv :: Pattern Int -> ControlPattern bpqrecv = bandqrecv bpf :: Pattern Double -> ControlPattern bpf = bandf bpfbus :: Pattern Int -> Pattern Double -> ControlPattern bpfbus = bandfbus bpfrecv :: Pattern Int -> ControlPattern bpfrecv = bandfrecv att :: Pattern Double -> ControlPattern att = attack attbus :: Pattern Int -> Pattern Double -> ControlPattern attbus = attackbus attrecv :: Pattern Int -> ControlPattern attrecv = attackrecv
bgold-cosmos/Tidal
src/Sound/Tidal/Params.hs
gpl-3.0
145,052
0
14
23,387
49,354
25,614
23,740
2,679
1
module ExprIfCond where f = if 3 then 4 else 5
roberth/uu-helium
test/typeerrors/Examples/ExprIfCond.hs
gpl-3.0
48
0
5
12
17
11
6
2
2
{-# 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.ElasticTranscoder.ListPresets -- 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. -- | The ListPresets operation gets a list of the default presets included with -- Elastic Transcoder and the presets that you've added in an AWS region. -- -- <http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/ListPresets.html> module Network.AWS.ElasticTranscoder.ListPresets ( -- * Request ListPresets -- ** Request constructor , listPresets -- ** Request lenses , lp1Ascending , lp1PageToken -- * Response , ListPresetsResponse -- ** Response constructor , listPresetsResponse -- ** Response lenses , lpr1NextPageToken , lpr1Presets ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.RestJSON import Network.AWS.ElasticTranscoder.Types import qualified GHC.Exts data ListPresets = ListPresets { _lp1Ascending :: Maybe Text , _lp1PageToken :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'ListPresets' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lp1Ascending' @::@ 'Maybe' 'Text' -- -- * 'lp1PageToken' @::@ 'Maybe' 'Text' -- listPresets :: ListPresets listPresets = ListPresets { _lp1Ascending = Nothing , _lp1PageToken = Nothing } -- | To list presets in chronological order by the date and time that they were -- created, enter 'true'. To list presets in reverse chronological order, enter 'false'. lp1Ascending :: Lens' ListPresets (Maybe Text) lp1Ascending = lens _lp1Ascending (\s a -> s { _lp1Ascending = a }) -- | When Elastic Transcoder returns more than one page of results, use 'pageToken' -- in subsequent 'GET' requests to get each successive page of results. lp1PageToken :: Lens' ListPresets (Maybe Text) lp1PageToken = lens _lp1PageToken (\s a -> s { _lp1PageToken = a }) data ListPresetsResponse = ListPresetsResponse { _lpr1NextPageToken :: Maybe Text , _lpr1Presets :: List "Presets" Preset } deriving (Eq, Read, Show) -- | 'ListPresetsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lpr1NextPageToken' @::@ 'Maybe' 'Text' -- -- * 'lpr1Presets' @::@ ['Preset'] -- listPresetsResponse :: ListPresetsResponse listPresetsResponse = ListPresetsResponse { _lpr1Presets = mempty , _lpr1NextPageToken = Nothing } -- | A value that you use to access the second and subsequent pages of results, if -- any. When the presets fit on one page or when you've reached the last page of -- results, the value of 'NextPageToken' is 'null'. lpr1NextPageToken :: Lens' ListPresetsResponse (Maybe Text) lpr1NextPageToken = lens _lpr1NextPageToken (\s a -> s { _lpr1NextPageToken = a }) -- | An array of 'Preset' objects. lpr1Presets :: Lens' ListPresetsResponse [Preset] lpr1Presets = lens _lpr1Presets (\s a -> s { _lpr1Presets = a }) . _List instance ToPath ListPresets where toPath = const "/2012-09-25/presets" instance ToQuery ListPresets where toQuery ListPresets{..} = mconcat [ "Ascending" =? _lp1Ascending , "PageToken" =? _lp1PageToken ] instance ToHeaders ListPresets instance ToJSON ListPresets where toJSON = const (toJSON Empty) instance AWSRequest ListPresets where type Sv ListPresets = ElasticTranscoder type Rs ListPresets = ListPresetsResponse request = get response = jsonResponse instance FromJSON ListPresetsResponse where parseJSON = withObject "ListPresetsResponse" $ \o -> ListPresetsResponse <$> o .:? "NextPageToken" <*> o .:? "Presets" .!= mempty instance AWSPager ListPresets where page rq rs | stop (rs ^. lpr1NextPageToken) = Nothing | otherwise = (\x -> rq & lp1PageToken ?~ x) <$> (rs ^. lpr1NextPageToken)
romanb/amazonka
amazonka-elastictranscoder/gen/Network/AWS/ElasticTranscoder/ListPresets.hs
mpl-2.0
4,787
0
12
1,036
676
399
277
73
1
module Hans.Nat where import Hans.Addr (toAddr) import qualified Hans.Nat.State as Nat import Hans.Network (Network) import Hans.Tcp.Packet (TcpPort) import Hans.Types import Hans.Udp.Packet (UdpPort) -- | Add a TCP port-forwarding rule. forwardTcpPort :: Network addr => NetworkStack -> addr -- ^ Local address (can be wildcard) -> TcpPort -- ^ Local port -> addr -- ^ Remote address -> TcpPort -- ^ Remote port -> IO () forwardTcpPort ns src srcPort dest destPort = Nat.addTcpPortForward ns Nat.PortForward { pfSourceAddr = toAddr src , pfSourcePort = srcPort , pfDestAddr = toAddr dest , pfDestPort = destPort } -- | Remove a TCP port-forwarding rule. removeTcpPortForward :: Network addr => NetworkStack -> addr -- ^ Local address (can be wildcard) -> TcpPort -- ^ Local port -> IO () removeTcpPortForward ns src port = Nat.removeTcpPortForward ns (toAddr src) port -- | Add a UDP port-forwarding rule. forwardUdpPort :: Network addr => NetworkStack -> addr -- ^ Local address (can be wildcard) -> UdpPort -- ^ Local port -> addr -- ^ Remote address -> UdpPort -- ^ Remote port -> IO () forwardUdpPort ns src srcPort dest destPort = Nat.addUdpPortForward ns Nat.PortForward { pfSourceAddr = toAddr src , pfSourcePort = srcPort , pfDestAddr = toAddr dest , pfDestPort = destPort } -- | Remove a UDP port-forwarding rule. removeUdpPortForward :: Network addr => NetworkStack -> addr -- ^ Local address (can be wildcard) -> UdpPort -- ^ Local port -> IO () removeUdpPortForward ns src port = Nat.removeUdpPortForward ns (toAddr src) port
GaloisInc/HaNS
src/Hans/Nat.hs
bsd-3-clause
2,101
0
12
810
378
208
170
45
1
module Distribution.Query.TH where import MonadUtils import Data.DeriveTH import Language.Haskell.TH deriveMany :: Derivation -> [Name] -> Q [Dec] deriveMany = concatMapM . derive
beni55/cabal-query
src/Distribution/Query/TH.hs
bsd-3-clause
182
0
8
24
52
31
21
6
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UnicodeSyntax #-} module T16326_Compile1 where import Data.Kind type DApply a (b :: a -> Type) (f :: forall (x :: a) -> b x) (x :: a) = f x type DComp a (b :: a -> Type) (c :: forall (x :: a). b x -> Type) (f :: forall (x :: a). forall (y :: b x) -> c y) (g :: forall (x :: a) -> b x) (x :: a) = f (g x) -- Ensure that ElimList has a CUSK, beuas it is -- is used polymorphically its RHS (c.f. #16344) type family ElimList (a :: Type) (p :: [a] -> Type) (s :: [a]) (pNil :: p '[]) (pCons :: forall (x :: a) (xs :: [a]) -> p xs -> p (x:xs)) :: p s where forall a p pNil (pCons :: forall (x :: a) (xs :: [a]) -> p xs -> p (x:xs)). ElimList a p '[] pNil pCons = pNil forall a p x xs pNil (pCons :: forall (x :: a) (xs :: [a]) -> p xs -> p (x:xs)). ElimList a p (x:xs) pNil pCons = pCons x xs (ElimList a p xs pNil pCons) data Proxy' :: forall k -> k -> Type where MkProxy' :: forall k (a :: k). Proxy' k a type family Proxy2' ∷ ∀ k → k → Type where Proxy2' = Proxy'
sdiehl/ghc
testsuite/tests/dependent/should_compile/T16326_Compile1.hs
bsd-3-clause
1,344
0
14
452
530
314
216
-1
-1
-- -- Copyright (c) 2013 Citrix Systems, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- {-# LANGUAGE OverloadedStrings #-} module XenMgr.Connect.Xenvm ( -- Queries domainID , stubDomainID , domainXsPath , isRunning , isFocused , state , stateStr , acpiState , wiredMac , nics , requiredToBootKib -- Xenvm activities , forkXenvm , quitXenvm , isXenvmUp , readConfig , onNotify , onNotifyRemove -- VM activities , start, startPaused , reboot , shutdown , destroy , waitForState , waitForAcpiState , sleep , hibernate , resumeFromSleep , suspendToFile , resumeFromFile , pause , unpause , changeCd , changeNicNetwork , connectVif , setMemTarget , setNicBackendDom , NotifyHandler ) where import Control.Applicative import Control.Monad import Control.Concurrent import Data.String import Data.Maybe import qualified Data.Map as M import qualified Data.Text as T import Tools.XenStore import Tools.Log import Tools.Process import Tools.Misc import Vm.Types import Vm.State import XenMgr.Rpc import Control.Monad.Error (catchError, throwError) type Params = [(String,String)] domainID :: MonadRpc e m => Uuid -> m (Maybe DomainID) domainID uuid = catchNoService Nothing $ do r <- invoke uuid "get_domid" [] let id = fromInteger (read $ unpackStrArg r) return $ if id<0 then Nothing else Just id stubDomainID :: MonadRpc e m => Uuid -> m (Maybe DomainID) stubDomainID uuid = catchNoService Nothing $ do r <- invoke uuid "get_stubdomid" [] let id = fromInteger (read $ unpackStrArg r) return $ if id<0 then Nothing else Just id domainXsPath :: MonadRpc e m => Uuid -> m String domainXsPath uuid = local `fmap` domainID uuid where local Nothing = "/local/domain/unknown" local (Just domid) = "/local/domain/" ++ show domid isRunning :: (MonadRpc e m) => Uuid -> m Bool isRunning uuid = (not . (`elem` [Shutdown, Rebooted])) `fmap` state uuid isFocused :: MonadRpc e m => Uuid -> m Bool isFocused uuid = catchNoService False $ do s <- state uuid p <- domainXsPath uuid haveFocus s p where -- If we are not running, we don't have focus, -- but if we are running, we test the xenstore node haveFocus Shutdown _ = return False haveFocus _ domP = let path = domP ++ "/switcher/have_focus" in liftIO $ xsRead path >>= -- We assumed not focused if the xenstore node cannot be read return . maybe False (== "1") state :: MonadRpc e m => Uuid -> m VmState state uuid = catchNoService Shutdown $ do r <- invoke uuid "get_status" [] return $ stateFromStr (unpackStrArg r) --FIXME: broadside misery, remove this on master stateStr :: Uuid -> Rpc String stateStr uuid = catchNoService "shutdown" $ do r <- invoke uuid "get_status" [] return $ unpackStrArg r acpiState :: Uuid -> Rpc AcpiState acpiState uuid = catchNoService 5 $ do r <- invoke uuid "get_acpi_state" [] return $ read (unpackStrArg r) wiredMac :: Uuid -> Rpc (Maybe String) wiredMac uuid = wiredNic uuid >>= return . (maybe Nothing $ Just . nicMac) -- first nic is assumed to be wired -- TODO: lift this assumption wiredNic :: Uuid -> Rpc (Maybe Nic) wiredNic uuid = catchNoService Nothing $ do ns <- nics uuid case ns of [] -> return Nothing n : _ -> return $ Just n nics :: Uuid -> Rpc [Nic] nics uuid = catchNoService [] $ do r <- invoke uuid "nic_list" [] let text = T.pack $ unpackStrArg r descriptions = tail $ T.lines text return $ map parse descriptions where parse str = let columns = T.split delim str columns' = map T.strip columns in case columns' of [id, bridge, mac, _] -> Nic (XbDeviceID $ read $ T.unpack id) (networkFromStr $ T.unpack bridge) (T.unpack mac) _ -> error "unexpected nic list string from xenvm" delim = T.pack "|" requiredToBootKib :: Uuid -> Rpc Integer requiredToBootKib uuid = read . unpackStrArg <$> invoke uuid "get" [("field","required-to-boot-kib")] -- Start XENVM and wait until it's dbus interface is ready -- TODO: clenup somehow ? forkXenvm :: Uuid -> Rpc () forkXenvm uuid = do dbusUp <- liftIO $ newEmptyMVar onNotify uuid "dbus-rpc-up" (whenDbusRpcUp dbusUp) output <- liftIO $ spawnShell' ("xenvm --config " ++ configPath) case output of Nothing -> -- Exit code was <> 0 -- If exit code <> 0, this usually means that an instance of xenvm is already running, -- so we do not have to wait for dbus ready message do info $ "Xenvm " ++ show uuid ++ " already running, skipping monitor start." return () Just _ -> -- Wait until DBUS rpc is up do debug "waiting until xenvm RPC is ready" liftIO $ takeMVar dbusUp return () where configPath = "/tmp/xenmgr-xenvm-" ++ show uuid whenDbusRpcUp dbusUp args = do debug "detected xenvm RPC up event" liftIO $ putMVar dbusUp True quitXenvm :: Uuid -> Rpc () quitXenvm uuid = void (invoke uuid "quit" []) `catchError` noop where noop _ = return () isXenvmUp :: Uuid -> Rpc Bool isXenvmUp uuid = serviceNameTaken (xenvmServiceName uuid) readConfig :: Uuid -> Rpc () readConfig uuid = do invoke uuid "read_config" [] return () start :: Uuid -> Rpc () start uuid = do invoke uuid "start" [] return () startPaused :: Uuid -> Rpc () startPaused uuid = do invoke uuid "start" [ ("paused", "true") ] return () pause :: Uuid -> Rpc () pause uuid = do invoke uuid "pause" [] return () unpause :: Uuid -> Rpc () unpause uuid = do invoke uuid "unpause" [] return () reboot :: Uuid -> Rpc () reboot uuid = do invoke uuid "reboot" [] return () shutdown :: Uuid -> Rpc () shutdown uuid = do r <- isRunning uuid case r of True -> invoke uuid "halt" [] _ -> return [] return () destroy :: Uuid -> Rpc () destroy uuid = do invoke uuid "destroy" [] return () sleep :: Uuid -> Rpc () sleep uuid = do invoke uuid "s3suspend" [ ("timeout", "90") ] return () hibernate :: Uuid -> Rpc () hibernate uuid = do invoke uuid "s4suspend" [ ("timeout", "90") ] return () resumeFromSleep :: Uuid -> Rpc Bool resumeFromSleep uuid = catchNoService False $ do invoke uuid "trigger" [ ("params", "s3resume") ] -- max 10s wait waitForAcpiState uuid 0 (Just 10) suspendToFile :: Uuid -> FilePath -> Rpc () suspendToFile uuid file = do invoke uuid "suspend" [ ("file", file) ] return () resumeFromFile :: Uuid -> FilePath -> Bool -> Bool -> Rpc () resumeFromFile uuid file delete_file paused = do let delete_str = if delete_file then "true" else "false" paused_str = if paused then "true" else "false" invoke uuid "restore" [ ("file", file), ("delete", delete_str), ("paused", paused_str) ] return () waitForState :: Uuid -> VmState -> Maybe Int -> Rpc Bool waitForState uuid expected timeout = do s <- state uuid case (s, timeout) of -- got right state, exit (x, _) | x == expected -> return True -- we timed out while waiting for state (_, Just t) | t <= 0 -> return False -- we continue waiting with lesser timeout (_, Just t) | t > 0 -> do liftIO (threadDelay $ 10^6) waitForState uuid expected (Just $ t-1) -- we have no timeout, wait indifinitely (_, Nothing) -> liftIO (threadDelay $ 10^6) >> waitForState uuid expected Nothing _ -> error "impossible" waitForAcpiState :: Uuid -> Int -> Maybe Int -> Rpc Bool waitForAcpiState uuid expected timeout = do s <- acpiState uuid case (s, timeout) of -- got right state, exit (x, _) | x == expected -> return True -- we timed out while waiting for state (_, Just t) | t <= 0 -> return False -- we continue waiting with lesser timeout (_, Just t) | t > 0 -> do liftIO (threadDelay $ 10^6) waitForAcpiState uuid expected (Just $ t-1) -- we have no timeout, wait indifinitely (_, Nothing) -> liftIO (threadDelay $ 10^6) >> waitForAcpiState uuid expected Nothing _ -> error "impossible" changeCd :: Uuid -> String -> Rpc () changeCd uuid path = do invoke uuid "cd_insert_file" [ ("virtpath", "hdc") , ("physpath", path ) ] return () --TODO: bridge -> network changeNicNetwork :: MonadRpc e m => Uuid -> NicID -> Network -> m () changeNicNetwork uuid nid@(XbDeviceID nicid) network = do invoke uuid "nic_network_switch" [ ("id" , show nicid) , ("network", networkToStr network) ] return () nicFrontendPath :: MonadRpc e m => Uuid -> NicID -> m (Maybe String) nicFrontendPath uuid (XbDeviceID nicid) = do domainP <- domainXsPath uuid vifs <- liftIO . xsDir $ domainP ++ "/device/vif" vwifs <- liftIO . xsDir $ domainP ++ "/device/vwif" let nicid_str = show nicid case () of _ | nicid_str `elem` vifs -> return $ Just (domainP ++ "/device/vif/" ++ nicid_str) | nicid_str `elem` vwifs -> return $ Just (domainP ++ "/device/vwif/" ++ nicid_str) | otherwise -> return Nothing -- Connect or disconnect VIF connectVif :: MonadRpc e m => Uuid -> NicID -> Bool -> m () connectVif uuid nicid connect = do domainP <- domainXsPath uuid front <- nicFrontendPath uuid nicid case front of Nothing -> warn $ "failed to lookup nic " ++ show nicid Just fp -> do let p = fp ++ "/disconnect" liftIO $ xsWrite p value where value | connect == True = "0" | otherwise = "1" setMemTarget :: Uuid -> Int -> Rpc () setMemTarget uuid mbs = do invoke uuid "set_mem_target" [ ("mb", show mbs) ] return () setNicBackendDom :: Uuid -> NicID -> DomainID -> Rpc () setNicBackendDom uuid nic domid = do invoke uuid "set_nic_backend_dom" [ ("id", show nic) , ("domid", show domid) ] return () -- Get a single string result from an RPC call unpackStrArg :: [Variant] -> String unpackStrArg r = case fromVariant . head $ r of Just str -> str Nothing -> error "failed to unpack string arg." -- A higher level wrapper which packs parameter to format expected by xenvm invoke :: MonadRpc e m => Uuid -> String -> Params -> m [Variant] invoke uuid method params = rpcXenvm uuid method [toVariant $ pack params] -- Xenvm expects parameters to be passed as a dictionary mapping strings to strings.. pack :: Params -> M.Map String String pack = M.fromList -- Try to call RPC on a proper xenvm instance rpcXenvm :: MonadRpc e m => Uuid -> String -> [Variant] -> m [Variant] rpcXenvm uuid method = rpcCallOnce . xenvmcall uuid method -- type NotifyHandler = [String] -> Rpc () onNotifyRemove :: Uuid -> String -> NotifyHandler -> Rpc () onNotifyRemove uuid msgname action = let rule = matchSignal "xenvm.signal.notify" "notify" in rpcOnSignalRemove rule process where process _ signal = let [uuidV, _, statusV] = signalArgs signal uuid' = let Just v = fromVariant $ uuidV in v status = let Just v = fromVariant $ statusV in v splits = split ':' status in when (uuid == uuid') $ case splits of (msg:args) | msg == msgname -> action args _ -> return () -- FIXME: centralise handling of events using one signal handler onNotify :: Uuid -> String -> NotifyHandler -> Rpc () onNotify uuid msgname action = let rule = matchSignal "xenvm.signal.notify" "notify" in rpcOnSignal rule process where process _ signal = let [uuidV, _, statusV] = signalArgs signal uuid' = let Just v = fromVariant $ uuidV in v status = let Just v = fromVariant $ statusV in v splits = split ':' status in when (uuid == uuid') $ case splits of (msg:args) | msg == msgname -> action args _ -> return () xenvmServiceName :: Uuid -> String xenvmServiceName uuid = "org.xen.vm.uuid_" ++ uuid' where uuid' = uuidStrUnderscore uuid xenvmcall :: Uuid -> String -> [Variant] -> RpcCall xenvmcall uuid memb args = RpcCall service object interface (fromString memb) args where service = fromString $ "org.xen.vm.uuid_" ++ uuid' -- Interface name of xenvm object is a bit dodgy, should probably change it to not include UUID at some point interface = fromString $ "org.xen.vm.uuid_" ++ uuid' object = fromString $ "/org/xen/vm/" ++ uuid' uuid' = uuidStrUnderscore uuid catchNoService :: MonadRpc e m => a -> m a -> m a catchNoService def f = f `catchError` badthings where badthings e = case remoteErrorName `fmap` toRemoteErr e of Just "org.freedesktop.DBus.Error.ServiceUnknown" -> return def _ -> throwError e
jean-edouard/manager
xenmgr/XenMgr/Connect/Xenvm.hs
gpl-2.0
14,597
4
16
4,506
4,193
2,085
2,108
309
5
{-# LANGUAGE MagicHash #-} import GHC.Exts hiding (fromList) import Unsafe.Coerce import Data.Map.Strict newtype Age = Age Int fooAge :: Map Int Int -> Map Int Age fooAge = fmap Age fooCoerce :: Map Int Int -> Map Int Age fooCoerce = fmap coerce fooUnsafeCoerce :: Map Int Int -> Map Int Age fooUnsafeCoerce = fmap unsafeCoerce same :: a -> b -> IO () same x y = case reallyUnsafePtrEquality# (unsafeCoerce x) y of 1# -> putStrLn "yes" _ -> putStrLn "no" main = do let l = fromList [(1,1),(2,2),(3,3)] same (fooAge l) l same (fooCoerce l) l same (fooUnsafeCoerce l) l
shockkolate/containers
tests-ghc/unreliable/mapcoercesmap.hs
bsd-3-clause
598
1
12
132
277
135
142
20
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} -- | Construct a @Plan@ for how to build module Stack.Build.ConstructPlan ( constructPlan ) where import Control.Exception.Lifted import Control.Monad import Control.Monad.Catch (MonadCatch) import Control.Monad.IO.Class import Control.Monad.Logger (MonadLogger) import Control.Monad.RWS.Strict import Control.Monad.Trans.Resource import qualified Data.ByteString.Char8 as S8 import Data.Either import Data.Function import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import qualified Data.Map.Strict as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8, decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Distribution.Package (Dependency (..)) import Distribution.Version (anyVersion) import Network.HTTP.Client.Conduit (HasHttpManager) import Prelude hiding (FilePath, pi, writeFile) import Stack.Build.Cache import Stack.Build.Haddock import Stack.Build.Installed import Stack.Build.Source import Stack.Types.Build import Stack.BuildPlan import Stack.Package import Stack.PackageIndex import Stack.Types data PackageInfo = PIOnlyInstalled Version InstallLocation Installed | PIOnlySource PackageSource | PIBoth PackageSource Installed combineSourceInstalled :: PackageSource -> (Version, InstallLocation, Installed) -> PackageInfo combineSourceInstalled ps (version, location, installed) = assert (piiVersion ps == version) $ assert (piiLocation ps == location) $ case location of -- Always trust something in the snapshot Snap -> PIOnlyInstalled version location installed Local -> PIBoth ps installed type CombinedMap = Map PackageName PackageInfo combineMap :: SourceMap -> InstalledMap -> CombinedMap combineMap = Map.mergeWithKey (\_ s i -> Just $ combineSourceInstalled s i) (fmap PIOnlySource) (fmap (\(v, l, i) -> PIOnlyInstalled v l i)) data AddDepRes = ADRToInstall Task | ADRFound InstallLocation Version Installed deriving Show data W = W { wFinals :: !(Map PackageName (Either ConstructPlanException (Task, LocalPackageTB))) , wInstall :: !(Map Text InstallLocation) -- ^ executable to be installed, and location where the binary is placed , wDirty :: !(Map PackageName Text) -- ^ why a local package is considered dirty , wDeps :: !(Set PackageName) -- ^ Packages which count as dependencies } instance Monoid W where mempty = W mempty mempty mempty mempty mappend (W a b c d) (W w x y z) = W (mappend a w) (mappend b x) (mappend c y) (mappend d z) type M = RWST Ctx W (Map PackageName (Either ConstructPlanException AddDepRes)) IO data Ctx = Ctx { mbp :: !MiniBuildPlan , baseConfigOpts :: !BaseConfigOpts , loadPackage :: !(PackageName -> Version -> Map FlagName Bool -> IO Package) , combinedMap :: !CombinedMap , toolToPackages :: !(Dependency -> Map PackageName VersionRange) , ctxEnvConfig :: !EnvConfig , callStack :: ![PackageName] , extraToBuild :: !(Set PackageName) , latestVersions :: !(Map PackageName Version) , wanted :: !(Set PackageName) } instance HasStackRoot Ctx instance HasPlatform Ctx instance HasConfig Ctx instance HasBuildConfig Ctx where getBuildConfig = getBuildConfig . getEnvConfig instance HasEnvConfig Ctx where getEnvConfig = ctxEnvConfig constructPlan :: forall env m. (MonadCatch m, MonadReader env m, HasEnvConfig env, MonadIO m, MonadLogger m, MonadBaseControl IO m, HasHttpManager env) => MiniBuildPlan -> BaseConfigOpts -> [LocalPackage] -> Set PackageName -- ^ additional packages that must be built -> Set GhcPkgId -- ^ locally registered -> (PackageName -> Version -> Map FlagName Bool -> IO Package) -- ^ load upstream package -> SourceMap -> InstalledMap -> m Plan constructPlan mbp0 baseConfigOpts0 locals extraToBuild0 locallyRegistered loadPackage0 sourceMap installedMap = do menv <- getMinimalEnvOverride caches <- getPackageCaches menv let latest = Map.fromListWith max $ map toTuple $ Map.keys caches econfig <- asks getEnvConfig let onWanted lp = do case lpExeComponents lp of Nothing -> return () Just _ -> void $ addDep False $ packageName $ lpPackage lp case lpTestBench lp of Just tb -> addFinal lp tb Nothing -> return () let inner = do mapM_ onWanted $ filter lpWanted locals mapM_ (addDep False) $ Set.toList extraToBuild0 ((), m, W efinals installExes dirtyReason deps) <- liftIO $ runRWST inner (ctx econfig latest) M.empty let toEither (_, Left e) = Left e toEither (k, Right v) = Right (k, v) (errlibs, adrs) = partitionEithers $ map toEither $ M.toList m (errfinals, finals) = partitionEithers $ map toEither $ M.toList efinals errs = errlibs ++ errfinals if null errs then do let toTask (_, ADRFound _ _ _) = Nothing toTask (name, ADRToInstall task) = Just (name, task) tasks = M.fromList $ mapMaybe toTask adrs takeSubset = case boptsBuildSubset $ bcoBuildOpts baseConfigOpts0 of BSAll -> id BSOnlySnapshot -> stripLocals BSOnlyDependencies -> stripNonDeps deps return $ takeSubset Plan { planTasks = tasks , planFinals = M.fromList finals , planUnregisterLocal = mkUnregisterLocal tasks dirtyReason locallyRegistered , planInstallExes = if boptsInstallExes $ bcoBuildOpts baseConfigOpts0 then installExes else Map.empty } else throwM $ ConstructPlanExceptions errs (bcStackYaml $ getBuildConfig econfig) where ctx econfig latest = Ctx { mbp = mbp0 , baseConfigOpts = baseConfigOpts0 , loadPackage = loadPackage0 , combinedMap = combineMap sourceMap installedMap , toolToPackages = \ (Dependency name _) -> maybe Map.empty (Map.fromSet (\_ -> anyVersion)) $ Map.lookup (S8.pack . packageNameString . fromCabalPackageName $ name) toolMap , ctxEnvConfig = econfig , callStack = [] , extraToBuild = extraToBuild0 , latestVersions = latest , wanted = wantedLocalPackages locals } -- TODO Currently, this will only consider and install tools from the -- snapshot. It will not automatically install build tools from extra-deps -- or local packages. toolMap = getToolMap mbp0 -- | Determine which packages to unregister based on the given tasks and -- already registered local packages mkUnregisterLocal :: Map PackageName Task -> Map PackageName Text -> Set GhcPkgId -> Map GhcPkgId Text mkUnregisterLocal tasks dirtyReason locallyRegistered = Map.unions $ map toUnregisterMap $ Set.toList locallyRegistered where toUnregisterMap gid = case M.lookup name tasks of Nothing -> Map.empty Just _ -> Map.singleton gid $ fromMaybe "likely unregistering due to a version change" $ Map.lookup name dirtyReason where ident = ghcPkgIdPackageIdentifier gid name = packageIdentifierName ident addFinal :: LocalPackage -> LocalPackageTB -> M () addFinal lp lptb = do depsRes <- addPackageDeps False package res <- case depsRes of Left e -> return $ Left e Right (missing, present, _minLoc) -> do ctx <- ask return $ Right (Task { taskProvides = PackageIdentifier (packageName package) (packageVersion package) , taskConfigOpts = TaskConfigOpts missing $ \missing' -> let allDeps = Set.union present missing' in configureOpts (getEnvConfig ctx) (baseConfigOpts ctx) allDeps True -- wanted Local package , taskPresent = present , taskType = TTLocal lp }, lptb) tell mempty { wFinals = Map.singleton (packageName package) res } where package = lptbPackage lptb addDep :: Bool -- ^ is this being used by a dependency? -> PackageName -> M (Either ConstructPlanException AddDepRes) addDep treatAsDep' name = do ctx <- ask let treatAsDep = treatAsDep' || name `Set.notMember` wanted ctx when treatAsDep $ markAsDep name m <- get case Map.lookup name m of Just res -> return res Nothing -> do res <- addDep' treatAsDep name modify $ Map.insert name res return res addDep' :: Bool -- ^ is this being used by a dependency? -> PackageName -> M (Either ConstructPlanException AddDepRes) addDep' treatAsDep name = do ctx <- ask if name `elem` callStack ctx then return $ Left $ DependencyCycleDetected $ name : callStack ctx else local (\ctx' -> ctx' { callStack = name : callStack ctx' }) $ do (addDep'' treatAsDep name) addDep'' :: Bool -- ^ is this being used by a dependency? -> PackageName -> M (Either ConstructPlanException AddDepRes) addDep'' treatAsDep name = do ctx <- ask case Map.lookup name $ combinedMap ctx of -- TODO look up in the package index and see if there's a -- recommendation available Nothing -> return $ Left $ UnknownPackage name Just (PIOnlyInstalled version loc installed) -> do tellExecutablesUpstream name version loc Map.empty -- slightly hacky, no flags since they likely won't affect executable names return $ Right $ ADRFound loc version installed Just (PIOnlySource ps) -> do tellExecutables name ps installPackage treatAsDep name ps Just (PIBoth ps installed) -> do tellExecutables name ps needInstall <- checkNeedInstall treatAsDep name ps installed (wanted ctx) if needInstall then installPackage treatAsDep name ps else return $ Right $ ADRFound (piiLocation ps) (piiVersion ps) installed tellExecutables :: PackageName -> PackageSource -> M () -- TODO merge this with addFinal above? tellExecutables _ (PSLocal lp) | lpWanted lp = tellExecutablesPackage Local $ lpPackage lp | otherwise = return () tellExecutables name (PSUpstream version loc flags) = do tellExecutablesUpstream name version loc flags tellExecutablesUpstream :: PackageName -> Version -> InstallLocation -> Map FlagName Bool -> M () tellExecutablesUpstream name version loc flags = do ctx <- ask when (name `Set.member` extraToBuild ctx) $ do p <- liftIO $ loadPackage ctx name version flags tellExecutablesPackage loc p tellExecutablesPackage :: InstallLocation -> Package -> M () tellExecutablesPackage loc p = do cm <- asks combinedMap -- Determine which components are enabled so we know which ones to copy let myComps = case Map.lookup (packageName p) cm of Nothing -> assert False Set.empty Just (PIOnlyInstalled _ _ _) -> Set.empty Just (PIOnlySource ps) -> goSource ps Just (PIBoth ps _) -> goSource ps goSource (PSLocal lp) = fromMaybe Set.empty $ lpExeComponents lp goSource (PSUpstream _ _ _) = Set.empty tell mempty { wInstall = m myComps } where m myComps = Map.fromList $ map (, loc) $ Set.toList $ filterComps myComps $ packageExes p filterComps myComps x | Set.null myComps = x | otherwise = Set.intersection x $ Set.map toExe myComps toExe x = fromMaybe x $ T.stripPrefix "exe:" x -- TODO There are a lot of duplicated computations below. I've kept that for -- simplicity right now installPackage :: Bool -- ^ is this being used by a dependency? -> PackageName -> PackageSource -> M (Either ConstructPlanException AddDepRes) installPackage treatAsDep name ps = do ctx <- ask package <- psPackage name ps depsRes <- addPackageDeps treatAsDep package case depsRes of Left e -> return $ Left e Right (missing, present, minLoc) -> do return $ Right $ ADRToInstall Task { taskProvides = PackageIdentifier (packageName package) (packageVersion package) , taskConfigOpts = TaskConfigOpts missing $ \missing' -> let allDeps = Set.union present missing' destLoc = piiLocation ps <> minLoc in configureOpts (getEnvConfig ctx) (baseConfigOpts ctx) allDeps (psWanted ps) -- An assertion to check for a recurrence of -- https://github.com/commercialhaskell/stack/issues/345 (assert (destLoc == piiLocation ps) destLoc) package , taskPresent = present , taskType = case ps of PSLocal lp -> TTLocal lp PSUpstream _ loc _ -> TTUpstream package $ loc <> minLoc } checkNeedInstall :: Bool -> PackageName -> PackageSource -> Installed -> Set PackageName -> M Bool checkNeedInstall treatAsDep name ps installed wanted = assert (piiLocation ps == Local) $ do package <- psPackage name ps depsRes <- addPackageDeps treatAsDep package case depsRes of Left _e -> return True -- installPackage will find the error again Right (missing, present, _loc) | Set.null missing -> checkDirtiness ps installed package present wanted | otherwise -> do tell mempty { wDirty = Map.singleton name $ let t = T.intercalate ", " $ map (T.pack . packageNameString . packageIdentifierName) (Set.toList missing) in T.append "missing dependencies: " $ if T.length t < 100 then t else T.take 97 t <> "..." } return True addPackageDeps :: Bool -- ^ is this being used by a dependency? -> Package -> M (Either ConstructPlanException (Set PackageIdentifier, Set GhcPkgId, InstallLocation)) addPackageDeps treatAsDep package = do ctx <- ask deps' <- packageDepsWithTools package deps <- forM (Map.toList deps') $ \(depname, range) -> do eres <- addDep treatAsDep depname let mlatest = Map.lookup depname $ latestVersions ctx case eres of Left e -> let bd = case e of UnknownPackage name -> assert (name == depname) NotInBuildPlan _ -> Couldn'tResolveItsDependencies in return $ Left (depname, (range, mlatest, bd)) Right adr | not $ adrVersion adr `withinRange` range -> return $ Left (depname, (range, mlatest, DependencyMismatch $ adrVersion adr)) Right (ADRToInstall task) -> return $ Right (Set.singleton $ taskProvides task, Set.empty, taskLocation task) Right (ADRFound loc _ (Executable _)) -> return $ Right (Set.empty, Set.empty, loc) Right (ADRFound loc _ (Library gid)) -> return $ Right (Set.empty, Set.singleton gid, loc) case partitionEithers deps of ([], pairs) -> return $ Right $ mconcat pairs (errs, _) -> return $ Left $ DependencyPlanFailures (PackageIdentifier (packageName package) (packageVersion package)) (Map.fromList errs) where adrVersion (ADRToInstall task) = packageIdentifierVersion $ taskProvides task adrVersion (ADRFound _ v _) = v checkDirtiness :: PackageSource -> Installed -> Package -> Set GhcPkgId -> Set PackageName -> M Bool checkDirtiness ps installed package present wanted = do ctx <- ask moldOpts <- tryGetFlagCache installed let configOpts = configureOpts (getEnvConfig ctx) (baseConfigOpts ctx) present (psWanted ps) (piiLocation ps) -- should be Local always package buildOpts = bcoBuildOpts (baseConfigOpts ctx) wantConfigCache = ConfigCache { configCacheOpts = map encodeUtf8 configOpts , configCacheDeps = present , configCacheComponents = case ps of PSLocal lp -> Set.map renderComponent $ lpComponents lp PSUpstream _ _ _ -> Set.empty , configCacheHaddock = shouldHaddockPackage buildOpts wanted (packageName package) || -- Disabling haddocks when old config had haddocks doesn't make dirty. maybe False configCacheHaddock moldOpts } let mreason = case moldOpts of Nothing -> Just "old configure information not found" Just oldOpts | Just reason <- describeConfigDiff oldOpts wantConfigCache -> Just reason | psDirty ps -> Just "local file changes" | otherwise -> Nothing case mreason of Nothing -> return False Just reason -> do tell mempty { wDirty = Map.singleton (packageName package) reason } return True describeConfigDiff :: ConfigCache -> ConfigCache -> Maybe Text describeConfigDiff old new | configCacheDeps old /= configCacheDeps new = Just "dependencies changed" | not $ Set.null newComponents = Just $ "components added: " `T.append` T.intercalate ", " (map (decodeUtf8With lenientDecode) (Set.toList newComponents)) | not (configCacheHaddock old) && configCacheHaddock new = Just "rebuilding with haddocks" | oldOpts /= newOpts = Just $ T.pack $ concat [ "flags changed from " , show oldOpts , " to " , show newOpts ] | otherwise = Nothing where -- options set by stack isStackOpt t = any (`T.isPrefixOf` t) [ "--dependency=" , "--constraint=" , "--package-db=" , "--libdir=" , "--bindir=" , "--enable-tests" , "--enable-benchmarks" ] userOpts = filter (not . isStackOpt) . map (decodeUtf8With lenientDecode) . configCacheOpts (oldOpts, newOpts) = removeMatching (userOpts old) (userOpts new) removeMatching (x:xs) (y:ys) | x == y = removeMatching xs ys removeMatching xs ys = (xs, ys) newComponents = configCacheComponents new `Set.difference` configCacheComponents old psDirty :: PackageSource -> Bool psDirty (PSLocal lp) = lpDirtyFiles lp psDirty (PSUpstream _ _ _) = False -- files never change in an upstream package psWanted :: PackageSource -> Bool psWanted (PSLocal lp) = lpWanted lp psWanted (PSUpstream _ _ _) = False psPackage :: PackageName -> PackageSource -> M Package psPackage _ (PSLocal lp) = return $ lpPackage lp psPackage name (PSUpstream version _ flags) = do ctx <- ask liftIO $ loadPackage ctx name version flags -- | Get all of the dependencies for a given package, including guessed build -- tool dependencies. packageDepsWithTools :: Package -> M (Map PackageName VersionRange) packageDepsWithTools p = do ctx <- ask return $ Map.unionsWith intersectVersionRanges $ packageDeps p : map (toolToPackages ctx) (packageTools p) -- | Strip out anything from the @Plan@ intended for the local database stripLocals :: Plan -> Plan stripLocals plan = plan { planTasks = Map.filter checkTask $ planTasks plan , planFinals = Map.empty , planUnregisterLocal = Map.empty , planInstallExes = Map.filter (/= Local) $ planInstallExes plan } where checkTask task = case taskType task of TTLocal _ -> False TTUpstream _ Local -> False TTUpstream _ Snap -> True stripNonDeps :: Set PackageName -> Plan -> Plan stripNonDeps deps plan = plan { planTasks = Map.filter checkTask $ planTasks plan , planFinals = Map.empty , planInstallExes = Map.empty -- TODO maybe don't disable this? } where checkTask task = packageIdentifierName (taskProvides task) `Set.member` deps markAsDep :: PackageName -> M () markAsDep name = tell mempty { wDeps = Set.singleton name }
Denommus/stack
src/Stack/Build/ConstructPlan.hs
bsd-3-clause
21,884
0
27
7,017
5,590
2,809
2,781
479
9
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module NN.Backend.Torch.Codegen where import Control.Applicative import Control.Lens hiding (assign) import Control.Monad.State.Strict import qualified Data.Foldable as F import Data.Monoid import Gen.Caffe.LayerParameter as LP import Language.Lua.PrettyPrinter import Language.Lua.Syntax import Text.Printf import NN.Backend.Torch.Flat import NN.Backend.Torch.Lua import NN.Backend.Torch.Torch data TorchState = TorchState { _statements :: [Stat], _count :: Int } makeLenses ''TorchState instance Monoid TorchState where mempty = TorchState [] 0 (TorchState ls lc) `mappend` (TorchState rs rc) = TorchState (ls <> rs) (max lc rc) newtype Torch a = Torch { _unTorch :: State TorchState a } deriving (Functor, Applicative, Monad, MonadState TorchState) (<>+) :: MonadState s m => ASetter' s [t] -> t -> m () xs <>+ x = xs <>= [x] imports :: Torch () imports = statements <>+ require "nn" fresh :: String -> Torch String fresh prefix = do c <- use count count += 1 return $ printf "%s%d" prefix c finalize :: Name -> [Exp] -> Torch Block finalize id' criteria' = do criteriaNames' <- forM criteria' $ \exp' -> do name' <- fresh "criteria" statements <>+ assign name' exp' return name' statements' <- use statements return $ Block statements' (Just $ return' <$> id':criteriaNames') insertContainer :: Name -> Exp -> [Flat Exp] -> Torch Name insertContainer prefix containerModule exps' = do name' <- fresh prefix statements <>+ assign name' containerModule forM_ exps' $ \exp' -> do innerName' <- insert exp' statements <>+ methCall name' "add" [var' innerName'] return name' insert :: Flat Exp -> Torch Name insert (Single exp') = do name' <- fresh "mod" statements <>+ assign name' exp' return name' insert (Seq exps') = insertContainer "seq" sequential' exps' where sequential' = torchExp (TorchModule "nn" "Sequential" []) insert (Par exps') = insertContainer "par" depthConcat' exps' where depthConcat' = torchExp (TorchModule "nn" "DepthConcat" []) runTorch :: Flat LayerParameter -> Torch Block runTorch root = do imports id' <- insert innerExps finalize id' criteriaExps where exps = (((torchExp <$>) <$>) . torchModules) <$> root innerExps = (simplify . nested . (inners <$>)) exps criteriaExps = F.concat (criteria <$> exps) lower :: Flat LayerParameter -> Block lower layers = (evalState . _unTorch) (runTorch layers) mempty codegen :: Block -> String codegen block = pprint block & renderPretty 0.4 200 & displayS & \f -> f ""
sjfloat/dnngraph
NN/Backend/Torch/Codegen.hs
bsd-3-clause
2,980
0
14
785
923
471
452
73
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell, CPP #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE PatternGuards #-} -- | Static file serving for WAI. module Network.Wai.Application.Static ( -- * WAI application staticApp -- ** Default Settings , defaultWebAppSettings , webAppSettingsWithLookup , defaultFileServerSettings , embeddedSettings -- ** Settings , StaticSettings , ssLookupFile , ssMkRedirect , ssGetMimeType , ssListing , ssIndices , ssMaxAge , ssRedirectToIndex , ssAddTrailingSlash ) where import Prelude hiding (FilePath) import qualified Network.Wai as W import qualified Network.HTTP.Types as H import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as L import Data.ByteString.Lazy.Char8 () import Control.Monad.IO.Class (liftIO) import Blaze.ByteString.Builder (toByteString) import Data.FileEmbed (embedFile) import Data.Text (Text) import qualified Data.Text as T import Data.Either (rights) import Network.HTTP.Date (parseHTTPDate, epochTimeToHTTPDate, formatHTTPDate) import Data.Monoid (First (First, getFirst), mconcat) import WaiAppStatic.Types import Util import WaiAppStatic.Storage.Filesystem import WaiAppStatic.Storage.Embedded import Network.Mime (MimeType) data StaticResponse = -- | Just the etag hash or Nothing for no etag hash Redirect Pieces (Maybe ByteString) | RawRedirect ByteString | NotFound | FileResponse File H.ResponseHeaders | NotModified -- TODO: add file size | SendContent MimeType L.ByteString | WaiResponse W.Response safeInit :: [a] -> [a] safeInit [] = [] safeInit xs = init xs filterButLast :: (a -> Bool) -> [a] -> [a] filterButLast _ [] = [] filterButLast _ [x] = [x] filterButLast f (x:xs) | f x = x : filterButLast f xs | otherwise = filterButLast f xs -- | Serve an appropriate response for a folder request. serveFolder :: StaticSettings -> Pieces -> W.Request -> Folder -> IO StaticResponse serveFolder ss@StaticSettings {..} pieces req folder@Folder {..} = -- first check if there is an index file in this folder case getFirst $ mconcat $ map (findIndex $ rights folderContents) ssIndices of Just index -> let pieces' = setLast pieces index in case () of () | ssRedirectToIndex -> return $ Redirect pieces' Nothing | Just path <- addTrailingSlash req, ssAddTrailingSlash -> return $ RawRedirect path | otherwise -> -- start the checking process over, with a new set checkPieces ss pieces' req Nothing -> case ssListing of Just _ | Just path <- addTrailingSlash req, ssAddTrailingSlash -> return $ RawRedirect path Just listing -> do -- directory listings turned on, display it builder <- listing pieces folder return $ WaiResponse $ W.responseBuilder H.status200 [ ("Content-Type", "text/html; charset=utf-8") ] builder Nothing -> return $ WaiResponse $ W.responseLBS H.status403 [ ("Content-Type", "text/plain") ] "Directory listings disabled" where setLast :: Pieces -> Piece -> Pieces setLast [] x = [x] setLast [t] x | fromPiece t == "" = [x] setLast (a:b) x = a : setLast b x addTrailingSlash :: W.Request -> Maybe ByteString addTrailingSlash req | S8.null rp = Just "/" | S8.last rp == '/' = Nothing | otherwise = Just $ S8.snoc rp '/' where rp = W.rawPathInfo req noTrailingSlash :: Pieces -> Bool noTrailingSlash [] = False noTrailingSlash [x] = fromPiece x /= "" noTrailingSlash (_:xs) = noTrailingSlash xs findIndex :: [File] -> Piece -> First Piece findIndex files index | index `elem` map fileName files = First $ Just index | otherwise = First Nothing checkPieces :: StaticSettings -> Pieces -- ^ parsed request -> W.Request -> IO StaticResponse -- If we have any empty pieces in the middle of the requested path, generate a -- redirect to get rid of them. checkPieces _ pieces _ | any (T.null . fromPiece) $ safeInit pieces = return $ Redirect (filterButLast (not . T.null . fromPiece) pieces) Nothing checkPieces ss@StaticSettings {..} pieces req = do res <- ssLookupFile pieces case res of LRNotFound -> return NotFound LRFile file -> serveFile ss req file LRFolder folder -> serveFolder ss pieces req folder serveFile :: StaticSettings -> W.Request -> File -> IO StaticResponse serveFile StaticSettings {..} req file -- First check etag values, if turned on | ssUseHash = do mHash <- fileGetHash file case (mHash, lookup "if-none-match" $ W.requestHeaders req) of -- if-none-match matches the actual hash, return a 304 (Just hash, Just lastHash) | hash == lastHash -> return NotModified -- Didn't match, but we have a hash value. Send the file contents -- with an ETag header. -- -- Note: It would be arguably better to next check -- if-modified-since and return a 304 if that indicates a match as -- well. However, the circumstances under which such a situation -- could arise would be very anomolous, and should likely warrant a -- new file being sent anyway. (Just hash, _) -> respond [("ETag", hash)] -- No hash value available, fall back to last modified support. (Nothing, _) -> lastMod -- etag turned off, so jump straight to last modified | otherwise = lastMod where mLastSent = lookup "if-modified-since" (W.requestHeaders req) >>= parseHTTPDate lastMod = case (fmap epochTimeToHTTPDate $ fileGetModified file, mLastSent) of -- File modified time is equal to the if-modified-since header, -- return a 304. -- -- Question: should the comparison be, date <= lastSent? (Just mdate, Just lastSent) | mdate == lastSent -> return NotModified -- Did not match, but we have a new last-modified header (Just mdate, _) -> respond [("last-modified", formatHTTPDate mdate)] -- No modification time available (Nothing, _) -> respond [] -- Send a file response with the additional weak headers provided. respond headers = return $ FileResponse file $ cacheControl ssMaxAge headers -- | Return a difference list of headers based on the specified MaxAge. -- -- This function will return both Cache-Control and Expires headers, as -- relevant. cacheControl :: MaxAge -> (H.ResponseHeaders -> H.ResponseHeaders) cacheControl maxage = headerCacheControl . headerExpires where ccInt = case maxage of NoMaxAge -> Nothing MaxAgeSeconds i -> Just i MaxAgeForever -> Just oneYear oneYear :: Int oneYear = 60 * 60 * 24 * 365 headerCacheControl = case ccInt of Nothing -> id Just i -> (:) ("Cache-Control", S8.append "public, max-age=" $ S8.pack $ show i) headerExpires = case maxage of NoMaxAge -> id MaxAgeSeconds _ -> id -- FIXME MaxAgeForever -> (:) ("Expires", "Thu, 31 Dec 2037 23:55:55 GMT") -- | Turn a @StaticSettings@ into a WAI application. staticApp :: StaticSettings -> W.Application staticApp set req = staticAppPieces set (W.pathInfo req) req staticAppPieces :: StaticSettings -> [Text] -> W.Application staticAppPieces _ _ req sendResponse | notElem (W.requestMethod req) ["GET", "HEAD"] = sendResponse $ W.responseLBS H.status405 [("Content-Type", "text/plain")] "Only GET or HEAD is supported" staticAppPieces _ [".hidden", "folder.png"] _ sendResponse = sendResponse $ W.responseLBS H.status200 [("Content-Type", "image/png")] $ L.fromChunks [$(embedFile "images/folder.png")] staticAppPieces _ [".hidden", "haskell.png"] _ sendResponse = sendResponse $ W.responseLBS H.status200 [("Content-Type", "image/png")] $ L.fromChunks [$(embedFile "images/haskell.png")] staticAppPieces ss rawPieces req sendResponse = liftIO $ do case toPieces rawPieces of Just pieces -> checkPieces ss pieces req >>= response Nothing -> sendResponse $ W.responseLBS H.status403 [ ("Content-Type", "text/plain") ] "Forbidden" where response :: StaticResponse -> IO W.ResponseReceived response (FileResponse file ch) = do mimetype <- ssGetMimeType ss file let filesize = fileGetSize file let headers = ("Content-Type", mimetype) -- Let Warp provide the content-length, since it takes -- range requests into account -- : ("Content-Length", S8.pack $ show filesize) : ch sendResponse $ fileToResponse file H.status200 headers response NotModified = sendResponse $ W.responseLBS H.status304 [] "" response (SendContent mt lbs) = do -- TODO: set caching headers sendResponse $ W.responseLBS H.status200 [ ("Content-Type", mt) -- TODO: set Content-Length ] lbs response (Redirect pieces' mHash) = do let loc = (ssMkRedirect ss) pieces' $ toByteString (H.encodePathSegments $ map fromPiece pieces') let qString = case mHash of Just hash -> replace "etag" (Just hash) (W.queryString req) Nothing -> remove "etag" (W.queryString req) sendResponse $ W.responseLBS H.status301 [ ("Content-Type", "text/plain") , ("Location", S8.append loc $ H.renderQuery True qString) ] "Redirect" response (RawRedirect path) = sendResponse $ W.responseLBS H.status301 [ ("Content-Type", "text/plain") , ("Location", path) ] "Redirect" response NotFound = sendResponse $ W.responseLBS H.status404 [ ("Content-Type", "text/plain") ] "File not found" response (WaiResponse r) = sendResponse r
AndrewRademacher/wai
wai-app-static/Network/Wai/Application/Static.hs
mit
10,596
0
18
3,049
2,503
1,306
1,197
195
9
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Dependency -- Copyright : (c) David Himmelstrup 2005, -- Bjorn Bringert 2007 -- Duncan Coutts 2008 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Top level interface to dependency resolution. ----------------------------------------------------------------------------- module Distribution.Client.Dependency ( -- * The main package dependency resolver chooseSolver, resolveDependencies, Progress(..), foldProgress, -- * Alternate, simple resolver that does not do dependencies recursively resolveWithoutDependencies, -- * Constructing resolver policies DepResolverParams(..), PackageConstraint(..), PackagesPreferenceDefault(..), PackagePreference(..), InstalledPreference(..), -- ** Standard policy standardInstallPolicy, PackageSpecifier(..), -- ** Sandbox policy applySandboxInstallPolicy, -- ** Extra policy options dontUpgradeNonUpgradeablePackages, hideBrokenInstalledPackages, upgradeDependencies, reinstallTargets, -- ** Policy utils addConstraints, addPreferences, setPreferenceDefault, setReorderGoals, setIndependentGoals, setAvoidReinstalls, setShadowPkgs, setStrongFlags, setMaxBackjumps, addSourcePackages, hideInstalledPackagesSpecificByInstalledPackageId, hideInstalledPackagesSpecificBySourcePackageId, hideInstalledPackagesAllVersions, removeUpperBounds ) where import Distribution.Client.Dependency.TopDown ( topDownResolver ) import Distribution.Client.Dependency.Modular ( modularResolver, SolverConfig(..) ) import qualified Distribution.Client.PackageIndex as PackageIndex import Distribution.Simple.PackageIndex (InstalledPackageIndex) import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex import qualified Distribution.Client.InstallPlan as InstallPlan import Distribution.Client.InstallPlan (InstallPlan) import Distribution.Client.Types ( SourcePackageDb(SourcePackageDb) , SourcePackage(..) ) import Distribution.Client.Dependency.Types ( PreSolver(..), Solver(..), DependencyResolver, PackageConstraint(..) , debugPackageConstraint , AllowNewer(..), PackagePreferences(..), InstalledPreference(..) , PackagesPreferenceDefault(..) , Progress(..), foldProgress ) import Distribution.Client.Sandbox.Types ( SandboxPackageInfo(..) ) import Distribution.Client.Targets import qualified Distribution.InstalledPackageInfo as Installed import Distribution.Package ( PackageName(..), PackageId, Package(..), packageName, packageVersion , InstalledPackageId, Dependency(Dependency)) import qualified Distribution.PackageDescription as PD ( PackageDescription(..), GenericPackageDescription(..) , Library(..), Executable(..), TestSuite(..), Benchmark(..), CondTree) import Distribution.PackageDescription (BuildInfo(targetBuildDepends)) import Distribution.PackageDescription.Configuration (mapCondTree) import Distribution.Version ( Version(..), VersionRange, anyVersion, thisVersion, withinRange , removeUpperBound, simplifyVersionRange ) import Distribution.Compiler ( CompilerId(..), CompilerInfo(..), CompilerFlavor(..) ) import Distribution.System ( Platform ) import Distribution.Simple.Utils ( comparing, warn, info ) import Distribution.Text ( display ) import Distribution.Verbosity ( Verbosity ) import Data.List (maximumBy, foldl', intercalate) import Data.Maybe (fromMaybe) import qualified Data.Map as Map import qualified Data.Set as Set import Data.Set (Set) -- ------------------------------------------------------------ -- * High level planner policy -- ------------------------------------------------------------ -- | The set of parameters to the dependency resolver. These parameters are -- relatively low level but many kinds of high level policies can be -- implemented in terms of adjustments to the parameters. -- data DepResolverParams = DepResolverParams { depResolverTargets :: [PackageName], depResolverConstraints :: [PackageConstraint], depResolverPreferences :: [PackagePreference], depResolverPreferenceDefault :: PackagesPreferenceDefault, depResolverInstalledPkgIndex :: InstalledPackageIndex, depResolverSourcePkgIndex :: PackageIndex.PackageIndex SourcePackage, depResolverReorderGoals :: Bool, depResolverIndependentGoals :: Bool, depResolverAvoidReinstalls :: Bool, depResolverShadowPkgs :: Bool, depResolverStrongFlags :: Bool, depResolverMaxBackjumps :: Maybe Int } debugDepResolverParams :: DepResolverParams -> String debugDepResolverParams p = "targets: " ++ intercalate ", " (map display (depResolverTargets p)) ++ "\nconstraints: " ++ concatMap (("\n " ++) . debugPackageConstraint) (depResolverConstraints p) ++ "\npreferences: " ++ concatMap (("\n " ++) . debugPackagePreference) (depResolverPreferences p) ++ "\nstrategy: " ++ show (depResolverPreferenceDefault p) -- | A package selection preference for a particular package. -- -- Preferences are soft constraints that the dependency resolver should try to -- respect where possible. It is not specified if preferences on some packages -- are more important than others. -- data PackagePreference = -- | A suggested constraint on the version number. PackageVersionPreference PackageName VersionRange -- | If we prefer versions of packages that are already installed. | PackageInstalledPreference PackageName InstalledPreference -- | Provide a textual representation of a package preference -- for debugging purposes. -- debugPackagePreference :: PackagePreference -> String debugPackagePreference (PackageVersionPreference pn vr) = display pn ++ " " ++ display (simplifyVersionRange vr) debugPackagePreference (PackageInstalledPreference pn ip) = display pn ++ " " ++ show ip basicDepResolverParams :: InstalledPackageIndex -> PackageIndex.PackageIndex SourcePackage -> DepResolverParams basicDepResolverParams installedPkgIndex sourcePkgIndex = DepResolverParams { depResolverTargets = [], depResolverConstraints = [], depResolverPreferences = [], depResolverPreferenceDefault = PreferLatestForSelected, depResolverInstalledPkgIndex = installedPkgIndex, depResolverSourcePkgIndex = sourcePkgIndex, depResolverReorderGoals = False, depResolverIndependentGoals = False, depResolverAvoidReinstalls = False, depResolverShadowPkgs = False, depResolverStrongFlags = False, depResolverMaxBackjumps = Nothing } addTargets :: [PackageName] -> DepResolverParams -> DepResolverParams addTargets extraTargets params = params { depResolverTargets = extraTargets ++ depResolverTargets params } addConstraints :: [PackageConstraint] -> DepResolverParams -> DepResolverParams addConstraints extraConstraints params = params { depResolverConstraints = extraConstraints ++ depResolverConstraints params } addPreferences :: [PackagePreference] -> DepResolverParams -> DepResolverParams addPreferences extraPreferences params = params { depResolverPreferences = extraPreferences ++ depResolverPreferences params } setPreferenceDefault :: PackagesPreferenceDefault -> DepResolverParams -> DepResolverParams setPreferenceDefault preferenceDefault params = params { depResolverPreferenceDefault = preferenceDefault } setReorderGoals :: Bool -> DepResolverParams -> DepResolverParams setReorderGoals b params = params { depResolverReorderGoals = b } setIndependentGoals :: Bool -> DepResolverParams -> DepResolverParams setIndependentGoals b params = params { depResolverIndependentGoals = b } setAvoidReinstalls :: Bool -> DepResolverParams -> DepResolverParams setAvoidReinstalls b params = params { depResolverAvoidReinstalls = b } setShadowPkgs :: Bool -> DepResolverParams -> DepResolverParams setShadowPkgs b params = params { depResolverShadowPkgs = b } setStrongFlags :: Bool -> DepResolverParams -> DepResolverParams setStrongFlags b params = params { depResolverStrongFlags = b } setMaxBackjumps :: Maybe Int -> DepResolverParams -> DepResolverParams setMaxBackjumps n params = params { depResolverMaxBackjumps = n } -- | Some packages are specific to a given compiler version and should never be -- upgraded. dontUpgradeNonUpgradeablePackages :: DepResolverParams -> DepResolverParams dontUpgradeNonUpgradeablePackages params = addConstraints extraConstraints params where extraConstraints = [ PackageConstraintInstalled pkgname | all (/=PackageName "base") (depResolverTargets params) , pkgname <- map PackageName [ "base", "ghc-prim", "integer-gmp" , "integer-simple" ] , isInstalled pkgname ] -- TODO: the top down resolver chokes on the base constraints -- below when there are no targets and thus no dep on base. -- Need to refactor constraints separate from needing packages. isInstalled = not . null . InstalledPackageIndex.lookupPackageName (depResolverInstalledPkgIndex params) addSourcePackages :: [SourcePackage] -> DepResolverParams -> DepResolverParams addSourcePackages pkgs params = params { depResolverSourcePkgIndex = foldl (flip PackageIndex.insert) (depResolverSourcePkgIndex params) pkgs } hideInstalledPackagesSpecificByInstalledPackageId :: [InstalledPackageId] -> DepResolverParams -> DepResolverParams hideInstalledPackagesSpecificByInstalledPackageId pkgids params = --TODO: this should work using exclude constraints instead params { depResolverInstalledPkgIndex = foldl' (flip InstalledPackageIndex.deleteInstalledPackageId) (depResolverInstalledPkgIndex params) pkgids } hideInstalledPackagesSpecificBySourcePackageId :: [PackageId] -> DepResolverParams -> DepResolverParams hideInstalledPackagesSpecificBySourcePackageId pkgids params = --TODO: this should work using exclude constraints instead params { depResolverInstalledPkgIndex = foldl' (flip InstalledPackageIndex.deleteSourcePackageId) (depResolverInstalledPkgIndex params) pkgids } hideInstalledPackagesAllVersions :: [PackageName] -> DepResolverParams -> DepResolverParams hideInstalledPackagesAllVersions pkgnames params = --TODO: this should work using exclude constraints instead params { depResolverInstalledPkgIndex = foldl' (flip InstalledPackageIndex.deletePackageName) (depResolverInstalledPkgIndex params) pkgnames } hideBrokenInstalledPackages :: DepResolverParams -> DepResolverParams hideBrokenInstalledPackages params = hideInstalledPackagesSpecificByInstalledPackageId pkgids params where pkgids = map Installed.installedPackageId . InstalledPackageIndex.reverseDependencyClosure (depResolverInstalledPkgIndex params) . map (Installed.installedPackageId . fst) . InstalledPackageIndex.brokenPackages $ depResolverInstalledPkgIndex params -- | Remove upper bounds in dependencies using the policy specified by the -- 'AllowNewer' argument (all/some/none). removeUpperBounds :: AllowNewer -> DepResolverParams -> DepResolverParams removeUpperBounds allowNewer params = params { -- NB: It's important to apply 'removeUpperBounds' after -- 'addSourcePackages'. Otherwise, the packages inserted by -- 'addSourcePackages' won't have upper bounds in dependencies relaxed. depResolverSourcePkgIndex = sourcePkgIndex' } where sourcePkgIndex = depResolverSourcePkgIndex params sourcePkgIndex' = case allowNewer of AllowNewerNone -> sourcePkgIndex AllowNewerAll -> fmap relaxAllPackageDeps sourcePkgIndex AllowNewerSome pkgs -> fmap (relaxSomePackageDeps pkgs) sourcePkgIndex relaxAllPackageDeps :: SourcePackage -> SourcePackage relaxAllPackageDeps = onAllBuildDepends doRelax where doRelax (Dependency pkgName verRange) = Dependency pkgName (removeUpperBound verRange) relaxSomePackageDeps :: [PackageName] -> SourcePackage -> SourcePackage relaxSomePackageDeps pkgNames = onAllBuildDepends doRelax where doRelax d@(Dependency pkgName verRange) | pkgName `elem` pkgNames = Dependency pkgName (removeUpperBound verRange) | otherwise = d -- Walk a 'GenericPackageDescription' and apply 'f' to all 'build-depends' -- fields. onAllBuildDepends :: (Dependency -> Dependency) -> SourcePackage -> SourcePackage onAllBuildDepends f srcPkg = srcPkg' where gpd = packageDescription srcPkg pd = PD.packageDescription gpd condLib = PD.condLibrary gpd condExes = PD.condExecutables gpd condTests = PD.condTestSuites gpd condBenchs = PD.condBenchmarks gpd f' = onBuildInfo f onBuildInfo g bi = bi { targetBuildDepends = map g (targetBuildDepends bi) } onLibrary lib = lib { PD.libBuildInfo = f' $ PD.libBuildInfo lib } onExecutable exe = exe { PD.buildInfo = f' $ PD.buildInfo exe } onTestSuite tst = tst { PD.testBuildInfo = f' $ PD.testBuildInfo tst } onBenchmark bmk = bmk { PD.benchmarkBuildInfo = f' $ PD.benchmarkBuildInfo bmk } srcPkg' = srcPkg { packageDescription = gpd' } gpd' = gpd { PD.packageDescription = pd', PD.condLibrary = condLib', PD.condExecutables = condExes', PD.condTestSuites = condTests', PD.condBenchmarks = condBenchs' } pd' = pd { PD.buildDepends = map f (PD.buildDepends pd), PD.library = fmap onLibrary (PD.library pd), PD.executables = map onExecutable (PD.executables pd), PD.testSuites = map onTestSuite (PD.testSuites pd), PD.benchmarks = map onBenchmark (PD.benchmarks pd) } condLib' = fmap (onCondTree onLibrary) condLib condExes' = map (mapSnd $ onCondTree onExecutable) condExes condTests' = map (mapSnd $ onCondTree onTestSuite) condTests condBenchs' = map (mapSnd $ onCondTree onBenchmark) condBenchs mapSnd :: (a -> b) -> (c,a) -> (c,b) mapSnd = fmap onCondTree :: (a -> b) -> PD.CondTree v [Dependency] a -> PD.CondTree v [Dependency] b onCondTree g = mapCondTree g (map f) id upgradeDependencies :: DepResolverParams -> DepResolverParams upgradeDependencies = setPreferenceDefault PreferAllLatest reinstallTargets :: DepResolverParams -> DepResolverParams reinstallTargets params = hideInstalledPackagesAllVersions (depResolverTargets params) params standardInstallPolicy :: InstalledPackageIndex -> SourcePackageDb -> [PackageSpecifier SourcePackage] -> DepResolverParams standardInstallPolicy installedPkgIndex (SourcePackageDb sourcePkgIndex sourcePkgPrefs) pkgSpecifiers = addPreferences [ PackageVersionPreference name ver | (name, ver) <- Map.toList sourcePkgPrefs ] . addConstraints (concatMap pkgSpecifierConstraints pkgSpecifiers) . addTargets (map pkgSpecifierTarget pkgSpecifiers) . hideInstalledPackagesSpecificBySourcePackageId [ packageId pkg | SpecificSourcePackage pkg <- pkgSpecifiers ] . addSourcePackages [ pkg | SpecificSourcePackage pkg <- pkgSpecifiers ] $ basicDepResolverParams installedPkgIndex sourcePkgIndex applySandboxInstallPolicy :: SandboxPackageInfo -> DepResolverParams -> DepResolverParams applySandboxInstallPolicy (SandboxPackageInfo modifiedDeps otherDeps allSandboxPkgs _allDeps) params = addPreferences [ PackageInstalledPreference n PreferInstalled | n <- installedNotModified ] . addTargets installedNotModified . addPreferences [ PackageVersionPreference (packageName pkg) (thisVersion (packageVersion pkg)) | pkg <- otherDeps ] . addConstraints [ PackageConstraintVersion (packageName pkg) (thisVersion (packageVersion pkg)) | pkg <- modifiedDeps ] . addTargets [ packageName pkg | pkg <- modifiedDeps ] . hideInstalledPackagesSpecificBySourcePackageId [ packageId pkg | pkg <- modifiedDeps ] -- We don't need to add source packages for add-source deps to the -- 'installedPkgIndex' since 'getSourcePackages' did that for us. $ params where installedPkgIds = map fst . InstalledPackageIndex.allPackagesBySourcePackageId $ allSandboxPkgs modifiedPkgIds = map packageId modifiedDeps installedNotModified = [ packageName pkg | pkg <- installedPkgIds, pkg `notElem` modifiedPkgIds ] -- ------------------------------------------------------------ -- * Interface to the standard resolver -- ------------------------------------------------------------ chooseSolver :: Verbosity -> PreSolver -> CompilerInfo -> IO Solver chooseSolver _ AlwaysTopDown _ = return TopDown chooseSolver _ AlwaysModular _ = return Modular chooseSolver verbosity Choose cinfo = do let (CompilerId f v) = compilerInfoId cinfo chosenSolver | f == GHC && v <= Version [7] [] = TopDown | otherwise = Modular msg TopDown = warn verbosity "Falling back to topdown solver for GHC < 7." msg Modular = info verbosity "Choosing modular solver." msg chosenSolver return chosenSolver runSolver :: Solver -> SolverConfig -> DependencyResolver runSolver TopDown = const topDownResolver -- TODO: warn about unsupported options runSolver Modular = modularResolver -- | Run the dependency solver. -- -- Since this is potentially an expensive operation, the result is wrapped in a -- a 'Progress' structure that can be unfolded to provide progress information, -- logging messages and the final result or an error. -- resolveDependencies :: Platform -> CompilerInfo -> Solver -> DepResolverParams -> Progress String String InstallPlan --TODO: is this needed here? see dontUpgradeNonUpgradeablePackages resolveDependencies platform comp _solver params | null (depResolverTargets params) = return (mkInstallPlan platform comp []) resolveDependencies platform comp solver params = Step (debugDepResolverParams finalparams) $ fmap (mkInstallPlan platform comp) $ runSolver solver (SolverConfig reorderGoals indGoals noReinstalls shadowing strFlags maxBkjumps) platform comp installedPkgIndex sourcePkgIndex preferences constraints targets where finalparams @ (DepResolverParams targets constraints prefs defpref installedPkgIndex sourcePkgIndex reorderGoals indGoals noReinstalls shadowing strFlags maxBkjumps) = dontUpgradeNonUpgradeablePackages -- TODO: -- The modular solver can properly deal with broken -- packages and won't select them. So the -- 'hideBrokenInstalledPackages' function should be moved -- into a module that is specific to the top-down solver. . (if solver /= Modular then hideBrokenInstalledPackages else id) $ params preferences = interpretPackagesPreference (Set.fromList targets) defpref prefs -- | Make an install plan from the output of the dep resolver. -- It checks that the plan is valid, or it's an error in the dep resolver. -- mkInstallPlan :: Platform -> CompilerInfo -> [InstallPlan.PlanPackage] -> InstallPlan mkInstallPlan platform comp pkgIndex = let index = InstalledPackageIndex.fromList pkgIndex in case InstallPlan.new platform comp index of Right plan -> plan Left problems -> error $ unlines $ "internal error: could not construct a valid install plan." : "The proposed (invalid) plan contained the following problems:" : map InstallPlan.showPlanProblem problems ++ "Proposed plan:" : [InstallPlan.showPlanIndex index] -- | Give an interpretation to the global 'PackagesPreference' as -- specific per-package 'PackageVersionPreference'. -- interpretPackagesPreference :: Set PackageName -> PackagesPreferenceDefault -> [PackagePreference] -> (PackageName -> PackagePreferences) interpretPackagesPreference selected defaultPref prefs = \pkgname -> PackagePreferences (versionPref pkgname) (installPref pkgname) where versionPref pkgname = fromMaybe anyVersion (Map.lookup pkgname versionPrefs) versionPrefs = Map.fromList [ (pkgname, pref) | PackageVersionPreference pkgname pref <- prefs ] installPref pkgname = fromMaybe (installPrefDefault pkgname) (Map.lookup pkgname installPrefs) installPrefs = Map.fromList [ (pkgname, pref) | PackageInstalledPreference pkgname pref <- prefs ] installPrefDefault = case defaultPref of PreferAllLatest -> \_ -> PreferLatest PreferAllInstalled -> \_ -> PreferInstalled PreferLatestForSelected -> \pkgname -> -- When you say cabal install foo, what you really mean is, prefer the -- latest version of foo, but the installed version of everything else if pkgname `Set.member` selected then PreferLatest else PreferInstalled -- ------------------------------------------------------------ -- * Simple resolver that ignores dependencies -- ------------------------------------------------------------ -- | A simplistic method of resolving a list of target package names to -- available packages. -- -- Specifically, it does not consider package dependencies at all. Unlike -- 'resolveDependencies', no attempt is made to ensure that the selected -- packages have dependencies that are satisfiable or consistent with -- each other. -- -- It is suitable for tasks such as selecting packages to download for user -- inspection. It is not suitable for selecting packages to install. -- -- Note: if no installed package index is available, it is OK to pass 'mempty'. -- It simply means preferences for installed packages will be ignored. -- resolveWithoutDependencies :: DepResolverParams -> Either [ResolveNoDepsError] [SourcePackage] resolveWithoutDependencies (DepResolverParams targets constraints prefs defpref installedPkgIndex sourcePkgIndex _reorderGoals _indGoals _avoidReinstalls _shadowing _strFlags _maxBjumps) = collectEithers (map selectPackage targets) where selectPackage :: PackageName -> Either ResolveNoDepsError SourcePackage selectPackage pkgname | null choices = Left $! ResolveUnsatisfiable pkgname requiredVersions | otherwise = Right $! maximumBy bestByPrefs choices where -- Constraints requiredVersions = packageConstraints pkgname pkgDependency = Dependency pkgname requiredVersions choices = PackageIndex.lookupDependency sourcePkgIndex pkgDependency -- Preferences PackagePreferences preferredVersions preferInstalled = packagePreferences pkgname bestByPrefs = comparing $ \pkg -> (installPref pkg, versionPref pkg, packageVersion pkg) installPref = case preferInstalled of PreferLatest -> const False PreferInstalled -> not . null . InstalledPackageIndex.lookupSourcePackageId installedPkgIndex . packageId versionPref pkg = packageVersion pkg `withinRange` preferredVersions packageConstraints :: PackageName -> VersionRange packageConstraints pkgname = Map.findWithDefault anyVersion pkgname packageVersionConstraintMap packageVersionConstraintMap = Map.fromList [ (name, range) | PackageConstraintVersion name range <- constraints ] packagePreferences :: PackageName -> PackagePreferences packagePreferences = interpretPackagesPreference (Set.fromList targets) defpref prefs collectEithers :: [Either a b] -> Either [a] [b] collectEithers = collect . partitionEithers where collect ([], xs) = Right xs collect (errs,_) = Left errs partitionEithers :: [Either a b] -> ([a],[b]) partitionEithers = foldr (either left right) ([],[]) where left a (l, r) = (a:l, r) right a (l, r) = (l, a:r) -- | Errors for 'resolveWithoutDependencies'. -- data ResolveNoDepsError = -- | A package name which cannot be resolved to a specific package. -- Also gives the constraint on the version and whether there was -- a constraint on the package being installed. ResolveUnsatisfiable PackageName VersionRange instance Show ResolveNoDepsError where show (ResolveUnsatisfiable name ver) = "There is no available version of " ++ display name ++ " that satisfies " ++ display (simplifyVersionRange ver)
DavidAlphaFox/ghc
libraries/Cabal/cabal-install/Distribution/Client/Dependency.hs
bsd-3-clause
26,991
1
16
6,898
4,519
2,488
2,031
460
4
module C2(myFringe, Tree(..), SameOrNot(..)) where data Tree a = Leaf a | Branch (Tree a) (Tree a) sumTree:: (Num a) => Tree a -> a sumTree (Leaf x ) = x sumTree (Branch left right) = sumTree left + sumTree right myFringe:: Tree a -> [a] myFringe (Leaf x ) = [x] myFringe (Branch left right) = myFringe left class SameOrNot a where isSame :: a -> a -> Bool isNotSame :: a -> a -> Bool instance SameOrNot Int where isSame a b = a == b isNotSame a b = a /= b
kmate/HaRe
old/testing/moveDefBtwMods/C2_TokOut.hs
bsd-3-clause
505
0
8
143
235
124
111
14
1
{-# LANGUAGE Arrows #-} module Arrow where import Control.Arrow import qualified Control.Category as Cat addA :: Arrow a => a b Int -> a b Int -> a b Int addA f g = proc x -> do y <- f -< x z <- g -< x returnA -< y + z 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)) -- | 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 (+) mean3 :: Fractional a => Circuit a a mean3 = proc value -> do (t, n) <- (| (&&&) (total -< value) (total -< 1) |) returnA -< t / n
olsner/ghc
testsuite/tests/printer/Ppr002.hs
bsd-3-clause
1,381
4
14
437
636
341
295
-1
-1
module SPARC.CodeGen.Base ( InstrBlock, CondCode(..), ChildCode64(..), Amode(..), Register(..), setFormatOfRegister, getRegisterReg, mangleIndexTree ) where import SPARC.Instr import SPARC.Cond import SPARC.AddrMode import SPARC.Regs import Format import Reg import CodeGen.Platform import DynFlags import Cmm import PprCmmExpr () import Platform import Outputable import OrdList -------------------------------------------------------------------------------- -- | 'InstrBlock's are the insn sequences generated by the insn selectors. -- They are really trees of insns to facilitate fast appending, where a -- left-to-right traversal yields the insns in the correct order. -- type InstrBlock = OrdList Instr -- | Condition codes passed up the tree. -- data CondCode = CondCode Bool Cond InstrBlock -- | a.k.a "Register64" -- Reg is the lower 32-bit temporary which contains the result. -- Use getHiVRegFromLo to find the other VRegUnique. -- -- Rules of this simplified insn selection game are therefore that -- the returned Reg may be modified -- data ChildCode64 = ChildCode64 InstrBlock Reg -- | Holds code that references a memory address. data Amode = Amode -- the AddrMode we can use in the instruction -- that does the real load\/store. AddrMode -- other setup code we have to run first before we can use the -- above AddrMode. InstrBlock -------------------------------------------------------------------------------- -- | Code to produce a result into a register. -- If the result must go in a specific register, it comes out as Fixed. -- Otherwise, the parent can decide which register to put it in. -- data Register = Fixed Format Reg InstrBlock | Any Format (Reg -> InstrBlock) -- | Change the format field in a Register. setFormatOfRegister :: Register -> Format -> Register setFormatOfRegister reg format = case reg of Fixed _ reg code -> Fixed format reg code Any _ codefn -> Any format codefn -------------------------------------------------------------------------------- -- | Grab the Reg for a CmmReg getRegisterReg :: Platform -> CmmReg -> Reg getRegisterReg _ (CmmLocal (LocalReg u pk)) = RegVirtual $ mkVirtualReg u (cmmTypeFormat pk) getRegisterReg platform (CmmGlobal mid) = case globalRegMaybe platform mid of Just reg -> RegReal reg Nothing -> pprPanic "SPARC.CodeGen.Base.getRegisterReg: global is in memory" (ppr $ CmmGlobal mid) -- Expand CmmRegOff. ToDo: should we do it this way around, or convert -- CmmExprs into CmmRegOff? mangleIndexTree :: DynFlags -> CmmExpr -> CmmExpr mangleIndexTree dflags (CmmRegOff reg off) = CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)] where width = typeWidth (cmmRegType dflags reg) mangleIndexTree _ _ = panic "SPARC.CodeGen.Base.mangleIndexTree: no match"
wxwxwwxxx/ghc
compiler/nativeGen/SPARC/CodeGen/Base.hs
bsd-3-clause
3,202
0
11
840
473
267
206
58
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE TemplateHaskell #-} module Tests.Math.Hclaws.Systems.TveitoWinther1995_3 ( tests ) where import Test.Tasty (TestTree, testGroup) import qualified Test.Tasty.QuickCheck as QC import qualified Test.Tasty.SmallCheck as SC import Test.Tasty.HUnit (testCase, (@?=)) import Test.Tasty.TH (testGroupGenerator) import Test.Curves import Math.Hclaws.ConservationLaws import qualified Math.Hclaws.Systems.TveitoWinther1995_3 as TW tests :: TestTree tests = testGroup "Math.Hclaws.Systems.TveitoWinther1995_3" [properties, unitTests] properties :: TestTree properties = testGroup "Properties" [ ] unitTests :: TestTree unitTests = testGroup "UnitTests" $ [ waveFanTestGroup (solveRiemann TW.system [0.3, 1] [0.2, 1.2]) TW.system "left region 1" , waveFanTestGroup (solveRiemann TW.system [0.3, 1] [0.9, 0.5]) TW.system "left region 2" , waveFanTestGroup (solveRiemann TW.system [0.3, 1] [0.2, 0.05]) TW.system "left region 3" , waveFanTestGroup (solveRiemann TW.system [0.7, 1] [0.8, 0.5]) TW.system "right region 2" , waveFanTestGroup (solveRiemann TW.system [0.7, 1] [0.1, 1.2]) TW.system "right region 1" , waveFanTestGroup (solveRiemann TW.system [0.7, 1] [0.1, 0.1]) TW.system "right region 3" , waveFanTestGroup (solveRiemann TW.system [0.5, 0.5] [0.5, 0.5]) TW.system "constant" ]
mikebenfield/hclaws
test/Tests/Math/Hclaws/Systems/TveitoWinther1995_3.hs
isc
1,581
0
10
388
403
238
165
50
1
module Utils ( module Utils ) where import Utils.Calendar as Utils import Utils.Email as Utils import Utils.Ldap as Utils import Utils.Protobuf as Utils import Utils.Session as Utils import Utils.Visual as Utils
dgonyeo/lambdollars
Utils.hs
mit
231
0
4
50
52
37
15
8
0
{-# LANGUAGE RankNTypes #-} module Evo.Type where import System.Random.MWC import Data.STRef import Control.Monad.ST import Control.Monad.Reader type Genotype = [Bool] type Phenotype = Genotype type Population = [Genotype] data Ref s = Ref { gen :: STRef s (GenST s) } type Evo s a = ReaderT (Ref s) (ST s) a getGen :: Evo s (GenST s) getGen = asks gen >>= lift . readSTRef putGen :: GenST s -> Evo s () putGen g = do ref <- asks gen lift $ writeSTRef ref g rand :: Variate a => Evo s a rand = getGen >>= lift . uniform randR :: Variate a => (a, a) -> Evo s a randR (a, b) = getGen >>= lift . uniformR (a, b) runEvo :: Seed -> (forall s. Evo s a) -> a runEvo seed f = runST $ do genRef <- restore seed >>= newSTRef runReaderT f (Ref genRef) -- import Control.Monad.Reader -- import Control.Monad.State -- import Control.Monad.Base -- import Control.Applicative (Applicative) -- import Control.Monad.Trans.Control -- newtype EvoM a = EvoM { runEvoM :: StateT Seed (ReaderT Parameter IO) a } -- deriving (Monad, Functor, Applicative, MonadIO, MonadState Seed, MonadReader Parameter, MonadBase IO) -- instance (MonadBaseControl IO) EvoM where -- newtype StM EvoM a = StMEvo { unStMCEvo :: StM (StateT Seed (ReaderT Parameter IO)) a } -- liftBaseWith f = EvoM (liftBaseWith (\run -> f (liftM StMEvo . run . runEvoM))) -- restoreM = EvoM . restoreM . unStMCEvo --data Parameter = Parameter -- { _populationSize :: Int -- , _learningRate :: Double -- , _discountFactor :: Double -- , _errorBound :: Double -- , _falloffRate :: Double -- , _initialPrediction :: Double -- , _initialError :: Double -- , _initialFitness :: Double -- , _chromosomeLength :: Int -- , _crossoverProb :: Double -- , _mutationProb :: Double -- } --type RuleSet c a = [Rule c a] --type MatchSet c a = RuleSet c a --type ActionSet c a = RuleSet c a --type Classifier c a = RuleSet c a -> [c] -> EvoM a --type Model c a = [c] -> a --data Rule c a = Rule -- { _condition :: [c] -- , _action :: a -- , _prediction :: Double -- , _error :: Double -- , _fitness :: Double -- } --instance (Show c, Show a) => Show (Rule c a) where -- show (Rule cond action prediction err fitness) = "< " ++ concat (map show cond) -- ++ " : " ++ show action -- ++ " = " ++ show prediction -- ++ " " ++ show err -- ++ " " ++ show fitness -- ++ " >" --class (Eq c, Enum c, Show c, Variate c, Bounded c) => Condition c where -- dontCare :: c --class (Eq a, Enum a, Show a, Variate a, Bounded a) => Action a where --data Bit = DontCare | On | Off deriving (Enum, Bounded) --instance Eq Bit where -- On == Off = False -- On == _ = True -- Off == On = False -- Off == _ = True -- DontCare == _ = True --instance Show Bit where -- show On = "1" -- show Off = "0" -- show DontCare = "#" --instance Condition Bit where -- dontCare = DontCare --instance Action Bool --instance Variate Bit where -- uniform gen = uniform gen >>= return . toEnum . flip mod 3 -- uniformR (a, b) gen = uniformR (fromEnum a, fromEnum b) gen >>= return . toEnum --type Vanilla = Rule Bit Bool
banacorn/evo
src/Evo/Type.hs
mit
3,233
0
11
818
409
247
162
26
1
module ProjectEuler.Problem013 (solve) where solve :: Integer solve = read . take 10 . show . sum $ xs where xs :: [Integer] xs = [ 37107287533902102798797998220837590246510135740250 , 46376937677490009712648124896970078050417018260538 , 74324986199524741059474233309513058123726617309629 , 91942213363574161572522430563301811072406154908250 , 23067588207539346171171980310421047513778063246676 , 89261670696623633820136378418383684178734361726757 , 28112879812849979408065481931592621691275889832738 , 44274228917432520321923589422876796487670272189318 , 47451445736001306439091167216856844588711603153276 , 70386486105843025439939619828917593665686757934951 , 62176457141856560629502157223196586755079324193331 , 64906352462741904929101432445813822663347944758178 , 92575867718337217661963751590579239728245598838407 , 58203565325359399008402633568948830189458628227828 , 80181199384826282014278194139940567587151170094390 , 35398664372827112653829987240784473053190104293586 , 86515506006295864861532075273371959191420517255829 , 71693888707715466499115593487603532921714970056938 , 54370070576826684624621495650076471787294438377604 , 53282654108756828443191190634694037855217779295145 , 36123272525000296071075082563815656710885258350721 , 45876576172410976447339110607218265236877223636045 , 17423706905851860660448207621209813287860733969412 , 81142660418086830619328460811191061556940512689692 , 51934325451728388641918047049293215058642563049483 , 62467221648435076201727918039944693004732956340691 , 15732444386908125794514089057706229429197107928209 , 55037687525678773091862540744969844508330393682126 , 18336384825330154686196124348767681297534375946515 , 80386287592878490201521685554828717201219257766954 , 78182833757993103614740356856449095527097864797581 , 16726320100436897842553539920931837441497806860984 , 48403098129077791799088218795327364475675590848030 , 87086987551392711854517078544161852424320693150332 , 59959406895756536782107074926966537676326235447210 , 69793950679652694742597709739166693763042633987085 , 41052684708299085211399427365734116182760315001271 , 65378607361501080857009149939512557028198746004375 , 35829035317434717326932123578154982629742552737307 , 94953759765105305946966067683156574377167401875275 , 88902802571733229619176668713819931811048770190271 , 25267680276078003013678680992525463401061632866526 , 36270218540497705585629946580636237993140746255962 , 24074486908231174977792365466257246923322810917141 , 91430288197103288597806669760892938638285025333403 , 34413065578016127815921815005561868836468420090470 , 23053081172816430487623791969842487255036638784583 , 11487696932154902810424020138335124462181441773470 , 63783299490636259666498587618221225225512486764533 , 67720186971698544312419572409913959008952310058822 , 95548255300263520781532296796249481641953868218774 , 76085327132285723110424803456124867697064507995236 , 37774242535411291684276865538926205024910326572967 , 23701913275725675285653248258265463092207058596522 , 29798860272258331913126375147341994889534765745501 , 18495701454879288984856827726077713721403798879715 , 38298203783031473527721580348144513491373226651381 , 34829543829199918180278916522431027392251122869539 , 40957953066405232632538044100059654939159879593635 , 29746152185502371307642255121183693803580388584903 , 41698116222072977186158236678424689157993532961922 , 62467957194401269043877107275048102390895523597457 , 23189706772547915061505504953922979530901129967519 , 86188088225875314529584099251203829009407770775672 , 11306739708304724483816533873502340845647058077308 , 82959174767140363198008187129011875491310547126581 , 97623331044818386269515456334926366572897563400500 , 42846280183517070527831839425882145521227251250327 , 55121603546981200581762165212827652751691296897789 , 32238195734329339946437501907836945765883352399886 , 75506164965184775180738168837861091527357929701337 , 62177842752192623401942399639168044983993173312731 , 32924185707147349566916674687634660915035914677504 , 99518671430235219628894890102423325116913619626622 , 73267460800591547471830798392868535206946944540724 , 76841822524674417161514036427982273348055556214818 , 97142617910342598647204516893989422179826088076852 , 87783646182799346313767754307809363333018982642090 , 10848802521674670883215120185883543223812876952786 , 71329612474782464538636993009049310363619763878039 , 62184073572399794223406235393808339651327408011116 , 66627891981488087797941876876144230030984490851411 , 60661826293682836764744779239180335110989069790714 , 85786944089552990653640447425576083659976645795096 , 66024396409905389607120198219976047599490197230297 , 64913982680032973156037120041377903785566085089252 , 16730939319872750275468906903707539413042652315011 , 94809377245048795150954100921645863754710598436791 , 78639167021187492431995700641917969777599028300699 , 15368713711936614952811305876380278410754449733078 , 40789923115535562561142322423255033685442488917353 , 44889911501440648020369068063960672322193204149535 , 41503128880339536053299340368006977710650566631954 , 81234880673210146739058568557934581403627822703280 , 82616570773948327592232845941706525094512325230608 , 22918802058777319719839450180888072429661980811197 , 77158542502016545090413245809786882778948721859617 , 72107838435069186155435662884062257473692284509516 , 20849603980134001723930671666823555245252804609722 , 53503534226472524250874054075591789781264330331690 ]
hachibu/project-euler
src/ProjectEuler/Problem013.hs
mit
6,343
0
9
1,137
355
231
124
104
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGUseElement (js_getX, getX, js_getY, getY, js_getWidth, getWidth, js_getHeight, getHeight, SVGUseElement, castToSVGUseElement, gTypeSVGUseElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"x\"]" js_getX :: SVGUseElement -> IO (Nullable SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGUseElement.x Mozilla SVGUseElement.x documentation> getX :: (MonadIO m) => SVGUseElement -> m (Maybe SVGAnimatedLength) getX self = liftIO (nullableToMaybe <$> (js_getX (self))) foreign import javascript unsafe "$1[\"y\"]" js_getY :: SVGUseElement -> IO (Nullable SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGUseElement.y Mozilla SVGUseElement.y documentation> getY :: (MonadIO m) => SVGUseElement -> m (Maybe SVGAnimatedLength) getY self = liftIO (nullableToMaybe <$> (js_getY (self))) foreign import javascript unsafe "$1[\"width\"]" js_getWidth :: SVGUseElement -> IO (Nullable SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGUseElement.width Mozilla SVGUseElement.width documentation> getWidth :: (MonadIO m) => SVGUseElement -> m (Maybe SVGAnimatedLength) getWidth self = liftIO (nullableToMaybe <$> (js_getWidth (self))) foreign import javascript unsafe "$1[\"height\"]" js_getHeight :: SVGUseElement -> IO (Nullable SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGUseElement.height Mozilla SVGUseElement.height documentation> getHeight :: (MonadIO m) => SVGUseElement -> m (Maybe SVGAnimatedLength) getHeight self = liftIO (nullableToMaybe <$> (js_getHeight (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGUseElement.hs
mit
2,525
24
10
320
638
377
261
36
1
module Game (Game(Game) ,bestAnswer ,bestAnswers ) where import Data.Maybe import Data.List import Expression data Game = Game [Int] Int without :: (Eq a) => (a, a) -> [a] -> [a] without (i1, i2) xs = (delete i1) . (delete i2) $ xs expressions :: (Expression -> Expression -> Expression) -> [Expression] -> [[Expression]] expressions func xs = filter (isJust . eval . head) [func i1 i2 : without (i1, i2) xs | (i1, i2) <- combination xs] allExpressions :: [Expression] -> [[Expression]] allExpressions [] = [] allExpressions xs = expressions Add xs ++ expressions Sub xs ++ expressions Mul xs ++ expressions Div xs solutions :: [Expression] -> [[Expression]] solutions [] = [] solutions xs = let all = allExpressions xs in all ++ foldl (++) [] (map solutions all) combination [] = [] combination (x:xs) = [(x, x') | x' <- xs] ++ combination xs join sep = foldl1 (\x y -> x ++ sep ++ y) play :: Game -> [[Expression]] play (Game xs _) = solutions $ map Equ xs target :: Game -> Int target (Game _ target) = target bestAnswers :: Game -> [Expression] bestAnswers g = best (target g) Nothing (play g) bestAnswer = last . bestAnswers
wharris/countdown
Game.hs
mit
1,239
0
10
312
553
296
257
39
1
module Flags ( Flags(..) , initFlags , getFlags , getTimeLeft , getTimeSpent , getTimeSpentS ) where {- Paradox/Equinox -- Copyright (c) 2003-2007, Koen Claessen, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} import System.Environment ( getArgs ) import Data.Char import Data.List (groupBy, intersperse) import System.CPUTime import System.Exit #if __GLASGOW_HASKELL__ >= 606 import Control.Monad.Instances () -- to get Functor (Either a) #endif ------------------------------------------------------------------------- -- flags data Flags = Flags { time :: Maybe Int , roots :: [FilePath] , printModel :: Bool , dot :: Maybe String , mfile :: Maybe FilePath , splitting :: Bool , sat :: Bool , onlyClausify :: Bool , strength :: Int , verbose :: Int , tstp :: Bool -- primitive , thisFile :: FilePath , files :: [FilePath] , start :: Integer } deriving (Eq, Show) initFlags :: Flags initFlags = Flags { time = Nothing , roots = [] , printModel = False , dot = Nothing , mfile = Nothing , splitting = False , sat = False , onlyClausify = False , strength = 4 , verbose = 0 , tstp = False -- primitive , thisFile = "" , files = [] , start = error "starting time not properly initialized" } ------------------------------------------------------------------------- -- options options :: [Option Flags] options = [ Option { long = "time" , meaning = (\n f -> f{ time = Just n }) <$> argNum , help = [ "Maximum running time in seconds. Is a (very) soft limit." , "Example: --time 300" , "Default: (off)" ] } , Option { long = "root" , meaning = (\r f -> f{ roots = roots f ++ [r] }) <$> argFile , help = [ "A directory in which included problems will be sought." , "Example: --root TPTP-v3.0.0" , "Default: --root ." ] } , Option { long = "split" , meaning = unit (\f -> f{ splitting = True }) , help = [ "Split the conjecture into several sub-conjectures." , "Default: (off)" ] } , Option { long = "model" , meaning = unit (\f -> f{ printModel = True }) , help = [ "Print the found model on the screen." , "Default: (off)" ] } {- , Option { long = "dot" , meaning = (\d f -> f{ dot = Just d }) <$> argDots , help = [ "Generate dot-files for each approximate model." , "<dot-spec> specifies what symbols to show and how." , "Default: (off)" ] } -} , Option { long = "strength" , meaning = (\n f -> f{ strength = n }) <$> argNum , help = [ "Maximum number of non-guessing quantifier instantations" , "before starting to guess." , "Example: --strength 7" , "Default: --strength " ++ show (strength initFlags) ] } , Option { long = "verbose" , meaning = (\n f -> f{ verbose = verbose f `max` n }) <$> argNum , help = [ "Verbosity level." , "Example: --verbose 2" , "Default: --verbose 0" ] } , Option { long = "tstp" , meaning = unit (\f -> f{ tstp = True }) , help = [ "Generate output in TSTP and SZS ontology format." , "Default: (off)" ] } , Option { long = "help" , meaning = unit id , help = [ "Displays this help message." ] } ] -- data Option data Option a = Option { long :: String , meaning :: Arg (a -> a) , help :: [String] } ------------------------------------------------------------------------- -- getFlags getFlags :: IO Flags getFlags = do as <- getArgs picoT <- getCPUTime case parseFlags initFlags as of Left [] -> do putStr (unlines helpMessage) exitWith ExitSuccess Left err -> do putStrLn "Error in arguments:" putStr (unlines err) putStrLn "Try --help." exitWith (ExitFailure (-1)) Right f -> do return f{ start = unPico picoT } getTimeLeft :: Flags -> IO Int getTimeLeft flags = do t' <- getTimeSpent flags return (t - t') where t = maybe 300 id (time flags) getTimeSpent :: Flags -> IO Int getTimeSpent flags = do picoT <- getCPUTime return (fromInteger (unPico picoT - start flags)) getTimeSpentS :: Flags -> IO String getTimeSpentS flags = do picoT <- getCPUTime let t = fromInteger (unPico' picoT - start flags) m = t `div` 600 s = (t `div` 10) `mod` 60 d = t `mod` 10 return ( show m ++ ":" ++ let x = show s in replicate (2 - length x) '0' ++ x ++ "." ++ show d ) unPico :: Integer {- picoseconds -} -> Integer {- seconds -} unPico = let c = 10^12 in (`div` c) unPico' :: Integer {- picoseconds -} -> Integer {- 0.1 seconds -} unPico' = let c = 10^11 in (`div` c) ------------------------------------------------------------------------- -- arg data Arg a = MkArg [String] ([String] -> Either [String] (a, [String])) #if __GLASGOW_HASKELL__ < 606 instance Functor (Either a) where fmap f (Left x) = Left x fmap f (Right y) = Right (f y) #endif unit :: a -> Arg a unit x = MkArg [] (\s -> Right (x,s)) (<*>) :: Arg (a -> b) -> Arg a -> Arg b MkArg fs f <*> MkArg xs x = MkArg (fs++xs) (\s -> case f s of Left err -> Left err Right (h,s') -> case x s' of Left err -> Left err Right (a,s'') -> Right (h a,s'') ) (<$>) :: (a -> b) -> Arg a -> Arg b f <$> x = unit f <*> x args :: Arg a -> [String] args (MkArg as _) = as ------------------------------------------------------------------------- -- parsers argNum :: (Read a, Num a) => Arg a argNum = MkArg ["<num>"] $ \xs -> case xs of x:xs | all isDigit x -> Right (read x, xs) ('-':x):xs | all isDigit x -> Right (-read x, xs) _ -> Left ["expected a number"] argFile :: Arg FilePath argFile = MkArg ["<file>"] $ \xs -> case xs of x:xs -> Right (x, xs) _ -> Left ["expected a file"] argDots :: Arg FilePath argDots = MkArg ["<dot-spec>"] $ \xs -> case xs of x:xs -> Right (x, xs) _ -> Left ["expected a dot-spec"] argNums :: Arg [Int] argNums = MkArg ["<nums>"] $ \xs -> case xs of [] -> Left ["expected a number list"] x:xs -> ((\a -> (a,xs)) `fmap`) . nums . groupBy (\x y -> isDigit x == isDigit y) $ x ++ "," where nums [] = Right [] nums (n:",":ns) = (read n :) `fmap` nums ns nums (n:"..":m:",":ns) = ([read n .. read m] ++) `fmap` nums ns nums _ = Left ["number list garbled"] argOption :: [String] -> Arg String argOption as = MkArg ["<" ++ concat (intersperse " | " as) ++ ">"] $ \xs -> case xs of [] -> Left ["expected an argument"] x:xs -> ((\a -> (a,xs)) `fmap`) . elts $ x where elts x | x `elem` as = Right x | otherwise = Left ["argument garbled"] argList :: [String] -> Arg [String] argList as = MkArg ["<" ++ concat (intersperse " | " as) ++ ">*"] $ \xs -> case xs of [] -> Left ["expected a list"] x:xs -> ((\a -> (a,xs)) `fmap`) . elts $ x ++ "," where elts [] = Right [] elts s | w `elem` as = (w:) `fmap` elts r where w = takeWhile (/= ',') s r = tail (dropWhile (/= ',') s) elts _ = Left ["argument list garbled"] parseFlags :: Flags -> [String] -> Either [String] Flags parseFlags f [] = Right f parseFlags f ("--help":xs) = Left [] parseFlags f (('-':'-':x):xs) = case [ opt | opt <- options, x == long opt ] of opt:_ -> case h xs of Left err -> Left err Right (g,xs') -> parseFlags (g f) xs' where MkArg _ h = meaning opt [] -> Left ["Unrecognized option: '--" ++ x ++ "'"] parseFlags f (x:xs) = parseFlags (f{files = files f ++ [x]}) xs ------------------------------------------------------------------------- -- help message helpMessage :: [String] helpMessage = [ "Usage: <option>* <file>*" , "" , "<file> should be in TPTP format." , "" , "<option> can be any of the following:" ] ++ concat [ [ "" , " --" ++ long opt ++ " " ++ unwords (args (meaning opt)) ] ++ map (" "++) (help opt) | opt <- options ] ------------------------------------------------------------------------- -- the end.
msakai/folkung
Haskell/Flags.hs
mit
9,911
1
18
3,175
2,890
1,576
1,314
222
5
{-# LANGUAGE OverloadedStrings, GADTs #-} -- | Data structures pertaining to gateway dispatch 'Event's module Network.Discord.Types.Events where import Control.Monad (mzero) import Data.Aeson import Network.Discord.Types.Channel import Network.Discord.Types.Gateway import Network.Discord.Types.Guild (Member, Guild) import Network.Discord.Types.Prelude -- |Represents data sent on READY event. data Init = Init Int User [Channel] [Guild] String deriving Show -- |Allows Init type to be generated using a JSON response by Discord. instance FromJSON Init where parseJSON (Object o) = Init <$> o .: "v" <*> o .: "user" <*> o .: "private_channels" <*> o .: "guilds" <*> o .: "session_id" parseJSON _ = mzero -- |Represents possible events sent by discord. Detailed information can be found at https://discordapp.com/developers/docs/topics/gateway. data Event = Ready Init | Resumed Object | ChannelCreate Channel | ChannelUpdate Channel | ChannelDelete Channel | GuildCreate Guild | GuildUpdate Guild | GuildDelete Guild | GuildBanAdd Member | GuildBanRemove Member | GuildEmojiUpdate Object | GuildIntegrationsUpdate Object | GuildMemberAdd Member | GuildMemberRemove Member | GuildMemberUpdate Member | GuildMemberChunk Object | GuildRoleCreate Object | GuildRoleUpdate Object | GuildRoleDelete Object | MessageCreate Message | MessageUpdate Message | MessageDelete Object | MessageDeleteBulk Object | PresenceUpdate Object | TypingStart Object | UserSettingsUpdate Object | UserUpdate Object | VoiceStateUpdate Object | VoiceServerUpdate Object | UnknownEvent String Object deriving Show -- |Parses JSON stuff by Discord to an event type. parseDispatch :: Payload -> Either String Event parseDispatch (Dispatch ob _ ev) = case ev of "READY" -> Ready <$> reparse o "RESUMED" -> Resumed <$> reparse o "CHANNEL_CREATE" -> ChannelCreate <$> reparse o "CHANNEL_UPDATE" -> ChannelUpdate <$> reparse o "CHANNEL_DELETE" -> ChannelDelete <$> reparse o "GUILD_CREATE" -> GuildCreate <$> reparse o "GUILD_UPDATE" -> GuildUpdate <$> reparse o "GUILD_DELETE" -> GuildDelete <$> reparse o "GUILD_BAN_ADD" -> GuildBanAdd <$> reparse o "GUILD_BAN_REMOVE" -> GuildBanRemove <$> reparse o "GUILD_EMOJI_UPDATE" -> GuildEmojiUpdate <$> reparse o "GUILD_INTEGRATIONS_UPDATE" -> GuildIntegrationsUpdate <$> reparse o "GUILD_MEMBER_ADD" -> GuildMemberAdd <$> reparse o "GUILD_MEMBER_UPDATE" -> GuildMemberUpdate <$> reparse o "GUILD_MEMBER_REMOVE" -> GuildMemberRemove <$> reparse o "GUILD_MEMBER_CHUNK" -> GuildMemberChunk <$> reparse o "GUILD_ROLE_CREATE" -> GuildRoleCreate <$> reparse o "GUILD_ROLE_UPDATE" -> GuildRoleUpdate <$> reparse o "GUILD_ROLE_DELETE" -> GuildRoleDelete <$> reparse o "MESSAGE_CREATE" -> MessageCreate <$> reparse o "MESSAGE_UPDATE" -> MessageUpdate <$> reparse o "MESSAGE_DELETE" -> MessageDelete <$> reparse o "MESSAGE_DELETE_BULK" -> MessageDeleteBulk <$> reparse o "PRESENCE_UPDATE" -> PresenceUpdate <$> reparse o "TYPING_START" -> TypingStart <$> reparse o "USER_SETTINGS_UPDATE" -> UserSettingsUpdate <$> reparse o "VOICE_STATE_UPDATE" -> VoiceStateUpdate <$> reparse o "VOICE_SERVER_UPDATE" -> VoiceServerUpdate <$> reparse o _ -> UnknownEvent ev <$> reparse o where o = Object ob parseDispatch _ = error "Tried to parse non-Dispatch payload"
jano017/Discord.hs
src/Network/Discord/Types/Events.hs
mit
4,518
0
15
1,681
757
394
363
81
29
module Paths_advent_coding ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version [0,1,0,0] [] bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/home/rewrite/Documents/Personal-Repository/Haskell/Playground/AdventOfCode/advent-coding/.stack-work/install/x86_64-linux/lts-3.14/7.10.2/bin" libdir = "/home/rewrite/Documents/Personal-Repository/Haskell/Playground/AdventOfCode/advent-coding/.stack-work/install/x86_64-linux/lts-3.14/7.10.2/lib/x86_64-linux-ghc-7.10.2/advent-coding-0.1.0.0-50qzlX786zH5MCh4a2QQrZ" datadir = "/home/rewrite/Documents/Personal-Repository/Haskell/Playground/AdventOfCode/advent-coding/.stack-work/install/x86_64-linux/lts-3.14/7.10.2/share/x86_64-linux-ghc-7.10.2/advent-coding-0.1.0.0" libexecdir = "/home/rewrite/Documents/Personal-Repository/Haskell/Playground/AdventOfCode/advent-coding/.stack-work/install/x86_64-linux/lts-3.14/7.10.2/libexec" sysconfdir = "/home/rewrite/Documents/Personal-Repository/Haskell/Playground/AdventOfCode/advent-coding/.stack-work/install/x86_64-linux/lts-3.14/7.10.2/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "advent_coding_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "advent_coding_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "advent_coding_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "advent_coding_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "advent_coding_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
cirquit/Personal-Repository
Haskell/Playground/AdventOfCode/advent-coding/.stack-work/dist/x86_64-linux/Cabal-1.22.4.0/build/autogen/Paths_advent_coding.hs
mit
1,978
0
10
177
362
206
156
28
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Caltrops.Common where import Servant import Data.Aeson (ToJSON(..)) import Data.Typeable import Data.Text (Text) import Data.Time.Calendar import Data.Time.Clock import GHC.Generics newtype Id = Id { unId :: Int } deriving instance FromText Id deriving instance ToJSON Id deriving instance Typeable Id deriving instance Num Id deriving instance Eq Id deriving instance Read Id deriving instance Show Id -------------------------------------------------------------------------------- -- User Types -------------------------------------------------------------------------------- data User = User { userId :: Id , userName :: Text , userEmail :: Text , userSince :: Day , userLastSeen :: UTCTime } deriving (Eq, Show, Generic, Typeable) instance ToJSON Day where toJSON d = toJSON (showGregorian d) instance ToJSON User
schell/caltrops
src/Caltrops/Common.hs
mit
1,270
0
8
254
227
135
92
35
0
{-| Module : DavisPutnam Description : Implementation of DP and DPLL algorithms Copyright : (c) Alex Nelson, 2015 License : MIT Maintainer : [email protected] Stability : experimental Portability : POSIX A slightly optimized method for checking satisfiability. -} module DavisPutnam ( dp , isTautology , isSatisfiable , isUnsatisfiable , dpll ) where import qualified Data.List import qualified Data.Map as Map import qualified Set import Data.Maybe import Prelude hiding (negate) import Formula hiding (isTautology, isSatisfiable, isUnsatisfiable) import NormalForm isUnitClause :: [Formula] -> Bool isUnitClause (_:t) = null t isUnitClause _ = False -- | The one literal rule for the Davis-Putnam algorithm. oneLiteralRule :: [[Formula]] -> Maybe [[Formula]] oneLiteralRule clauses = case Data.List.find isUnitClause clauses of Nothing -> Nothing Just [u] -> Just (Set.image (Set.\\ [u']) clauses') where u' = negate u clauses' = filter (notElem u) clauses _ -> error "oneLiteralRule reached impossible state" -- | Attempts to eliminate literals that show up as _only positive_ or -- _only negative_. If this eliminates everything, it will return -- 'Nothing'; otherwise, it returns 'Just' the transformed clauses. affirmativeNegativeRule :: [[Formula]] -> Maybe [[Formula]] affirmativeNegativeRule clauses = let (neg', pos) = Data.List.partition isNegative (Set.unions clauses) neg = map negate neg' posOnly = Set.difference pos neg negOnly = Set.difference neg pos pure = Set.union posOnly (map negate negOnly) in case pure of [] -> Nothing _ -> Just (filter (null . Set.intersect pure) clauses) -- | Gets rid of a literal (first argument) from the clauses (second argument) -- producing a new set of clauses without the literal showing up at all. -- Warning: the result could be huge. resolveOn :: Formula -> [[Formula]] -> [[Formula]] resolveOn p clauses = let p' = negate p (pos, notPos) = Data.List.partition (elem p) clauses (neg, other) = Data.List.partition (elem p') notPos pos' = map (filter (/= p)) pos neg' = map (filter (/= p')) neg res0 = [ c `Set.union` d | c <- pos', d <- neg'] in Set.union other (filter (not . trivial) res0) -- | A crude heuristic to determine which literal to use. findBlowup :: [[Formula]] -> Formula -> (Int, Formula) findBlowup cls l = let m = length(filter (elem l) cls) n = length(filter (elem (negate l)) cls) in (m*n - m - n, l) -- | A one-step resolution rule, which 'resolveOn' the literal -- determined by minimizing 'findBlowup' on the clauses. resolutionRule :: [[Formula]] -> [[Formula]] resolutionRule clauses = let pvs = filter isPositive (Set.unions clauses) (_, p) = Data.List.minimum $ map (findBlowup clauses) pvs in resolveOn p clauses -- | The basic structure of the Davis-Putnam and DPLL algorithms are the -- same, they just differ with respect to the splitting rule. So, -- refactor out the similar structure into a helper function, and have -- each algorithm pass in its own splitting rule. dpSkeleton :: [[Formula]] -> ([[Formula]] -> Bool) -> Bool dpSkeleton [] _ = True dpSkeleton clauses isSatisfiable = if [] `elem` clauses then False else case oneLiteralRule clauses of Just clauses' -> dpSkeleton clauses' isSatisfiable Nothing -> case affirmativeNegativeRule clauses of Just clauses' -> dpSkeleton clauses' isSatisfiable Nothing -> isSatisfiable clauses -- | The original Davis-Putnam algorithm, in all its glory. dp :: [[Formula]] -> Bool dp clauses = dpSkeleton clauses (dp . resolutionRule) -- | Given the clauses and a literal, return an ordered pair '(Int, Formula)' -- which gives how many times the literal (or its negation) appears in -- the clauses, and the literal being checked for. frequencies :: [[Formula]] -> Formula -> (Int, Formula) frequencies clauses p = let m = length $ filter (elem p) clauses n = length $ filter (elem (Not p)) clauses in (m+n, p) -- | Return all literals that occur in the formula, negated literals are -- transformed to be positive. getLiterals :: [[Formula]] -> [Formula] getLiterals clauses = let (pos,neg) = Data.List.partition isPositive $ Set.unions clauses in Set.union pos (map negate neg) -- | The unique component to the DPLL modifies the splitting rule. splittingRule :: [[Formula]] -> Bool splittingRule clauses = let pvs = getLiterals clauses lcounts = map (frequencies clauses) pvs (_, p) = Data.List.maximum lcounts in dpll (Set.insert [p] clauses) || dpll (Set.insert [negate p] clauses) -- | The 1962 Davis-Putnam rule, which is slightly slicker. -- See Davis, Logemann, and Loveland's "A Machine Program for Theorem Proving" -- Comm. of the ACM, vol 5, no 7 (1962) pp 394-397 for the original reference. dpll :: [[Formula]] -> Bool dpll clauses = dpSkeleton clauses splittingRule {- The following code is idiosyncratic, and has to do with backtracking in the DPLL algorithm. -} -- | Keep track of each step in the trail when we 'Guessed' or 'Deduced' -- a value in the valuation. data TrailMix = Deduced | Guessed deriving (Eq, Ord) -- | The Trail is just a step in the trail, keeping track of a 'Formula' -- and a 'TrailMix' explanation. type Trail = (Formula, TrailMix) type Clauses = [[Formula]] -- | Updates the clauses to remove negated literals which do not belong to -- the trail, as specified by the map. removeTrailedNegLits :: Map.Map Formula Formula -> Clauses -> Clauses removeTrailedNegLits m = map (filter (not . (`Map.member` m) . negate)) -- | Given a 'Map.Map Formula Formula', and a list '[Formula]', -- for each element in our list, check if it's a member of the map; -- if so, map it to 'Just fm', otherwise map it to 'Nothing'. maybeInclude :: Map.Map Formula Formula -> [Formula] -> [Maybe Formula] maybeInclude m (c:cls) = if Map.member c m then Nothing : maybeInclude m cls else Just c : maybeInclude m cls maybeInclude _ [] = [] -- | Get all the units from the clauses which are undefined according -- to our dictionary. undefinedUnits :: Map.Map Formula Formula -> Clauses -> [Formula] undefinedUnits m = Set.unions . map (catMaybes . maybeInclude m) -- | We keep track of the trail history in the @Map.Map Formula Formula@ -- parameter, the given clause is the first parameter, and the @[Trail]@ -- stars as itself. unitSubpropagate :: (Clauses, Map.Map Formula Formula, [Trail]) -> (Clauses, Map.Map Formula Formula, [Trail]) unitSubpropagate (cls, m, trail) = let cls' = removeTrailedNegLits m cls newunits = undefinedUnits m cls' in if null newunits then (cls', m, trail) else let trail' = foldr (\l t -> (l, Deduced):t) trail newunits m' = foldr (\l mp -> Map.insert l l mp) m newunits in unitSubpropagate (cls', m', trail') -- | Unit propagation using the newfangled 'Trail'. It amounts to making -- 'unitSubpropagate' doing all the work, and 'btUnitPropagation' -- getting all the glory. btUnitPropagation :: (Clauses, [Trail]) -> (Clauses, [Trail]) btUnitPropagation (cls, trail) = let m = foldr (\(l,_) mp -> Map.insert l l mp) Map.empty trail (cls', _, trail') = unitSubpropagate (cls, m, trail) in (cls', trail') -- | Backtrack the trail until we found the last guess which caused problems. backtrack :: [Trail] -> [Trail] backtrack ((_, Deduced):tt) = backtrack tt backtrack tt = tt --- backtrack [] = [] -- | All the literals in the clauses not yet assigned to the trail yet. unassigned :: Clauses -> [Trail] -> [Formula] unassigned cls trail = Set.difference (Set.unions (Set.image (Set.image litAbs) cls)) (Set.image (litAbs . fst) trail) -- | The iterative DPLL algorithm with backtracking. dpli :: Clauses -> [Trail] -> Bool dpli cls trail = let (cls', trail') = btUnitPropagation (cls, trail) in if [] `elem` cls' --- if we get the empty clause then case backtrack trail of --- backtrack until (p, Guessed):tt --- we guessed last -> dpli cls ((negate p, Deduced):tt) --- and guess again! _ -> False --- unless we can't else case unassigned cls trail' of --- otherwise [] -> True --- it's satisfiable if there are no unassigned literals ps -> let (_, p) = Data.List.maximum $ map (frequencies cls') ps in dpli cls ((p, Guessed):trail') --- recur with the next --- best guess -- | Test for satisfiability using 'dpli' dplisat :: Formula -> Bool dplisat fm = dpli (defCNFClauses fm) [] -- | Test for validity using 'dpli' dplitaut :: Formula -> Bool dplitaut = not . dplisat . Not -- | Given a set of clauses, a literal, and a trail, go back through the -- trail as far as possible while ensuring the most recent decision @p@ -- (the second argument) still leads to a conflict. It returns this -- modified 'Trail' list. backjump :: Clauses -> Formula -> [Trail] -> [Trail] backjump cls p trail@((q, Guessed):tt) = let (cls', trail') = btUnitPropagation (cls, (p,Guessed):tt) in if [] `elem` cls' then backjump cls p tt else trail backjump _ _ trail = trail -- | Given a list of 'Trail' elements, filter out all the 'Guessed' nodes. -- It will return a list of 'Trail', possibly empty if there were no 'Guessed' -- elements. guessedLiterals :: [Trail] -> [Trail] guessedLiterals ((p, Guessed):tt) = (p, Guessed):guessedLiterals tt guessedLiterals ((_, Deduced):tt) = guessedLiterals tt guessedLiterals [] = [] -- | The DPLL with backjumping and conflict learning. dplb :: Clauses -> [Trail] -> Bool dplb cls trail = let (cls', trail') = btUnitPropagation (cls, trail) in if [] `elem` cls' then case backtrack trail of (p, Guessed):tt -> let trail'' = backjump cls p tt declits = guessedLiterals trail'' conflict = Set.insert (negate p) (Set.image (negate . fst) declits) in dplb (conflict:cls) (Set.insert (negate p, Deduced) trail'') _ -> False else case unassigned cls trail' of [] -> True ps -> let (_,p) = Data.List.maximum $ map (frequencies cls') ps in dplb cls (Set.insert (p, Guessed) trail') -- | Uses our newfangled 'dplb' algorithm to test for satisfiability. isSatisfiable :: Formula -> Bool isSatisfiable fm = dplb (defCNFClauses fm) [] -- | Simply the complement of 'isSatisfiable' isUnsatisfiable :: Formula -> Bool isUnsatisfiable = not . isSatisfiable -- | Checks if the negated input 'isUnsatisfiable'. isTautology :: Formula -> Bool isTautology = isUnsatisfiable . Not
pqnelson/surak
src/DavisPutnam.hs
mit
11,365
0
19
2,955
2,796
1,522
1,274
165
4
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} -- | An implementation of @RWST@ built on top of mutable references, -- providing a proper monad morphism. -- -- An additional advantage of this transformer over the standard @RWST@ -- transformers in the transformers package is that it does not have space -- leaks in the writer component. For more information, see -- <https://mail.haskell.org/pipermail/libraries/2012-October/018599.html>. -- -- Please see the documentation at -- <https://www.stackage.org/package/monad-unlift> for more details on using -- this module. module Control.Monad.Trans.RWS.Ref ( RWSRefT , runRWSRefT , runRWSIORefT , runRWSSTRefT , module Control.Monad.RWS.Class ) where import Control.Applicative (Applicative (..)) import Control.Monad (ap, liftM) import Control.Monad.Catch (MonadCatch (..), MonadMask (..), MonadThrow (..)) import Control.Monad.IO.Class (MonadIO (..)) import Control.Monad.RWS.Class import Control.Monad.Trans.Control (defaultLiftBaseWith, defaultRestoreM) import Control.Monad.Trans.Unlift import Control.Monad.Trans.Resource (MonadResource (..)) import Data.Monoid (Monoid, mappend, mempty) import Data.Mutable (IORef, MCState, MutableRef, PrimMonad, PrimState, RealWorld, RefElement, STRef, modifyRef', newRef, readRef, writeRef) -- | -- -- @since 0.1.0 newtype RWSRefT refw refs r w s m a = RWSRefT { unRWSRefT :: r -> refw w -> refs s -> m a } deriving Functor -- | -- -- @since 0.1.0 runRWSRefT :: ( Monad m , w ~ RefElement (refw w) , s ~ RefElement (refs s) , MCState (refw w) ~ PrimState b , MCState (refs s) ~ PrimState b , MonadBase b m , MutableRef (refw w) , MutableRef (refs s) , PrimMonad b , Monoid w ) => RWSRefT refw refs r w s m a -> r -> s -> m (a, s, w) runRWSRefT (RWSRefT f) r s0 = do (refw, refs) <- liftBase $ (,) `liftM` newRef mempty `ap` newRef s0 a <- f r refw refs (w, s) <- liftBase $ (,) `liftM` readRef refw `ap` readRef refs return (a, s, w) {-# INLINEABLE runRWSRefT #-} -- | -- -- @since 0.1.0 runRWSIORefT :: ( Monad m , RealWorld ~ PrimState b , MonadBase b m , PrimMonad b , Monoid w ) => RWSRefT IORef IORef r w s m a -> r -> s -> m (a, s, w) runRWSIORefT = runRWSRefT {-# INLINE runRWSIORefT #-} -- | -- -- @since 0.1.0 runRWSSTRefT :: ( Monad m , ps ~ PrimState b , MonadBase b m , PrimMonad b , Monoid w ) => RWSRefT (STRef ps) (STRef ps) r w s m a -> r -> s -> m (a, s, w) runRWSSTRefT = runRWSRefT {-# INLINE runRWSSTRefT #-} instance Applicative m => Applicative (RWSRefT refw refs r w s m) where pure m = RWSRefT $ \_ _ _ -> pure m {-# INLINE pure #-} RWSRefT f <*> RWSRefT g = RWSRefT $ \x y z -> f x y z <*> g x y z {-# INLINE (<*>) #-} instance Monad m => Monad (RWSRefT refw refs r w s m) where return m = RWSRefT $ \_ _ _ -> return m {-# INLINE return #-} RWSRefT f >>= g = RWSRefT $ \x y z -> do a <- f x y z unRWSRefT (g a) x y z {-# INLINE (>>=) #-} instance Monad m => MonadReader r (RWSRefT refw refs r w s m) where ask = RWSRefT $ \r _ _ -> return r {-# INLINE ask #-} local f (RWSRefT g) = RWSRefT $ \r w s -> g (f r) w s instance ( MCState (refw w) ~ PrimState b , Monad m , w ~ RefElement (refw w) , MutableRef (refw w) , PrimMonad b , MonadBase b m , Monoid w ) => MonadWriter w (RWSRefT refw refs r w s m) where writer (a, w) = RWSRefT $ \_ ref _ -> liftBase $ modifyRef' ref (`mappend` w) >> return a {-# INLINE writer #-} tell w = RWSRefT $ \_ ref _ -> liftBase $ modifyRef' ref (`mappend` w) {-# INLINE tell #-} listen (RWSRefT f) = RWSRefT $ \r _ s -> do ref <- liftBase (newRef mempty) a <- f r ref s w <- liftBase (readRef ref) return (a, w) {-# INLINEABLE listen #-} pass (RWSRefT f) = RWSRefT $ \r ref s -> do (a, g) <- f r ref s liftBase $ modifyRef' ref g return a {-# INLINEABLE pass #-} instance ( MCState (refs s) ~ PrimState b , Monad m , s ~ RefElement (refs s) , MutableRef (refs s) , PrimMonad b , MonadBase b m ) => MonadState s (RWSRefT refw refs r w s m) where get = RWSRefT $ \_ _ -> liftBase . readRef {-# INLINE get #-} put x = seq x $ RWSRefT $ \_ _ -> liftBase . (`writeRef` x) {-# INLINE put #-} instance ( MCState (refw w) ~ PrimState b , MCState (refs s) ~ PrimState b , Monad m , w ~ RefElement (refw w) , s ~ RefElement (refs s) , MutableRef (refw w) , MutableRef (refs s) , PrimMonad b , MonadBase b m , Monoid w ) => MonadRWS r w s (RWSRefT refw refs r w s m) instance MonadTrans (RWSRefT refw refs r w s) where lift f = RWSRefT $ \_ _ _ -> f {-# INLINE lift #-} instance MonadIO m => MonadIO (RWSRefT refw refs r w s m) where liftIO = lift . liftIO {-# INLINE liftIO #-} instance MonadBase b m => MonadBase b (RWSRefT refw refs r w s m) where liftBase = lift . liftBase {-# INLINE liftBase #-} instance MonadTransControl (RWSRefT refw refs r w s) where type StT (RWSRefT refw refs r w s) a = a liftWith f = RWSRefT $ \r w s -> f $ \t -> unRWSRefT t r w s restoreT f = RWSRefT $ \_ _ _ -> f {-# INLINABLE liftWith #-} {-# INLINABLE restoreT #-} instance MonadBaseControl b m => MonadBaseControl b (RWSRefT refw refs r w s m) where type StM (RWSRefT refw refs r w s m) a = StM m a liftBaseWith = defaultLiftBaseWith restoreM = defaultRestoreM {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance MonadThrow m => MonadThrow (RWSRefT refw refs r w s m) where throwM = lift . throwM {-# INLINE throwM #-} instance MonadCatch m => MonadCatch (RWSRefT refw refs r w s m) where catch (RWSRefT f) g = RWSRefT $ \e w s -> catch (f e w s) ((\m -> unRWSRefT m e w s) . g) instance MonadMask m => MonadMask (RWSRefT refw refs r w s m) where mask a = RWSRefT $ \e w s -> mask $ \u -> unRWSRefT (a $ q u) e w s where q :: (m a -> m a) -> RWSRefT refw refs r w s m a -> RWSRefT refw refs r w s m a q u (RWSRefT b) = RWSRefT (\r w s -> u (b r w s)) {-# INLINE mask #-} uninterruptibleMask a = RWSRefT $ \e w s -> uninterruptibleMask $ \u -> unRWSRefT (a $ q u) e w s where q :: (m a -> m a) -> RWSRefT refw refs r w s m a -> RWSRefT refw refs r w s m a q u (RWSRefT b) = RWSRefT (\r w s -> u (b r w s)) {-# INLINE uninterruptibleMask #-} instance MonadResource m => MonadResource (RWSRefT refw refs r w s m) where liftResourceT = lift . liftResourceT {-# INLINE liftResourceT #-}
fpco/monad-unlift
monad-unlift-ref/Control/Monad/Trans/RWS/Ref.hs
mit
7,486
0
13
2,459
2,574
1,354
1,220
172
1
module Verba.CLI (runCLI) where import Data.List (intersperse, intercalate) import System.IO (hFlush, stdout) import Verba.Solver (solve) import Verba.Dictionary (Dictionary) import Verba.Puzzle (Puzzle) import Verba.Formatting import Verba.Utils import qualified Verba.Dictionary as Dictionary import qualified Verba.Puzzle as Puzzle runCLI :: String -> IO () runCLI lang = do putStrLn . label . unlines $ [ "What's the matrix row by" , "row without spaces?" ] puz <- Puzzle.ask putStr "\n" putStrLn . label . unlines $ [ "What's the length of the" , "words separated by space?" ] lengths <- getLine >>= (return . map read . words) putStr "\n" putStrLn . label . unlines $ [ "Do you know some of the" , "words already?" ] knownWords <- getLine >>= (return . words) putStr "\n" dict <- Dictionary.loadAll lang lengths let sols = solve dict lengths puz putStrLn . label . unlines $ [ "Answer 'y' or press enter to" , "the following questions." ] let initFilter = filter (supersetOf knownWords) sols confirmSolutions (length lengths) knownWords initFilter putGuess :: String -> [String] -> [String] -> IO () putGuess guessedWord correctOnes guess = do let styledWords = map (\w -> if (w `elem` correctOnes) then success w else if w == guessedWord then warning w else w) guess putStr $ label "Is it " ++ (intercalate " " styledWords) ++ label "? " -- Takes a list of known solutions and a -- list of grouped solutions (pair of first word and -- rest of the solutions) and returns the list of confirmed solutions -- going deep as long as the user confirms. -- Once all options are exhausted, it returns back the list -- of confirmed solutions up until now. confirmSolutions :: Int -> [String] -> [[String]] -> IO () confirmSolutions _ _ [] = return () confirmSolutions n correctOnes (sol:sols) = do let guessedWord = head $ filter (not . (`elem` correctOnes)) sol putGuess guessedWord correctOnes sol hFlush stdout answer <- getLine if answer == "y" then let newCorrectOnes = guessedWord:correctOnes in if length newCorrectOnes == n then putStrLn . label $ "\nSeems like we are done." else confirmSolutions n newCorrectOnes (filter (elem guessedWord) (sol:sols)) else confirmSolutions n correctOnes (filter (not . elem guessedWord) sols)
Jefffrey/Verba
src/Verba/CLI.hs
mit
2,551
0
15
681
696
360
336
55
3
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} -- | Transformations on distilled expressions. Before transforming expressions, -- they should first be renumbered, type checked, and had their source -- annotations deleted. module Distill.Transform ( lambdaLift , aNormalizeExpr ) where import Control.Arrow import Control.Monad.Reader import Control.Monad.State import Data.Functor.Foldable hiding (Mu) import Data.List ((\\)) import Data.Maybe (fromJust) import Distill.Expr import Distill.Util -- | Lambda-lift a set of declarations into supercombinator form. lambdaLift :: (Eq b, Pretty b) => (b -> Int -> b) -> Int -> [Decl' b] -> [Decl' b] lambdaLift ctor start decls = let declTypes = map (\(Decl' x t _) -> (x, t)) decls state = mapM_ (lambdaLift' ctor declTypes) decls in snd $ snd $ runState state (start, []) -- | Lambda-lifts a single declaration into supercombinator form. lambdaLift' :: (Eq b, Pretty b) => (b -> Int -> b) -> [(b, Type' b)] -> Decl' b -> State (Int, [Decl' b]) () lambdaLift' ctor assumed (Decl' x t m) = do m' <- runReaderT (lambdaLiftOuter m) (x, assumed) addDecl (Decl' x t m') return () where -- Lift a lambda assuming we are at the top level. lambdaLiftOuter = \case lambda@Lambda{} -> do let (args, body) = splitLambda lambda let (xs, ts) = unzip args ts' <- mapM lambdaLiftInner ts let args' = zip xs ts' body' <- assumeArgs args $ lambdaLiftInner body return (unsplitLambda args' body') expr -> lambdaLiftInner expr -- Lift a lambda assuming we are inside another expression. lambdaLiftInner = \case lambda@Lambda{} -> do base <- lambdaLiftOuter lambda freeArgs <- (freeVars base \\) <$> boundVars completed <- unsplitLambda <$> createArgs freeArgs <*> pure base type_ <- typeof completed name <- createName addDecl (Decl' name type_ completed) return (unsplitApply (Var name : map Var freeArgs)) expr -> embed <$> sequence (lambdaLiftInner <$> project expr) -- Determine the set of variables bound by declarations. boundVars = map (\(Decl' x _ _) -> x) <$> snd <$> get -- Assume a set of arguments are a set of types in a sub-computation. assumeArgs args = local (second (args ++)) -- Create a new unique name for a declaration to use. createName = ctor <$> (fst <$> ask) <*> (fst <$> get <* modify (first succ)) -- Add a newly created declaration to the set of declarations. addDecl decl = modify (second (decl:)) -- Creates a list of (Var, Type) pairs, used as arguments for a lambda. createArgs names = do assumed <- snd <$> ask return (map (id &&& fromJust . flip lookup assumed) names) -- Determine the type of an expression. typeof expr = do assumed <- snd <$> ask decls <- snd <$> get let assumed' = assumed ++ map (\(Decl' x t _) -> (x, t)) decls let defined' = map (\(Decl' x _ m) -> (x, m)) decls let tcm = assumesIn assumed' $ definesIn defined' $ inferType expr return (fromRight (runTCM undefined tcm)) -- | Translate an expression into administrative normal form. aNormalizeExpr :: (Int -> b) -> Expr' b -> State Int (Expr' b) aNormalizeExpr ctor = aNormalizeOuter where -- Normalize expressions to A-normal form; assumes we are not in an apply. aNormalizeOuter expr = do (lets, expr') <- aNormalizeInner expr return (unsplitLet lets expr') -- Normalize expressions to simple values; this assumes we are in an apply. aNormalizeInner = \case Var x -> return ([], Var x) Star -> return ([], Star) Let x m n -> do (mlets, m') <- aNormalizeInner m (nlets, n') <- aNormalizeInner n return (mlets ++ [(x, m')] ++ nlets, n') Forall x t s -> do (tlets, t') <- aNormalizeInner t s' <- aNormalizeOuter s return (tlets, Forall x t' s') Lambda x t m -> do (tlets, t') <- aNormalizeInner t m' <- aNormalizeOuter m return (tlets, Lambda x t' m') apply@Apply{} -> do let args = splitApply apply (lets, args') <- unzip <$> mapM aNormalizeInner args let apply' = unsplitApply args' name <- createName return (concat lets ++ [(name, apply')], Var name) Mu x t s -> do (tlets, t') <- aNormalizeInner t s' <- aNormalizeOuter s return (tlets, Mu x t' s') Fold m t -> do (mlets, m') <- aNormalizeInner m (tlets, t') <- aNormalizeInner t return (mlets ++ tlets, Fold m' t') Unfold m -> do (mlets, m') <- aNormalizeInner m return (mlets, Unfold m') UnitT -> return ([], UnitT) UnitV -> return ([], UnitV) Product x t s -> do (tlets, t') <- aNormalizeInner t s' <- aNormalizeOuter s return (tlets, Product x t' s') Pack x m n s -> do (mlets, m') <- aNormalizeInner m (nlets, n') <- aNormalizeInner n s' <- aNormalizeOuter s return (mlets ++ nlets, Pack x m' n' s') Unpack m x y n -> do (mlets, m') <- aNormalizeInner m n' <- aNormalizeOuter n return (mlets, Unpack m' x y n') Coproduct ts -> do (tslets, ts') <- unzip <$> mapM aNormalizeInner ts return (concat tslets, Coproduct ts') Inject m i t -> do (mlets, m') <- aNormalizeInner m (tlets, t') <- aNormalizeInner t return (mlets ++ tlets, Inject m' i t') CaseOf m cs -> do (mlets, m') <- aNormalizeInner m cs' <- forM cs $ \(x, c) -> do c' <- aNormalizeOuter c return (x, c') return (mlets, CaseOf m' cs') CaseOfFalse m t -> do (mlets, m') <- aNormalizeInner m (tlets, t') <- aNormalizeInner t return (mlets ++ tlets, CaseOfFalse m' t') AnnotSource{} -> unstrippedError UnknownType{} -> unstrippedError createName = ctor <$> (get <* modify succ) unstrippedError = error "Unstripped annotations while A-normalizing."
DNoved1/distill
src/Distill/Transform.hs
mit
6,438
0
18
2,043
2,118
1,052
1,066
-1
-1
import Control.Arrow import Data.List main :: IO () main = do _ <- getLine interact $ lines >>> map (read >>> solve >>> showRes) >>> intercalate "\n" solve :: Integer -> Bool solve n = elem n $ takeWhile (<=n) fibs fibs :: [Integer] fibs = 0 : 1 : zipWith (+) fibs (tail fibs) showRes :: Bool -> String showRes True = "IsFibo" showRes False = "IsNotFibo"
Dobiasd/HackerRank-solutions
Algorithms/Warmup/Is_Fibo/Main.hs
mit
366
0
12
79
159
82
77
13
1
module Domain.Roles where import Database.Persist import DBTypes import Models import Operation import Data.Text import Control.Monad.Trans dbCreateRole :: MonadIO m => Role -> OperationT (TransactionT m) (Maybe RoleId) dbCreateRole = lift . insertUnique dbGetRole :: MonadIO m => RoleId -> TransactionT m (Maybe Role) dbGetRole = get dbGetRoles :: MonadIO m => TenantId -> TransactionT m [Entity Role] dbGetRoles tid = selectList [RoleTenant ==. tid] [] dbGetRoleByName :: MonadIO m => Text -> TenantId -> TransactionT m (Maybe (Entity Role)) dbGetRoleByName name tid = getBy (UniqueRoleName name tid)
wz1000/haskell-webapps
ServantPersistent/src/Domain/Roles.hs
mit
641
0
12
125
212
109
103
15
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE CPP #-} module Yesod.Form.Fields ( -- * i18n FormMessage (..) , defaultFormMessage -- * Fields , textField , passwordField , textareaField , hiddenField , intField , dayField , timeField , htmlField , emailField , multiEmailField , searchField , AutoFocus , urlField , doubleField , parseDate , parseTime , Textarea (..) , boolField , checkBoxField , fileField -- * File 'AForm's , fileAFormReq , fileAFormOpt -- * Options , selectField , selectFieldList , radioField , radioFieldList , checkboxesFieldList , checkboxesField , multiSelectField , multiSelectFieldList , Option (..) , OptionList (..) , mkOptionList , optionsPersist , optionsPersistKey , optionsPairs , optionsEnum ) where import Yesod.Form.Types import Yesod.Form.I18n.English import Yesod.Form.Functions (parseHelper) import Yesod.Core import Text.Hamlet import Text.Blaze (ToMarkup (toMarkup), unsafeByteString) #define ToHtml ToMarkup #define toHtml toMarkup #define preEscapedText preEscapedToMarkup import Text.Cassius import Data.Time (Day, TimeOfDay(..)) import qualified Text.Email.Validate as Email import Data.Text.Encoding (encodeUtf8, decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Network.URI (parseURI) import Database.Persist.Sql (PersistField, PersistFieldSql (..)) import Database.Persist (Entity (..), SqlType (SqlString)) import Text.HTML.SanitizeXSS (sanitizeBalance) import Control.Monad (when, unless) import Data.Either (partitionEithers) import Data.Maybe (listToMaybe, fromMaybe) import qualified Blaze.ByteString.Builder.Html.Utf8 as B import Blaze.ByteString.Builder (writeByteString, toLazyByteString) import Blaze.ByteString.Builder.Internal.Write (fromWriteList) import Database.Persist (PersistEntityBackend) import Text.Blaze.Html.Renderer.String (renderHtml) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.Text as T ( Text, append, concat, cons, head , intercalate, isPrefixOf, null, unpack, pack, splitOn ) import qualified Data.Text as T (drop, dropWhile) import qualified Data.Text.Read import qualified Data.Map as Map import Yesod.Persist (selectList, runDB, Filter, SelectOpt, Key, YesodPersist, PersistEntity, PersistQuery) import Control.Arrow ((&&&)) import Control.Applicative ((<$>), (<|>)) import Data.Attoparsec.Text (Parser, char, string, digit, skipSpace, endOfInput, parseOnly) import Yesod.Persist.Core defaultFormMessage :: FormMessage -> Text defaultFormMessage = englishFormMessage intField :: (Monad m, Integral i, RenderMessage (HandlerSite m) FormMessage) => Field m i intField = Field { fieldParse = parseHelper $ \s -> case Data.Text.Read.signed Data.Text.Read.decimal s of Right (a, "") -> Right a _ -> Left $ MsgInvalidInteger s , fieldView = \theId name attrs val isReq -> toWidget [hamlet| $newline never <input id="#{theId}" name="#{name}" *{attrs} type="number" step=1 :isReq:required="" value="#{showVal val}"> |] , fieldEnctype = UrlEncoded } where showVal = either id (pack . showI) showI x = show (fromIntegral x :: Integer) doubleField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Double doubleField = Field { fieldParse = parseHelper $ \s -> case Data.Text.Read.double (prependZero s) of Right (a, "") -> Right a _ -> Left $ MsgInvalidNumber s , fieldView = \theId name attrs val isReq -> toWidget [hamlet| $newline never <input id="#{theId}" name="#{name}" *{attrs} type="number" step=any :isReq:required="" value="#{showVal val}"> |] , fieldEnctype = UrlEncoded } where showVal = either id (pack . show) dayField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Day dayField = Field { fieldParse = parseHelper $ parseDate . unpack , fieldView = \theId name attrs val isReq -> toWidget [hamlet| $newline never <input id="#{theId}" name="#{name}" *{attrs} type="date" :isReq:required="" value="#{showVal val}"> |] , fieldEnctype = UrlEncoded } where showVal = either id (pack . show) timeField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m TimeOfDay timeField = Field { fieldParse = parseHelper parseTime , fieldView = \theId name attrs val isReq -> toWidget [hamlet| $newline never <input id="#{theId}" name="#{name}" *{attrs} :isReq:required="" value="#{showVal val}"> |] , fieldEnctype = UrlEncoded } where showVal = either id (pack . show . roundFullSeconds) roundFullSeconds tod = TimeOfDay (todHour tod) (todMin tod) fullSec where fullSec = fromInteger $ floor $ todSec tod htmlField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Html htmlField = Field { fieldParse = parseHelper $ Right . preEscapedText . sanitizeBalance , fieldView = \theId name attrs val isReq -> toWidget [hamlet| $newline never <textarea :isReq:required="" id="#{theId}" name="#{name}" *{attrs}>#{showVal val} |] , fieldEnctype = UrlEncoded } where showVal = either id (pack . renderHtml) -- | A newtype wrapper around a 'Text' that converts newlines to HTML -- br-tags. newtype Textarea = Textarea { unTextarea :: Text } deriving (Show, Read, Eq, PersistField, Ord, ToJSON, FromJSON) instance PersistFieldSql Textarea where sqlType _ = SqlString instance ToHtml Textarea where toHtml = unsafeByteString . S.concat . L.toChunks . toLazyByteString . fromWriteList writeHtmlEscapedChar . unpack . unTextarea where -- Taken from blaze-builder and modified with newline handling. writeHtmlEscapedChar '\n' = writeByteString "<br>" writeHtmlEscapedChar c = B.writeHtmlEscapedChar c textareaField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Textarea textareaField = Field { fieldParse = parseHelper $ Right . Textarea , fieldView = \theId name attrs val isReq -> toWidget [hamlet| $newline never <textarea id="#{theId}" name="#{name}" :isReq:required="" *{attrs}>#{either id unTextarea val} |] , fieldEnctype = UrlEncoded } hiddenField :: (Monad m, PathPiece p, RenderMessage (HandlerSite m) FormMessage) => Field m p hiddenField = Field { fieldParse = parseHelper $ maybe (Left MsgValueRequired) Right . fromPathPiece , fieldView = \theId name attrs val _isReq -> toWidget [hamlet| $newline never <input type="hidden" id="#{theId}" name="#{name}" *{attrs} value="#{either id toPathPiece val}"> |] , fieldEnctype = UrlEncoded } textField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text textField = Field { fieldParse = parseHelper $ Right , fieldView = \theId name attrs val isReq -> [whamlet| $newline never <input id="#{theId}" name="#{name}" *{attrs} type="text" :isReq:required value="#{either id id val}"> |] , fieldEnctype = UrlEncoded } passwordField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text passwordField = Field { fieldParse = parseHelper $ Right , fieldView = \theId name attrs val isReq -> toWidget [hamlet| $newline never <input id="#{theId}" name="#{name}" *{attrs} type="password" :isReq:required="" value="#{either id id val}"> |] , fieldEnctype = UrlEncoded } readMay :: Read a => String -> Maybe a readMay s = case filter (Prelude.null . snd) $ reads s of (x, _):_ -> Just x [] -> Nothing parseDate :: String -> Either FormMessage Day parseDate = maybe (Left MsgInvalidDay) Right . readMay . replace '/' '-' -- | Replaces all instances of a value in a list by another value. -- from http://hackage.haskell.org/packages/archive/cgi/3001.1.7.1/doc/html/src/Network-CGI-Protocol.html#replace replace :: Eq a => a -> a -> [a] -> [a] replace x y = map (\z -> if z == x then y else z) parseTime :: Text -> Either FormMessage TimeOfDay parseTime = either (Left . fromMaybe MsgInvalidTimeFormat . readMay . drop 2 . dropWhile (/= ':')) Right . parseOnly timeParser timeParser :: Parser TimeOfDay timeParser = do skipSpace h <- hour _ <- char ':' m <- minsec MsgInvalidMinute hasSec <- (char ':' >> return True) <|> return False s <- if hasSec then minsec MsgInvalidSecond else return 0 skipSpace isPM <- (string "am" >> return (Just False)) <|> (string "AM" >> return (Just False)) <|> (string "pm" >> return (Just True)) <|> (string "PM" >> return (Just True)) <|> return Nothing h' <- case isPM of Nothing -> return h Just x | h <= 0 || h > 12 -> fail $ show $ MsgInvalidHour $ pack $ show h | h == 12 -> return $ if x then 12 else 0 | otherwise -> return $ h + (if x then 12 else 0) skipSpace endOfInput return $ TimeOfDay h' m s where hour = do x <- digit y <- (return <$> digit) <|> return [] let xy = x : y let i = read xy if i < 0 || i >= 24 then fail $ show $ MsgInvalidHour $ pack xy else return i minsec :: Num a => (Text -> FormMessage) -> Parser a minsec msg = do x <- digit y <- digit <|> fail (show $ msg $ pack [x]) let xy = [x, y] let i = read xy if i < 0 || i >= 60 then fail $ show $ msg $ pack xy else return $ fromIntegral (i :: Int) emailField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text emailField = Field { fieldParse = parseHelper $ \s -> case Email.canonicalizeEmail $ encodeUtf8 s of Just e -> Right $ decodeUtf8With lenientDecode e Nothing -> Left $ MsgInvalidEmail s , fieldView = \theId name attrs val isReq -> toWidget [hamlet| $newline never <input id="#{theId}" name="#{name}" *{attrs} type="email" :isReq:required="" value="#{either id id val}"> |] , fieldEnctype = UrlEncoded } -- | -- -- Since 1.3.7 multiEmailField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m [Text] multiEmailField = Field { fieldParse = parseHelper $ \s -> let addrs = map validate $ splitOn "," s in case partitionEithers addrs of ([], good) -> Right good (bad, _) -> Left $ MsgInvalidEmail $ cat bad , fieldView = \theId name attrs val isReq -> toWidget [hamlet| $newline never <input id="#{theId}" name="#{name}" *{attrs} type="email" multiple :isReq:required="" value="#{either id cat val}"> |] , fieldEnctype = UrlEncoded } where -- report offending address along with error validate a = case Email.validate $ encodeUtf8 a of Left e -> Left $ T.concat [a, " (", pack e, ")"] Right r -> Right $ emailToText r cat = intercalate ", " emailToText = decodeUtf8With lenientDecode . Email.toByteString type AutoFocus = Bool searchField :: Monad m => RenderMessage (HandlerSite m) FormMessage => AutoFocus -> Field m Text searchField autoFocus = Field { fieldParse = parseHelper Right , fieldView = \theId name attrs val isReq -> do [whamlet| $newline never <input id="#{theId}" name="#{name}" *{attrs} type="search" :isReq:required="" :autoFocus:autofocus="" value="#{either id id val}"> |] when autoFocus $ do -- we want this javascript to be placed immediately after the field [whamlet| $newline never <script>if (!('autofocus' in document.createElement('input'))) {document.getElementById('#{theId}').focus();} |] toWidget [cassius| ##{theId} -webkit-appearance: textfield |] , fieldEnctype = UrlEncoded } urlField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text urlField = Field { fieldParse = parseHelper $ \s -> case parseURI $ unpack s of Nothing -> Left $ MsgInvalidUrl s Just _ -> Right s , fieldView = \theId name attrs val isReq -> [whamlet|<input ##{theId} name=#{name} *{attrs} type=url :isReq:required value=#{either id id val}>|] , fieldEnctype = UrlEncoded } selectFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg) => [(msg, a)] -> Field (HandlerT site IO) a selectFieldList = selectField . optionsPairs selectField :: (Eq a, RenderMessage site FormMessage) => HandlerT site IO (OptionList a) -> Field (HandlerT site IO) a selectField = selectFieldHelper (\theId name attrs inside -> [whamlet| $newline never <select ##{theId} name=#{name} *{attrs}>^{inside} |]) -- outside (\_theId _name isSel -> [whamlet| $newline never <option value=none :isSel:selected>_{MsgSelectNone} |]) -- onOpt (\_theId _name _attrs value isSel text -> [whamlet| $newline never <option value=#{value} :isSel:selected>#{text} |]) -- inside multiSelectFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg) => [(msg, a)] -> Field (HandlerT site IO) [a] multiSelectFieldList = multiSelectField . optionsPairs multiSelectField :: (Eq a, RenderMessage site FormMessage) => HandlerT site IO (OptionList a) -> Field (HandlerT site IO) [a] multiSelectField ioptlist = Field parse view UrlEncoded where parse [] _ = return $ Right Nothing parse optlist _ = do mapopt <- olReadExternal <$> ioptlist case mapM mapopt optlist of Nothing -> return $ Left "Error parsing values" Just res -> return $ Right $ Just res view theId name attrs val isReq = do opts <- fmap olOptions $ handlerToWidget ioptlist let selOpts = map (id &&& (optselected val)) opts [whamlet| <select ##{theId} name=#{name} :isReq:required multiple *{attrs}> $forall (opt, optsel) <- selOpts <option value=#{optionExternalValue opt} :optsel:selected>#{optionDisplay opt} |] where optselected (Left _) _ = False optselected (Right vals) opt = (optionInternalValue opt) `elem` vals radioFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg) => [(msg, a)] -> Field (HandlerT site IO) a radioFieldList = radioField . optionsPairs checkboxesFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg) => [(msg, a)] -> Field (HandlerT site IO) [a] checkboxesFieldList = checkboxesField . optionsPairs checkboxesField :: (Eq a, RenderMessage site FormMessage) => HandlerT site IO (OptionList a) -> Field (HandlerT site IO) [a] checkboxesField ioptlist = (multiSelectField ioptlist) { fieldView = \theId name attrs val isReq -> do opts <- fmap olOptions $ handlerToWidget ioptlist let optselected (Left _) _ = False optselected (Right vals) opt = (optionInternalValue opt) `elem` vals [whamlet| <span ##{theId}> $forall opt <- opts <label> <input type=checkbox name=#{name} value=#{optionExternalValue opt} *{attrs} :optselected val opt:checked> #{optionDisplay opt} |] } radioField :: (Eq a, RenderMessage site FormMessage) => HandlerT site IO (OptionList a) -> Field (HandlerT site IO) a radioField = selectFieldHelper (\theId _name _attrs inside -> [whamlet| $newline never <div ##{theId}>^{inside} |]) (\theId name isSel -> [whamlet| $newline never <label .radio for=#{theId}-none> <div> <input id=#{theId}-none type=radio name=#{name} value=none :isSel:checked> _{MsgSelectNone} |]) (\theId name attrs value isSel text -> [whamlet| $newline never <label .radio for=#{theId}-#{value}> <div> <input id=#{theId}-#{value} type=radio name=#{name} value=#{value} :isSel:checked *{attrs}> \#{text} |]) boolField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Bool boolField = Field { fieldParse = \e _ -> return $ boolParser e , fieldView = \theId name attrs val isReq -> [whamlet| $newline never $if not isReq <input id=#{theId}-none *{attrs} type=radio name=#{name} value=none checked> <label for=#{theId}-none>_{MsgSelectNone} <input id=#{theId}-yes *{attrs} type=radio name=#{name} value=yes :showVal id val:checked> <label for=#{theId}-yes>_{MsgBoolYes} <input id=#{theId}-no *{attrs} type=radio name=#{name} value=no :showVal not val:checked> <label for=#{theId}-no>_{MsgBoolNo} |] , fieldEnctype = UrlEncoded } where boolParser [] = Right Nothing boolParser (x:_) = case x of "" -> Right Nothing "none" -> Right Nothing "yes" -> Right $ Just True "on" -> Right $ Just True "no" -> Right $ Just False "true" -> Right $ Just True "false" -> Right $ Just False t -> Left $ SomeMessage $ MsgInvalidBool t showVal = either (\_ -> False) -- | While the default @'boolField'@ implements a radio button so you -- can differentiate between an empty response (Nothing) and a no -- response (Just False), this simpler checkbox field returns an empty -- response as Just False. -- -- Note that this makes the field always optional. -- checkBoxField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Bool checkBoxField = Field { fieldParse = \e _ -> return $ checkBoxParser e , fieldView = \theId name attrs val _ -> [whamlet| $newline never <input id=#{theId} *{attrs} type=checkbox name=#{name} value=yes :showVal id val:checked> |] , fieldEnctype = UrlEncoded } where checkBoxParser [] = Right $ Just False checkBoxParser (x:_) = case x of "yes" -> Right $ Just True "on" -> Right $ Just True _ -> Right $ Just False showVal = either (\_ -> False) data OptionList a = OptionList { olOptions :: [Option a] , olReadExternal :: Text -> Maybe a } mkOptionList :: [Option a] -> OptionList a mkOptionList os = OptionList { olOptions = os , olReadExternal = flip Map.lookup $ Map.fromList $ map (optionExternalValue &&& optionInternalValue) os } data Option a = Option { optionDisplay :: Text , optionInternalValue :: a , optionExternalValue :: Text } optionsPairs :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => [(msg, a)] -> m (OptionList a) optionsPairs opts = do mr <- getMessageRender let mkOption external (display, internal) = Option { optionDisplay = mr display , optionInternalValue = internal , optionExternalValue = pack $ show external } return $ mkOptionList (zipWith mkOption [1 :: Int ..] opts) optionsEnum :: (MonadHandler m, Show a, Enum a, Bounded a) => m (OptionList a) optionsEnum = optionsPairs $ map (\x -> (pack $ show x, x)) [minBound..maxBound] optionsPersist :: ( YesodPersist site, PersistEntity a , PersistQuery (PersistEntityBackend a) , PathPiece (Key a) , RenderMessage site msg , YesodPersistBackend site ~ PersistEntityBackend a ) => [Filter a] -> [SelectOpt a] -> (a -> msg) -> HandlerT site IO (OptionList (Entity a)) optionsPersist filts ords toDisplay = fmap mkOptionList $ do mr <- getMessageRender pairs <- runDB $ selectList filts ords return $ map (\(Entity key value) -> Option { optionDisplay = mr (toDisplay value) , optionInternalValue = Entity key value , optionExternalValue = toPathPiece key }) pairs -- | An alternative to 'optionsPersist' which returns just the @Key@ instead of -- the entire @Entity@. -- -- Since 1.3.2 optionsPersistKey :: (YesodPersist site , PersistEntity a , PersistQuery (PersistEntityBackend a) , PathPiece (Key a) , RenderMessage site msg , YesodPersistBackend site ~ PersistEntityBackend a ) => [Filter a] -> [SelectOpt a] -> (a -> msg) -> HandlerT site IO (OptionList (Key a)) optionsPersistKey filts ords toDisplay = fmap mkOptionList $ do mr <- getMessageRender pairs <- runDB $ selectList filts ords return $ map (\(Entity key value) -> Option { optionDisplay = mr (toDisplay value) , optionInternalValue = key , optionExternalValue = toPathPiece key }) pairs selectFieldHelper :: (Eq a, RenderMessage site FormMessage) => (Text -> Text -> [(Text, Text)] -> WidgetT site IO () -> WidgetT site IO ()) -> (Text -> Text -> Bool -> WidgetT site IO ()) -> (Text -> Text -> [(Text, Text)] -> Text -> Bool -> Text -> WidgetT site IO ()) -> HandlerT site IO (OptionList a) -> Field (HandlerT site IO) a selectFieldHelper outside onOpt inside opts' = Field { fieldParse = \x _ -> do opts <- opts' return $ selectParser opts x , fieldView = \theId name attrs val isReq -> do opts <- fmap olOptions $ handlerToWidget opts' outside theId name attrs $ do unless isReq $ onOpt theId name $ not $ render opts val `elem` map optionExternalValue opts flip mapM_ opts $ \opt -> inside theId name ((if isReq then (("required", "required"):) else id) attrs) (optionExternalValue opt) ((render opts val) == optionExternalValue opt) (optionDisplay opt) , fieldEnctype = UrlEncoded } where render _ (Left _) = "" render opts (Right a) = maybe "" optionExternalValue $ listToMaybe $ filter ((== a) . optionInternalValue) opts selectParser _ [] = Right Nothing selectParser opts (s:_) = case s of "" -> Right Nothing "none" -> Right Nothing x -> case olReadExternal opts x of Nothing -> Left $ SomeMessage $ MsgInvalidEntry x Just y -> Right $ Just y fileField :: (Monad m, RenderMessage (HandlerSite m) FormMessage) => Field m FileInfo fileField = Field { fieldParse = \_ files -> return $ case files of [] -> Right Nothing file:_ -> Right $ Just file , fieldView = \id' name attrs _ isReq -> toWidget [hamlet| <input id=#{id'} name=#{name} *{attrs} type=file :isReq:required> |] , fieldEnctype = Multipart } fileAFormReq :: (MonadHandler m, RenderMessage (HandlerSite m) FormMessage) => FieldSettings (HandlerSite m) -> AForm m FileInfo fileAFormReq fs = AForm $ \(site, langs) menvs ints -> do let (name, ints') = case fsName fs of Just x -> (x, ints) Nothing -> let i' = incrInts ints in (pack $ 'f' : show i', i') id' <- maybe newIdent return $ fsId fs let (res, errs) = case menvs of Nothing -> (FormMissing, Nothing) Just (_, fenv) -> case Map.lookup name fenv of Just (fi:_) -> (FormSuccess fi, Nothing) _ -> let t = renderMessage site langs MsgValueRequired in (FormFailure [t], Just $ toHtml t) let fv = FieldView { fvLabel = toHtml $ renderMessage site langs $ fsLabel fs , fvTooltip = fmap (toHtml . renderMessage site langs) $ fsTooltip fs , fvId = id' , fvInput = [whamlet| $newline never <input type=file name=#{name} ##{id'} *{fsAttrs fs}> |] , fvErrors = errs , fvRequired = True } return (res, (fv :), ints', Multipart) fileAFormOpt :: MonadHandler m => RenderMessage (HandlerSite m) FormMessage => FieldSettings (HandlerSite m) -> AForm m (Maybe FileInfo) fileAFormOpt fs = AForm $ \(master, langs) menvs ints -> do let (name, ints') = case fsName fs of Just x -> (x, ints) Nothing -> let i' = incrInts ints in (pack $ 'f' : show i', i') id' <- maybe newIdent return $ fsId fs let (res, errs) = case menvs of Nothing -> (FormMissing, Nothing) Just (_, fenv) -> case Map.lookup name fenv of Just (fi:_) -> (FormSuccess $ Just fi, Nothing) _ -> (FormSuccess Nothing, Nothing) let fv = FieldView { fvLabel = toHtml $ renderMessage master langs $ fsLabel fs , fvTooltip = fmap (toHtml . renderMessage master langs) $ fsTooltip fs , fvId = id' , fvInput = [whamlet| $newline never <input type=file name=#{name} ##{id'} *{fsAttrs fs}> |] , fvErrors = errs , fvRequired = False } return (res, (fv :), ints', Multipart) incrInts :: Ints -> Ints incrInts (IntSingle i) = IntSingle $ i + 1 incrInts (IntCons i is) = (i + 1) `IntCons` is -- | Adds a '0' to some text so that it may be recognized as a double. -- The read ftn does not recognize ".3" as 0.3 nor "-.3" as -0.3, so this -- function changes ".xxx" to "0.xxx" and "-.xxx" to "-0.xxx" prependZero :: Text -> Text prependZero t0 = if T.null t1 then t1 else if T.head t1 == '.' then '0' `T.cons` t1 else if "-." `T.isPrefixOf` t1 then "-0." `T.append` (T.drop 2 t1) else t1 where t1 = T.dropWhile ((==) ' ') t0
wujf/yesod
yesod-form/Yesod/Form/Fields.hs
mit
26,432
0
22
7,368
7,078
3,790
3,288
-1
-1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.ANGLEInstancedArrays (js_drawArraysInstancedANGLE, drawArraysInstancedANGLE, js_drawElementsInstancedANGLE, drawElementsInstancedANGLE, js_vertexAttribDivisorANGLE, vertexAttribDivisorANGLE, pattern VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE, ANGLEInstancedArrays, castToANGLEInstancedArrays, gTypeANGLEInstancedArrays) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"drawArraysInstancedANGLE\"]($2,\n$3, $4, $5)" js_drawArraysInstancedANGLE :: ANGLEInstancedArrays -> Word -> Int -> Int -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/ANGLEInstancedArrays.drawArraysInstancedANGLE Mozilla ANGLEInstancedArrays.drawArraysInstancedANGLE documentation> drawArraysInstancedANGLE :: (MonadIO m) => ANGLEInstancedArrays -> Word -> Int -> Int -> Int -> m () drawArraysInstancedANGLE self mode first count primcount = liftIO (js_drawArraysInstancedANGLE (self) mode first count primcount) foreign import javascript unsafe "$1[\"drawElementsInstancedANGLE\"]($2,\n$3, $4, $5, $6)" js_drawElementsInstancedANGLE :: ANGLEInstancedArrays -> Word -> Int -> Word -> Double -> Int -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/ANGLEInstancedArrays.drawElementsInstancedANGLE Mozilla ANGLEInstancedArrays.drawElementsInstancedANGLE documentation> drawElementsInstancedANGLE :: (MonadIO m) => ANGLEInstancedArrays -> Word -> Int -> Word -> Int64 -> Int -> m () drawElementsInstancedANGLE self mode count type' offset primcount = liftIO (js_drawElementsInstancedANGLE (self) mode count type' (fromIntegral offset) primcount) foreign import javascript unsafe "$1[\"vertexAttribDivisorANGLE\"]($2,\n$3)" js_vertexAttribDivisorANGLE :: ANGLEInstancedArrays -> Word -> Word -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/ANGLEInstancedArrays.vertexAttribDivisorANGLE Mozilla ANGLEInstancedArrays.vertexAttribDivisorANGLE documentation> vertexAttribDivisorANGLE :: (MonadIO m) => ANGLEInstancedArrays -> Word -> Word -> m () vertexAttribDivisorANGLE self index divisor = liftIO (js_vertexAttribDivisorANGLE (self) index divisor) pattern VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 35070
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/ANGLEInstancedArrays.hs
mit
3,266
40
9
568
655
382
273
50
1
type Peg = String type Move = (Peg, Peg) hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] hanoi 1 orig dest temp = [(orig, dest)] hanoi n orig dest temp = hanoi (n-1) orig temp dest ++ [(orig, dest)] ++ hanoi (n-1) temp dest orig
julitopower/HaskellLearning
hanoi.hs
mit
230
0
9
49
129
71
58
5
1
module Philed.Data.Rect (Rect, left, right, top, bottom, topLeft, topRight, bottomLeft, bottomRight, width, height, mkRect) where import Control.Applicative import Data.Binary import Philed.Data.Vector import Philed.Data.NNeg import Test.QuickCheck.Arbitrary data Rect a = Rect { bottomLeft :: Vec a, width :: NNeg a, height :: NNeg a } deriving (Eq, Ord, Show) left :: Num a => Rect a -> a left = fst . bottomLeft right :: Num a => Rect a -> a right = fst . topRight top :: Num a => Rect a -> a top = snd . topRight bottom :: Num a => Rect a -> a bottom = snd . bottomLeft topLeft :: Num a => Rect a -> Vec a topLeft r = bottomLeft r +. (0, extract $ height r) bottomRight :: Num a => Rect a -> Vec a bottomRight r = bottomLeft r +. (extract $ width r, 0) topRight :: Num a => Rect a -> Vec a topRight r = bottomLeft r +. (extract $ width r, extract $ height r) mkRect :: Num a => Vec a -> NNeg a -> NNeg a -> Rect a mkRect = Rect instance Binary a => Binary (Rect a) where put (Rect bl w h) = put bl >> put w >> put h get = liftA3 Rect get get get instance Arbitrary a => Arbitrary (Rect a) where arbitrary = Rect <$> arbitrary <*> arbitrary <*> arbitrary instance CoArbitrary a => CoArbitrary (Rect a) where coarbitrary (Rect (x,y) w h) = coarbitrary ((x,y),w,h)
Chattered/PhilEdCommon
Philed/Data/Rect.hs
mit
1,374
0
9
359
606
313
293
34
1
import Data.Char import qualified Data.List as L superDigit :: Int -> Int superDigit n = if n `div` 10 == 0 then n else superDigit $ sum $ map (\x -> ord x - ord '0') $ show n main = do line <- getLine let [num,times] = (words line) n = (read times) :: Int tmp = sum $ map (\x -> ord x - ord '0') num putStrLn $ show $ superDigit $ tmp * n
m00nlight/hackerrank
functional/recursion/Super-Digits/main.hs
gpl-2.0
429
0
15
167
184
96
88
14
2
module DarkPlaces.ProtocolConstants where u_morebits_bit :: Int u_morebits_bit = 0 u_origin1_bit :: Int u_origin1_bit = 1 u_origin2_bit :: Int u_origin2_bit = 2 u_origin3_bit :: Int u_origin3_bit = 3 u_angle2_bit :: Int u_angle2_bit = 4 u_step_bit :: Int u_step_bit = 5 u_frame_bit :: Int u_frame_bit = 6 u_signal_bit :: Int u_signal_bit = 7 u_angle1_bit :: Int u_angle1_bit = 8 u_angle3_bit :: Int u_angle3_bit = 9 u_model_bit :: Int u_model_bit = 10 u_colormap_bit :: Int u_colormap_bit = 11 u_skin_bit :: Int u_skin_bit = 12 u_effects_bit :: Int u_effects_bit = 13 u_longentity_bit :: Int u_longentity_bit = 14 u_extend1_bit :: Int u_extend1_bit = 15 u_delta_bit :: Int u_delta_bit = 16 u_alpha_bit :: Int u_alpha_bit = 17 u_scale_bit :: Int u_scale_bit = 18 u_effects2_bit :: Int u_effects2_bit = 19 u_glowsize_bit :: Int u_glowsize_bit = 20 u_glowcolor_bit :: Int u_glowcolor_bit = 21 u_colormod_bit :: Int u_colormod_bit = 22 u_extend2_bit :: Int u_extend2_bit = 23 u_glowtrail_bit :: Int u_glowtrail_bit = 24 u_viewmodel_bit :: Int u_viewmodel_bit = 25 u_frame2_bit :: Int u_frame2_bit = 26 u_model2_bit :: Int u_model2_bit = 27 u_exteriormodel_bit :: Int u_exteriormodel_bit = 28 u_unused29_bit :: Int u_unused29_bit = 29 u_unused30_bit :: Int u_unused30_bit = 30 u_extend3_bit :: Int u_extend3_bit = 31 su_viewheight_bit :: Int su_viewheight_bit = 0 su_idealpitch_bit :: Int su_idealpitch_bit = 1 su_punch1_bit :: Int su_punch1_bit = 2 su_punch2_bit :: Int su_punch2_bit = 3 su_punch3_bit :: Int su_punch3_bit = 4 su_velocity1_bit :: Int su_velocity1_bit = 5 su_velocity2_bit :: Int su_velocity2_bit = 6 su_velocity3_bit :: Int su_velocity3_bit = 7 su_items_bit :: Int su_items_bit = 9 su_onground_bit :: Int su_onground_bit = 10 su_inwater_bit :: Int su_inwater_bit = 11 su_weaponframe_bit :: Int su_weaponframe_bit = 12 su_armor_bit :: Int su_armor_bit = 13 su_weapon_bit :: Int su_weapon_bit = 14 su_extend1_bit :: Int su_extend1_bit = 15 su_punchvec1_bit :: Int su_punchvec1_bit = 16 su_punchvec2_bit :: Int su_punchvec2_bit = 17 su_punchvec3_bit :: Int su_punchvec3_bit = 18 su_viewzoom_bit :: Int su_viewzoom_bit = 19 su_unused20_bit :: Int su_unused20_bit = 20 su_unused21_bit :: Int su_unused21_bit = 21 su_unused22_bit :: Int su_unused22_bit = 22 su_extend2_bit :: Int su_extend2_bit = 23 su_unused24_bit :: Int su_unused24_bit = 24 su_unused25_bit :: Int su_unused25_bit = 25 su_unused26_bit :: Int su_unused26_bit = 26 su_unused27_bit :: Int su_unused27_bit = 27 su_unused28_bit :: Int su_unused28_bit = 28 su_unused29_bit :: Int su_unused29_bit = 29 su_unused30_bit :: Int su_unused30_bit = 30 su_extend3_bit :: Int su_extend3_bit = 31 snd_volume_bit :: Int snd_volume_bit = 0 snd_attenuation_bit :: Int snd_attenuation_bit = 1 snd_looping_bit :: Int snd_looping_bit = 2 snd_largeentity_bit :: Int snd_largeentity_bit = 3 snd_largesound_bit :: Int snd_largesound_bit = 4 snd_speedushort4000_bit :: Int snd_speedushort4000_bit = 5 e_origin1_bit :: Int e_origin1_bit = 0 e_origin2_bit :: Int e_origin2_bit = 1 e_origin3_bit :: Int e_origin3_bit = 2 e_angle1_bit :: Int e_angle1_bit = 3 e_angle2_bit :: Int e_angle2_bit = 4 e_angle3_bit :: Int e_angle3_bit = 5 e_model1_bit :: Int e_model1_bit = 6 e_extend1_bit :: Int e_extend1_bit = 7 e_frame1_bit :: Int e_frame1_bit = 8 e_effects1_bit :: Int e_effects1_bit = 9 e_alpha_bit :: Int e_alpha_bit = 10 e_scale_bit :: Int e_scale_bit = 11 e_colormap_bit :: Int e_colormap_bit = 12 e_skin_bit :: Int e_skin_bit = 13 e_flags_bit :: Int e_flags_bit = 14 e_extend2_bit :: Int e_extend2_bit = 15 e_frame2_bit :: Int e_frame2_bit = 16 e_model2_bit :: Int e_model2_bit = 17 e_effects2_bit :: Int e_effects2_bit = 18 e_glowsize_bit :: Int e_glowsize_bit = 19 e_glowcolor_bit :: Int e_glowcolor_bit = 20 e_light_bit :: Int e_light_bit = 21 e_lightpflags_bit :: Int e_lightpflags_bit = 22 e_extend3_bit :: Int e_extend3_bit = 23 e_sound1_bit :: Int e_sound1_bit = 24 e_soundvol_bit :: Int e_soundvol_bit = 25 e_soundatten_bit :: Int e_soundatten_bit = 26 e_tagattachment_bit :: Int e_tagattachment_bit = 27 e_lightstyle_bit :: Int e_lightstyle_bit = 28 e_unused6_bit :: Int e_unused6_bit = 29 e_unused7_bit :: Int e_unused7_bit = 30 e_extend4_bit :: Int e_extend4_bit = 31 e5_fullupdate_bit :: Int e5_fullupdate_bit = 0 e5_origin_bit :: Int e5_origin_bit = 1 e5_angles_bit :: Int e5_angles_bit = 2 e5_model_bit :: Int e5_model_bit = 3 e5_frame_bit :: Int e5_frame_bit = 4 e5_skin_bit :: Int e5_skin_bit = 5 e5_effects_bit :: Int e5_effects_bit = 6 e5_extend1_bit :: Int e5_extend1_bit = 7 e5_flags_bit :: Int e5_flags_bit = 8 e5_alpha_bit :: Int e5_alpha_bit = 9 e5_scale_bit :: Int e5_scale_bit = 10 e5_origin32_bit :: Int e5_origin32_bit = 11 e5_angles16_bit :: Int e5_angles16_bit = 12 e5_model16_bit :: Int e5_model16_bit = 13 e5_colormap_bit :: Int e5_colormap_bit = 14 e5_extend2_bit :: Int e5_extend2_bit = 15 e5_attachment_bit :: Int e5_attachment_bit = 16 e5_light_bit :: Int e5_light_bit = 17 e5_glow_bit :: Int e5_glow_bit = 18 e5_effects16_bit :: Int e5_effects16_bit = 19 e5_effects32_bit :: Int e5_effects32_bit = 20 e5_frame16_bit :: Int e5_frame16_bit = 21 e5_colormod_bit :: Int e5_colormod_bit = 22 e5_extend3_bit :: Int e5_extend3_bit = 23 e5_glowmod_bit :: Int e5_glowmod_bit = 24 e5_complexanimation_bit :: Int e5_complexanimation_bit = 25 e5_traileffectnum_bit :: Int e5_traileffectnum_bit = 26 e5_unused27_bit :: Int e5_unused27_bit = 27 e5_unused28_bit :: Int e5_unused28_bit = 28 e5_unused29_bit :: Int e5_unused29_bit = 29 e5_unused30_bit :: Int e5_unused30_bit = 30 e5_extend4_bit :: Int e5_extend4_bit = 31 qw_pf_msec_bit :: Int qw_pf_msec_bit = 0 qw_pf_command_bit :: Int qw_pf_command_bit = 1 qw_pf_velocity1_bit :: Int qw_pf_velocity1_bit = 2 qw_pf_velocity2_bit :: Int qw_pf_velocity2_bit = 3 qw_pf_velocity3_bit :: Int qw_pf_velocity3_bit = 4 qw_pf_model_bit :: Int qw_pf_model_bit = 5 qw_pf_skinnum_bit :: Int qw_pf_skinnum_bit = 6 qw_pf_effects_bit :: Int qw_pf_effects_bit = 7 qw_pf_weaponframe_bit :: Int qw_pf_weaponframe_bit = 8 qw_pf_dead_bit :: Int qw_pf_dead_bit = 9 qw_pf_gib_bit :: Int qw_pf_gib_bit = 10 qw_pf_nograv_bit :: Int qw_pf_nograv_bit = 11 qw_cm_angle1_bit :: Int qw_cm_angle1_bit = 0 qw_cm_angle3_bit :: Int qw_cm_angle3_bit = 1 qw_cm_forward_bit :: Int qw_cm_forward_bit = 2 qw_cm_side_bit :: Int qw_cm_side_bit = 3 qw_cm_up_bit :: Int qw_cm_up_bit = 4 qw_cm_buttons_bit :: Int qw_cm_buttons_bit = 5 qw_cm_impulse_bit :: Int qw_cm_impulse_bit = 6 qw_cm_angle2_bit :: Int qw_cm_angle2_bit = 7 qw_u_origin1_bit :: Int qw_u_origin1_bit = 9 qw_u_origin2_bit :: Int qw_u_origin2_bit = 10 qw_u_origin3_bit :: Int qw_u_origin3_bit = 11 qw_u_angle2_bit :: Int qw_u_angle2_bit = 12 qw_u_frame_bit :: Int qw_u_frame_bit = 13 qw_u_remove_bit :: Int qw_u_remove_bit = 14 qw_u_morebits_bit :: Int qw_u_morebits_bit = 15 qw_u_angle1_bit :: Int qw_u_angle1_bit = 0 qw_u_angle3_bit :: Int qw_u_angle3_bit = 1 qw_u_model_bit :: Int qw_u_model_bit = 2 qw_u_colormap_bit :: Int qw_u_colormap_bit = 3 qw_u_skin_bit :: Int qw_u_skin_bit = 4 qw_u_effects_bit :: Int qw_u_effects_bit = 5 qw_u_solid_bit :: Int qw_u_solid_bit = 6
bacher09/darkplaces-demo
src/DarkPlaces/ProtocolConstants.hs
gpl-2.0
7,121
0
4
1,007
1,676
1,006
670
335
1
module OpenBookModule where import System.Random import System.IO.Unsafe import Board import MoveModule import FileModule type OpeningBook = [(Int, Int, String, String)] --Every move represented by a 4-tuple (ID, Parent, White, Black). --Black king side castling: e8g8 --Black queen side castling: e8c8 --White king side castling: e1g1 --White queen side castling: e1c1 --The filepath for openBookTree. openBookTreePath::FilePath openBookTreePath = "../data/open_book_tree.dat" --Function to load the opening book tree given filepath. loadMovesArray::FilePath -> OpeningBook loadMovesArray fpath = read (unsafePerformIO $ loadFromFile fpath)::OpeningBook --Abstraction to load opening book tree. movesArray::OpeningBook movesArray = loadMovesArray openBookTreePath --Extract the parent's ID from a node. getParentID::(Int, Int, String, String) -> Int getParentID (_, parent, _, _) = parent --Extract the ID from a node. getID::(Int, Int, String, String) -> Int getID (id_, _, _, _) = id_ --Extract the black move from a node. getBlackMove::(Int, Int, String, String) -> String getBlackMove (_, _, _, black) = black --Extract the white move from a node. getWhiteMove::(Int, Int, String, String) -> String getWhiteMove (_, _, white, _) = white --Extratc both white and black moves in that order. getBothMoves::(Int, Int, String, String) -> (String, String) getBothMoves x = (getWhiteMove x, getBlackMove x) --Given ID number of the node and the movesArray, extract the node getNodeFromArray::Int -> OpeningBook -> (Int, Int, String, String) getNodeFromArray _ [] = (-1, -1, "NULL", "NULL") getNodeFromArray id_ (x:xs) = if (getID x) == id_ then x else (getNodeFromArray id_ xs) -- Given the ID number of the node, extracts the node from the tree. getNode::Int -> OpeningBook -> (Int, Int, String, String) getNode id_ openingBook = getNodeFromArray id_ openingBook --Given an array and the parent's ID, extracts a list of children IDs. getChildrenFromArray::Int -> OpeningBook -> [Int] getChildrenFromArray _ [] = [] getChildrenFromArray pid (x:xs) = if (getParentID x) == pid then [(getID x)]++(getChildrenFromArray pid xs) else (getChildrenFromArray pid xs) --The wrapper function for getChildrenFromArrat to abstract the loading of the opening tree. getChildren::Int -> OpeningBook -> [Int] getChildren pid openingBook= getChildrenFromArray pid openingBook --Given a list of IDs and a move, matches the move to ID and returns the ID of the matching move. matchChild::[Int] -> (String, String) -> OpeningBook-> Int matchChild [] _ _= -2 matchChild (x:xs) (white, black) openingBook = if (and [(getWhiteMove$(getNode x openingBook)) == white, (getBlackMove$(getNode x openingBook)) == black]) then (getID$(getNode x openingBook)) else (matchChild xs (white, black) openingBook) --Takes a parent ID and the move sequence and matches the sequence to yield the final list of children matchSequence::Int -> [(String, String)] -> OpeningBook -> [Int] matchSequence (-2) _ _= [-2] matchSequence pid [] openingBook = getChildren pid openingBook matchSequence pid (x:xs) openingBook = matchSequence (matchChild (getChildren pid openingBook) x openingBook) xs openingBook --Given a list, randomly select one element. selectRandomMove::[Int] -> Int selectRandomMove [] = -1 selectRandomMove xs = unsafePerformIO $ fmap (xs!!) $ randomRIO (0, length xs - 1) --Given possible candidates for nextMove, choose those whose white move matches lastMove. matchLastMove::[Int] -> String -> OpeningBook -> [Int] matchLastMove [] _ _= [] matchLastMove (x:xs) lastMove openingBook= if (getWhiteMove$(getNode x openingBook)) == lastMove then [x]++(matchLastMove xs lastMove openingBook) else (matchLastMove xs lastMove openingBook) --Given a movesString, traverse the tree and get the next node. Used for openings. getNextEvenChild::[(String, String)] -> OpeningBook -> (String, String) getNextEvenChild moves openingBook = getBothMoves$(getNode (selectRandomMove$(matchSequence (-1) moves openingBook)) openingBook) --Given a movesString and white move, traverse the tree and get the next node. Used for defence. getNextOddChild::([(String, String)], String) -> OpeningBook -> (String, String) getNextOddChild (moves, lastMove) openingBook = getBothMoves$(getNode (selectRandomMove$(matchLastMove (matchSequence (-1) moves openingBook) lastMove openingBook)) openingBook) --Given a movesString convert it to a list of (W,B) moves. Used for opening. convertToEvenTuple::[String] -> [(String, String)] convertToEvenTuple [] = [] convertToEvenTuple (x:[]) = [] convertToEvenTuple (x:y:z) = [(x, y)] ++ convertToEvenTuple z --Given a movesString convert it to a tuple of list of (W,B) and the last move. Used for defence. convertToOddTuple::[String] -> ([(String, String)], String) convertToOddTuple [] = ([], "") convertToOddTuple x = (convertToEvenTuple x, last x) --Given a movesString, get the next move to be played. getNextMove::[String] -> OpeningBook -> String getNextMove ["NULL"] _ = "NULL" getNextMove moves openingBook= case (length moves `mod` 2) of 0 -> fst$getNextEvenChild (convertToEvenTuple$moves) openingBook 1 -> snd$getNextOddChild (convertToOddTuple$moves) openingBook --Given history check if the last board is an empty board (only possible if FEN is used). containsEmptyBoard::History -> Bool containsEmptyBoard [] = False containsEmptyBoard hs = if (snd$last$hs) == emptyBoard then True else False --Given a gamestate, generate the movesString. historyParser'::GameState -> [String] historyParser' (_, []) = [] historyParser' (currBoard, x:[]) = [genMovesString x currBoard] historyParser' (b, (x:y:xs)) = [(genMovesString x y)] ++ historyParser' (b, [y]++xs) --If board is FEN, don't use openBook hence return NULL else use historyParser'. historyParser::GameState -> [String] historyParser gs = if containsEmptyBoard$snd$gs then ["NULL"] else (historyParser' gs) --Given a gamestate, return the next gamestate. getStateOpenBook:: GameState -> OpeningBook -> GameState getStateOpenBook gs openingBook = makeMove gs (parseMove $ getNextMove (historyParser gs) openingBook)
adityashah30/haskellchess
chessEngine/OpenBookModule.hs
gpl-2.0
6,149
0
17
891
1,716
950
766
73
2
module Errors ( LispError(..) , ThrowsError , throwError , trapError , extractValue ) where import Control.Monad.Except (throwError, catchError, MonadError) import Text.ParserCombinators.Parsec import Types -- for an example of how to use a custom error data type, see -- See https://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Except.html#g:3 data LispError = NumArgs Integer [LispVal] | TypeMismatch String LispVal | Parser ParseError | BadSpecialForm String LispVal | NotFunction String String | UnboundVar String String | Default String showError :: LispError -> String showError (UnboundVar message varname) = message ++ ": " ++ varname showError (BadSpecialForm message form) = message ++ ": " ++ show form showError (NotFunction message func) = message ++ ": " ++ show func showError (NumArgs expected found) = "Expected " ++ show expected ++ " args; found values " ++ unwordsList found showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected ++ ", found " ++ show found showError (Parser parseErr) = "Parse error at " ++ show parseErr showError (Default err) = "Error: " ++ err instance Show LispError where show = showError {- - --this isn't needed instance Error LispError where noMsg = Default "An error has occured" strMsg = Default -} -- Currying the Either type constructor. -- "Either a b" means Left a, Right b type ThrowsError = Either LispError -- Now "ThrowsError a", a is the value. The error LispError is embedded in ThrowsError extractValue :: ThrowsError a -> a extractValue (Right val) = val -- this is like an error handler. -- action is a result of a monadic computation (e.g. do notation.) -- What handler does is show the value and wrap it the monad -- catchError :: m a -> (e -> m a) -> m a trapError :: (Show e, MonadError e m) => m String -> m String trapError action = catchError action (return . show)
quakehead/haskell-scheme
Errors.hs
gpl-3.0
2,169
0
8
600
404
218
186
31
1
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-} module WildFire.WildFireModelStatic where import System.Random import qualified PureAgentsSeq as PA type WFCell = (Int, Int) data WFState = Living | Burning | Dead deriving (Eq, Show) data WFMsg = Ignite data WFAgentState = WFAgentState { wfState :: WFState, burnable :: Double, rng :: StdGen } deriving (Show) type WFEnvironment = () type WFAgent = PA.Agent WFMsg WFAgentState WFEnvironment type WFTransformer = PA.AgentTransformer WFMsg WFAgentState WFEnvironment type WFSimHandle = PA.SimHandle WFMsg WFAgentState WFEnvironment burnPerTimeUnit :: Double burnPerTimeUnit = 0.2 is :: WFAgent -> WFState -> Bool is a wfs = (wfState s) == wfs where s = PA.state a wfTransformer :: WFTransformer wfTransformer ae (PA.Start) = ae wfTransformer (a, e) (PA.Dt dt) = (wfDt a dt, e) wfTransformer (a, e) (PA.Message (_, m)) = (wfMsg a m, e) wfDt :: WFAgent -> Double -> WFAgent wfDt a dt | is a Living = a | is a Dead = a | is a Burning = handleBurningAgent a dt wfMsg :: WFAgent -> WFMsg -> WFAgent wfMsg a Ignite | is a Living = igniteAgent a | otherwise = a igniteAgent :: WFAgent -> WFAgent igniteAgent a = PA.updateState a (\sOld -> sOld { wfState = Burning } ) handleBurningAgent :: WFAgent -> Double -> WFAgent handleBurningAgent a dt = if burnableLeft <= 0.0 then deadAgent else PA.updateState aAfterRandIgnite (\sOld -> sOld { rng = g' } ) where b = (burnable (PA.state a)) burnableLeft = b - (burnPerTimeUnit * dt) deadAgent = PA.updateState a (\sOld -> sOld { wfState = Dead, burnable = 0.0 } ) burningAgent = PA.updateState a (\sOld -> sOld { burnable = burnableLeft } ) (aAfterRandIgnite, g') = PA.sendMsgToRandomNeighbour burningAgent Ignite (rng (PA.state a)) createRandomWFAgents :: StdGen -> (Int, Int) -> ([WFAgent], StdGen) createRandomWFAgents gInit cells@(x, y) = (as', g') where agentCount = x*y (randStates, g') = createRandomStates gInit agentCount as = map (\idx -> PA.createAgent idx (randStates !! idx) wfTransformer) [0..agentCount-1] as' = map (\a -> PA.addNeighbours a (agentNeighbours a as cells) ) as agentNeighbours :: WFAgent -> [WFAgent] -> (Int, Int) -> [WFAgent] agentNeighbours a as cells = filter (\a' -> any (==(agentToCell a' cells)) neighbourCells ) as where aCell = agentToCell a cells neighbourCells = neighbours aCell agentToCell :: WFAgent -> (Int, Int) -> (Int, Int) agentToCell a (xCells, yCells) = (ax, ay) where aid = PA.agentId a ax = mod aid yCells ay = floor((fromIntegral aid) / (fromIntegral xCells)) neighbourhood :: [(Int, Int)] neighbourhood = [topLeft, top, topRight, left, right, bottomLeft, bottom, bottomRight] where topLeft = (-1, -1) top = (0, -1) topRight = (1, -1) left = (-1, 0) right = (1, 0) bottomLeft = (-1, 1) bottom = (0, 1) bottomRight = (1, 1) neighbours :: (Int, Int) -> [(Int, Int)] neighbours (x,y) = map (\(x', y') -> (x+x', y+y')) neighbourhood createRandomStates :: StdGen -> Int -> ([WFAgentState], StdGen) createRandomStates g 0 = ([], g) createRandomStates g n = (rands, g'') where (randState, g') = randomAgentState g (ras, g'') = createRandomStates g' (n-1) rands = randState : ras randomAgentState :: StdGen -> (WFAgentState, StdGen) randomAgentState g = (WFAgentState{ wfState = Living, burnable = randBurnable, rng = g'' }, g') where (randBurnable, g') = randomR(1.0, 1.0) g (g'', _) = split g'
thalerjonathan/phd
public/ArtIterating/code/haskell/PureAgentsSeq/src/WildFire/WildFireModelStatic.hs
gpl-3.0
3,752
0
12
963
1,401
784
617
84
2
module Tests.Conversion where import QHaskell.MyPrelude import qualified Language.Haskell.TH.Syntax as TH import qualified QHaskell.Expression.ADTUntypedNamed as AUN import qualified QHaskell.Expression.ADTUntypedDebruijn as AUD import qualified QHaskell.Expression.GADTTyped as GTD import qualified QHaskell.Expression.GADTFirstOrder as GFO import qualified QHaskell.Expression.GADTHigherOrder as GHO import qualified QHaskell.Expression.ADTValue as FAV import qualified QHaskell.Expression.GADTValue as FGV import qualified Tests.TemplateHaskell as TH import qualified Tests.ADTUntypedNamed as AUN import qualified Tests.ADTUntypedDebruijn as AUD import qualified Tests.GADTTyped as GTD import qualified Tests.GADTFirstOrder as GFO import qualified Tests.GADTHigherOrder as GHO import qualified QHaskell.Type.ADT as TA import qualified QHaskell.Type.GADT as TG import qualified QHaskell.Environment.Map as EM import qualified QHaskell.Environment.Plain as EP import qualified QHaskell.Environment.Scoped as ES import qualified QHaskell.Environment.Typed as ET import QHaskell.Conversion import QHaskell.Variable.Conversion () import QHaskell.Environment.Conversion () import QHaskell.Type.Conversion () import QHaskell.Expression.Conversion () import qualified QHaskell.Nat.ADT as NA import QHaskell.Expression.Utils.TemplateHaskell type One = NA.Suc NA.Zro type Add = Word32 -> Word32 -> Word32 type EnvAdd = '[Add] typAddG :: TG.Typ Add typAddG = (TG.Arr TG.Wrd (TG.Arr TG.Wrd TG.Wrd)) envAddTypG :: ET.Env TG.Typ EnvAdd envAddTypG = ET.Ext typAddG ET.Emp vec :: ES.Env One TH.Name vec = ES.Ext (stripNameSpace 'TH.add) ES.Emp envAddValG :: ET.Env FGV.Exp EnvAdd envAddValG = ET.Ext (FGV.Exp (+) :: FGV.Exp (Word32 -> Word32 -> Word32)) ET.Emp envAddValV :: ES.Env One FAV.Exp envAddValV = ES.Ext (FAV.lft ((+) :: Word32 -> Word32 -> Word32)) ES.Emp envAddValA :: EP.Env FAV.Exp envAddValA = (FAV.lft ((+) :: Word32 -> Word32 -> Word32)) : [] envAddValM :: EM.Env TH.Name FAV.Exp envAddValM = (stripNameSpace 'TH.add , FAV.lft ((+) :: Word32 -> Word32 -> Word32)) : [] cnvGHO :: Cnv (e , ET.Env TG.Typ EnvAdd , ES.Env (NA.Suc NA.Zro) TH.Name) (GHO.Exp EnvAdd Word32) => e -> Word32 -> Bool cnvGHO e j = case runNamM (do e' :: GHO.Exp EnvAdd Word32 <- cnv (e , envAddTypG,vec) curry cnv e' envAddValG) of Rgt (FGV.Exp i) -> i == j _ -> False cnvGFO :: Cnv (e , ET.Env TG.Typ EnvAdd , ES.Env (NA.Suc NA.Zro) TH.Name) (GFO.Exp EnvAdd '[] Word32) => e -> Word32 -> Bool cnvGFO e j = case runNamM (do e' :: GFO.Exp EnvAdd '[] Word32 <- cnv (e , envAddTypG ,vec) cnv (e' , (envAddValG ,ET.Emp :: ET.Env FGV.Exp '[]))) of Rgt (FGV.Exp i) -> i == j _ -> False cnvGTD :: Cnv (e , ET.Env TG.Typ EnvAdd , ES.Env One TH.Name) (GTD.Exp One NA.Zro TA.Typ) => e -> Word32 -> Bool cnvGTD e j = case runNamM (do e' :: GTD.Exp One NA.Zro TA.Typ <- cnv (e , envAddTypG , vec) cnv (e' , (envAddValV,ES.Emp :: ES.Env NA.Zro FAV.Exp))) of Rgt (FAV.colft -> Rgt i) -> i == j _ -> False cnvAUD :: Cnv (e , ET.Env TG.Typ EnvAdd , ES.Env (NA.Suc NA.Zro) TH.Name) AUD.Exp => e -> Word32 -> Bool cnvAUD e j = case runNamM (do e' :: AUD.Exp <- cnv (e , envAddTypG , vec) cnv (e' , (envAddValA , [] :: EP.Env FAV.Exp))) of Rgt (FAV.colft -> Rgt i) -> i == j _ -> False cnvAUN :: Cnv (e , ET.Env TG.Typ EnvAdd , ES.Env (NA.Suc NA.Zro) TH.Name) (AUN.Exp TH.Name) => e -> Word32 -> Bool cnvAUN e j = case runNamM (do e' :: AUN.Exp TH.Name <- cnv (e , envAddTypG , vec) cnv (e' , (envAddValM,[] :: EM.Env TH.Name FAV.Exp))) of Rgt (FAV.colft -> Rgt i) -> i == j _ -> False test :: Bool test = cnvAUN TH.four 4 && cnvAUN AUN.four 4 && cnvAUD TH.four 4 && cnvAUD AUN.four 4 && cnvAUD AUD.four 4 && cnvGTD TH.four 4 && cnvGTD AUN.four 4 && cnvGTD AUD.four 4 && cnvGTD GTD.four 4 && cnvGFO TH.four 4 && cnvGFO AUN.four 4 && cnvGFO AUD.four 4 && cnvGFO GTD.four 4 && cnvGFO GFO.four 4 && cnvGFO GHO.four 4 && cnvGHO TH.four 4 && cnvGHO AUN.four 4 && cnvGHO AUD.four 4 && cnvGHO GTD.four 4 && cnvGHO GFO.four 4 && cnvGHO GHO.four 4
shayan-najd/QHaskell
Tests/Conversion.hs
gpl-3.0
4,817
0
26
1,453
1,727
930
797
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Main where import Affection as A import qualified SDL import Linear as L import NanoVG hiding (V2(..), V4(..)) import Control.Concurrent.MVar import Control.Monad (when, void) import Data.String (fromString) -- internal imports import Types import StateMachine () import Init instance Affectionate UserData where loadState = load preLoop = (\ud -> pre ud >> smLoad Menu ud) handleEvents = handle update = Main.update draw = Main.draw cleanUp = \_ -> return () hasNextStep = liftIO . readMVar . doNextStep main :: IO () main = do logIO A.Debug "Starting" withAffection (AffectionConfig { initComponents = All , windowTitle = "Haskelloids" , windowConfigs = [ ( 0 , SDL.defaultWindow { SDL.windowGraphicsContext = SDL.OpenGLContext SDL.defaultOpenGL { SDL.glProfile = SDL.Core SDL.Normal 3 2 , SDL.glColorPrecision = V4 8 8 8 1 } , SDL.windowResizable = True } , SDL.Windowed )] } :: AffectionConfig UserData) pre :: UserData -> Affection () pre ud = do let subs = subsystems ud liftIO $ logIO A.Debug "Setting global resize event listener" _ <- partSubscribe (subWindow subs) (fitViewport (800/600)) _ <- partSubscribe (subKeyboard subs) $ \kbdev -> when (msgKbdKeyMotion kbdev == SDL.Pressed) $ case SDL.keysymKeycode (msgKbdKeysym kbdev) of SDL.KeycodeF -> do dt <- getDelta liftIO $ logIO A.Debug $ "FPS: " <> (fromString $ show (1/dt)) SDL.KeycodeO -> toggleScreen 0 _ -> return () return () update :: UserData -> Double -> Affection () update ud sec = do curstate <- liftIO $ readMVar (state ud) smUpdate curstate ud sec handle :: UserData -> [SDL.EventPayload] -> Affection () handle ud e = do let (Subsystems w k) = subsystems ud void $ consumeSDLEvents w =<< consumeSDLEvents k e draw :: UserData -> Affection () draw ud = do liftIO $ beginFrame (nano ud) 800 600 1 curstate <- liftIO $ readMVar (state ud) smDraw curstate ud drawVignette (nano ud) liftIO $ endFrame (nano ud) drawVignette :: Context -> Affection () drawVignette ctx = liftIO $ do save ctx beginPath ctx grad <- boxGradient ctx 200 150 400 300 0 500 (rgba 0 0 0 0) (rgba 0 0 0 255) rect ctx 0 0 800 600 fillPaint ctx grad fill ctx restore ctx
nek0/haskelloids
src/Main.hs
gpl-3.0
2,437
0
21
635
878
441
437
74
3
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module ArgsParser (parseArgs) where import BasicPrelude (error) import Common hiding (error) import Options.Applicative parseArgs :: IO ProgArgs parseArgs = execParser $ info (helper <*> argsParser) idm argsParser :: Parser ProgArgs argsParser = args <$> settingsFileParser <*> (domainCmdParser <|> ((,) DomainMain <$> mainDomainParser)) args :: Text -> (Domain,Command) -> ProgArgs args path (domain,domainCommand) = ProgArgs path domain domainCommand settingsFileParser :: Parser Text settingsFileParser = fromString <$> strOption (value defaultSettingsPath <> long "settings" <> short 's' <> metavar "FILE" <> help ("Use settings FILE instead of default one at " ++ defaultSettingsPath)) domainCmdParser :: Parser (Domain,Command) domainCmdParser = hsubparser $ metavar "DOMAIN" <> value (DomainMain,CommandList ListDefault) <> cmd "main" ((,) DomainMain <$> mainDomainParser) "Main domain - default domain." <> cmd "trash" ((,) DomainTrash <$> trashDomainParser) "Trash domain." <> cmd "archive" ((,) DomainArchive <$> archiveDomainParser) "Archive domain." domainParser :: Parser Domain domainParser = hsubparser $ metavar "DOMAIN" <> value DomainMain <> cmd "main" (pure DomainMain) "Main domain - default domain." <> cmd "trash" (pure DomainTrash) "Trash domain." <> cmd "archive" (pure DomainArchive) "Archive domain." commands :: [(String,Mod CommandFields Command)] commands = [cmdPair "version" (pure CommandVersion) "Show version." ,cmdPair "doctor" (pure CommandDoctor) "Validate settings and working directories." ,cmdPair "view" (CommandView <$> targetParser) "View target." ,cmdPair "edit" (CommandEdit <$> targetParser) "Edit note with given id." ,cmdPair "path" (CommandPath <$> targetParser) "Print absolute path of target." ,cmdPair' "list" ["ls"] (CommandList <$> listType <|> pure (CommandList ListDefault)) "Show list of notes. Default command." ,cmdPair' "filter" ["search"] (CommandSearch <$> searchQuery) "Filter the long list." ,cmdPair' "move" ["mv"] (CommandMove <$> noteID <*> domainParser) "Move note with id from current domain to selected one." ,cmdPair' "remove" ["rm"] (CommandRemove <$> noteID) "Remove note with given id." ,cmdPair' "create" ["new","add"] (CommandCreate <$> noteTitle) "Create note with provided title." ,cmdPair' "archive" ["store"] (CommandArchive <$> noteID) "Move note with id to archive." ,cmdPair' "extension" ["ext"] (CommandChangeExtension <$> noteID <*> extension) "Change extension of note with given id." ,cmdPair "clear" (pure CommandClear) "Clear trash." ,cmdPair "restore" (CommandRestore <$> noteID) "Move note from trash to main domain."] generateCmdParser :: [String] -> Parser Command generateCmdParser cs = hsubparser $ metavar "COMMAND" <> value (CommandList ListDefault) <> (concat . map lookupCmd $ cs) mainDomainParser :: Parser Command mainDomainParser = generateCmdParser ["version" ,"doctor" ,"view" ,"edit" ,"path" ,"list" ,"filter" ,"move" ,"remove" ,"create" ,"archive" ,"extension"] trashDomainParser :: Parser Command trashDomainParser = generateCmdParser ["view","path","list","filter","move","remove","clear","restore"] archiveDomainParser :: Parser Command archiveDomainParser = generateCmdParser ["view","edit","path","list","filter","move","remove","restore"] targetParser :: Parser CommandTarget targetParser = hsubparser (metavar "TARGET" <> cmd "note" (TargetNote <$> noteID) "Target note with id (default target)" <> cmd "info" (TargetNoteInfo <$> noteID) "Target info of note with id" <> cmd "assets" (TargetNoteAssets <$> noteID) "Target assets folder of note with id" <> cmd "note directory" (TargetNoteRoot <$> noteID) "Target note directory of note with id" <> cmd "settings" (pure TargetSettings) "Target application settings file") <|> (TargetNote <$> noteID) listType :: Parser ListType listType = argument auto (metavar "LIST_TYPE") searchQuery :: Parser [Text] searchQuery = some $ textArgument (metavar "SEARCH" <> help "Search query.") noteID :: Parser Int noteID = argument auto $ metavar "NOTE_ID" noteTitle :: Parser [Text] noteTitle = many $ textArgument (metavar "NOTE_TITLE" <> help "Title of note. Warning! Parser is greedy!") extension :: Parser Text extension = validateExt <$> textArgument (metavar "EXTENSION" <> help "Extension of the note. You may include dot symbol if you want.") -- helper functions textArgument :: IsString a => Mod ArgumentFields String -> Parser a textArgument m = fromString <$> strArgument m cmd :: String -> Parser a -> String -> Mod CommandFields a cmd s p d = command s (info p (progDesc d)) cmd' :: String -> [String] -> Parser a -> String -> Mod CommandFields a cmd' s as p d = command' s as (info p (progDesc d)) cmdPair :: String -> Parser a -> String -> (String, Mod CommandFields a) cmdPair s p d = (s,cmd s p d) cmdPair' :: String -> [String] -> Parser a -> String -> (String, Mod CommandFields a) cmdPair' s as p d = (s,cmd' s as p d) lookupCmd :: String -> Mod CommandFields Command lookupCmd c = fromMaybe (error . textToString $ "Couldn't find command " ++ fromString c) (lookup c commands)
d12frosted/kitsunebook-v1
src/ArgsParser.hs
gpl-3.0
5,759
0
15
1,337
1,522
791
731
164
1
module Language.Octopus.Parser.Tokens where import qualified Text.Parsec as P import Language.Octopus.Data import Language.Octopus.Data.Shortcut import Language.Octopus.Parser.Import import Language.Octopus.Parser.Whitespace import Language.Octopus.Parser.Policy ------ Atoms ------ atom :: Parser Val atom = P.choice [ numberLit, charLit , textLit, bytesLiteral, rawTextLit, heredoc , symbol , builtin ] symbol :: Parser Val symbol = try $ do n <- name when (n `elem` reservedWords) (unexpected $ "reserved word (" ++ n ++ ")") --FIXME report error position before token, not after return $ mkSy n numberLit :: Parser Val numberLit = Nm <$> anyNumber charLit :: Parser Val charLit = mkInt . ord <$> between2 (char '\'') (literalChar P.<|> oneOf "\'\"") bytesLiteral :: Parser Val bytesLiteral = do string "b\"" P.optional mws content <- P.many1 $ byte <* P.optional mws string "\"" return $ mkBy content where byte = do one <- P.hexDigit two <- P.hexDigit return . fromIntegral $ stringToInteger 16 [one, two] textLit :: Parser Val textLit = do content <- catMaybes <$> between2 (char '\"') (P.many maybeLiteralChar) return $ mkTx content rawTextLit :: Parser Val rawTextLit = do content <- P.between (string "r\"") (char '"') $ P.many (noneOf "\"" P.<|> (const '"' <$> string "\"\"")) return $ mkTx content heredoc :: Parser Val heredoc = do string "#<<" end <- P.many1 P.letter <* newline let endParser = newline *> string (end ++ ">>") <* (newline P.<|> eof) mkTx <$> anyChar `manyThru` endParser builtin :: Parser Val builtin = do table <- getBuiltins P.choice (map mkPrimParser table) where mkPrimParser (name, val) = string ("#<" ++ name ++ ">") >> return val ------ Basic Tokens ------ name :: Parser String name = P.choice [ (:) <$> namehead <*> nametail , (:) <$> char '-' <*> P.option [] ((:) <$> (namehead P.<|> char '-') <*> nametail) ] where namehead = blacklistChar (`elem` reservedFirstChar) nametail = P.many $ blacklistChar (`elem` reservedChar) ------ Separators ------ openParen :: Parser () openParen = char '(' >> whenLayout (indentFromPos >>= pushExplicit) openBracket :: Parser () openBracket = char '[' >> whenLayout (indentFromPos >>= pushExplicit) openBrace :: Parser () openBrace = char '{' >> whenLayout (indentFromPos >>= pushExplicit) closeParen :: Parser () closeParen = char ')' >> whenLayout popExplicit closeBracket :: Parser () closeBracket = char ']' >> whenLayout popExplicit closeBrace :: Parser () closeBrace = char '}' >> whenLayout popExplicit comma :: Parser () comma = do try $ char ',' >> mws whenLayout $ popExplicit >> indentFromPos >>= pushExplicit
Zankoku-Okuno/octopus
Language/Octopus/Parser/Tokens.hs
gpl-3.0
2,884
0
14
685
962
493
469
74
1
-- | This module is responsible for interacting with the backing database. The -- rest of the program communicates with it over a pair of TChans. The first -- TChan is used by the `restore` function, which reads the database and sends -- all the schedule entry over the chan. The reciever must then construct a -- schedule to actually run the jobs. -- `save` holds its chan open, and whenever it recieves a request, it toggles -- the state of the particular subscription in the DB. If the subscription -- already existed, it is removed, and if it didn't it is added. module Persist (save,restore) where import Database.HDBC import Database.HDBC.Sqlite3 import Control.Concurrent.STM.TChan import Control.Monad.STM(atomically) import Control.Monad(liftM) import Data.ByteString.Char8 import Data.List as L import Data.Time(UTCTime(..)) import Data.Time.Clock(secondsToDiffTime) import Data.Time.Calendar.WeekDate(toWeekDate) import SimpleScheduler import Reddit import Debug.Trace -- Return how far into the given period a certain time is -- E.g. Day (3:00 February 7) --> 3 -- Month (February 7) --> 7 currentTime :: Frequency -> UTCTime -> Int currentTime Minute t = floor (utctDayTime t) `mod` 60 currentTime Hour t = (floor (utctDayTime t) `mod` 3600) `div` 60 currentTime Day t = floor (utctDayTime t) `div` 3600 currentTime Week t = (\(_,_,a) -> a) . toWeekDate $ utctDay t -- | `save` holds its chan open, and whenever it recieves a request, it toggles -- the state of the particular subscription in the DB. If the subscription -- already existed, it is removed, and if it didn't it is added. saveTChan :: (IConnection c) => TChan (ScheduleEntry (ByteString,ByteString,ByteString,Bool)) -> c -> Statement -> Statement -> Statement -> IO () saveTChan chan conn insert check delete = do -- This is a bit hacky. To enable deleting, assume that a request to add an -- entry that already exists is actually a request to delete the entry. -- I still need to remove the entry from the live schedule. ScheduleEntry { key = (freq,addr,sub,mobile)} <- atomically $ readTChan chan let sqlArg = [toSql addr, toSql sub, toSql freq] execute check sqlArg found <- fetchRow check case found of Nothing -> trace "Adding to database" $ execute insert $ sqlArg ++ [toSql mobile] Just _ -> trace "Removing from database" $ execute delete sqlArg commit conn saveTChan chan conn insert check delete -- All these statements are used in the save functionality -- Prepare a statement to insert a new user into the database insertS :: Connection -> IO Statement insertS conn = prepare conn "insert into users (addr, sub, freq, mobile) values (?, ?, ?, ?)" checkS conn = prepare conn "select * from users where addr = ? and sub = ? and freq = ? " deleteS conn = prepare conn "delete from users where addr = ? and sub = ? and freq = ? " -- This is only used to restore the server from disk selectS conn = prepare conn "select * from users" -- Open the database. If it doesn't already exist, make it. openConnection :: FilePath -> IO Connection openConnection path = do conn <- connectSqlite3 path tables <- getTables conn if "users" `L.elem` tables then return conn else do run conn "create table users (addr varchar(256) not null, sub varchar(256) not null, freq varchar(10) not null, mobile bool not null)" [] commit conn return conn -- Connect a TChan to the database save :: TChan (ScheduleEntry (ByteString, ByteString, ByteString,Bool)) -> IO () save chan = do conn <- openConnection "users.db" ins <- insertS conn check <- checkS conn del <- deleteS conn saveTChan chan conn ins check del -- Read from the database, and send every element in it over the TChan to the -- scheduler. restore :: TChan (ScheduleEntry (ByteString, ByteString, ByteString,Bool)) -> IO () restore chan = do conn <- openConnection "users.db" stmt <- selectS conn execute stmt [] rows <- fetchAllRows stmt trace (show rows) $ return () mapM_ ((atomically . writeTChan chan) . ( \ [a,s,f,mobile] -> ScheduleEntry { freq = read $ fromSql f :: Frequency, action = sendDigest (MessageType $ fromSql mobile) (fromSql s) (fromSql a), key = (fromSql f, fromSql a, fromSql s, fromSql mobile)})) rows disconnect conn
joelwilliamson/reddit-digest
Persist.hs
gpl-3.0
4,430
0
17
955
990
516
474
71
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.Projects.EnableXpnHost -- 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) -- -- Enable this project as a shared VPC host project. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.projects.enableXpnHost@. module Network.Google.Resource.Compute.Projects.EnableXpnHost ( -- * REST Resource ProjectsEnableXpnHostResource -- * Creating a Request , projectsEnableXpnHost , ProjectsEnableXpnHost -- * Request Lenses , pexhRequestId , pexhProject ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.projects.enableXpnHost@ method which the -- 'ProjectsEnableXpnHost' request conforms to. type ProjectsEnableXpnHostResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "enableXpnHost" :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> Post '[JSON] Operation -- | Enable this project as a shared VPC host project. -- -- /See:/ 'projectsEnableXpnHost' smart constructor. data ProjectsEnableXpnHost = ProjectsEnableXpnHost' { _pexhRequestId :: !(Maybe Text) , _pexhProject :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsEnableXpnHost' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pexhRequestId' -- -- * 'pexhProject' projectsEnableXpnHost :: Text -- ^ 'pexhProject' -> ProjectsEnableXpnHost projectsEnableXpnHost pPexhProject_ = ProjectsEnableXpnHost' {_pexhRequestId = Nothing, _pexhProject = pPexhProject_} -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). pexhRequestId :: Lens' ProjectsEnableXpnHost (Maybe Text) pexhRequestId = lens _pexhRequestId (\ s a -> s{_pexhRequestId = a}) -- | Project ID for this request. pexhProject :: Lens' ProjectsEnableXpnHost Text pexhProject = lens _pexhProject (\ s a -> s{_pexhProject = a}) instance GoogleRequest ProjectsEnableXpnHost where type Rs ProjectsEnableXpnHost = Operation type Scopes ProjectsEnableXpnHost = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient ProjectsEnableXpnHost'{..} = go _pexhProject _pexhRequestId (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy ProjectsEnableXpnHostResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Projects/EnableXpnHost.hs
mpl-2.0
3,975
0
14
837
398
242
156
63
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.TargetPools.AddInstance -- 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) -- -- Adds an instance to a target pool. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetPools.addInstance@. module Network.Google.Resource.Compute.TargetPools.AddInstance ( -- * REST Resource TargetPoolsAddInstanceResource -- * Creating a Request , targetPoolsAddInstance , TargetPoolsAddInstance -- * Request Lenses , tpaiProject , tpaiTargetPool , tpaiPayload , tpaiRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetPools.addInstance@ method which the -- 'TargetPoolsAddInstance' request conforms to. type TargetPoolsAddInstanceResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "targetPools" :> Capture "targetPool" Text :> "addInstance" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TargetPoolsAddInstanceRequest :> Post '[JSON] Operation -- | Adds an instance to a target pool. -- -- /See:/ 'targetPoolsAddInstance' smart constructor. data TargetPoolsAddInstance = TargetPoolsAddInstance' { _tpaiProject :: !Text , _tpaiTargetPool :: !Text , _tpaiPayload :: !TargetPoolsAddInstanceRequest , _tpaiRegion :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TargetPoolsAddInstance' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tpaiProject' -- -- * 'tpaiTargetPool' -- -- * 'tpaiPayload' -- -- * 'tpaiRegion' targetPoolsAddInstance :: Text -- ^ 'tpaiProject' -> Text -- ^ 'tpaiTargetPool' -> TargetPoolsAddInstanceRequest -- ^ 'tpaiPayload' -> Text -- ^ 'tpaiRegion' -> TargetPoolsAddInstance targetPoolsAddInstance pTpaiProject_ pTpaiTargetPool_ pTpaiPayload_ pTpaiRegion_ = TargetPoolsAddInstance' { _tpaiProject = pTpaiProject_ , _tpaiTargetPool = pTpaiTargetPool_ , _tpaiPayload = pTpaiPayload_ , _tpaiRegion = pTpaiRegion_ } -- | Project ID for this request. tpaiProject :: Lens' TargetPoolsAddInstance Text tpaiProject = lens _tpaiProject (\ s a -> s{_tpaiProject = a}) -- | Name of the TargetPool resource to add instances to. tpaiTargetPool :: Lens' TargetPoolsAddInstance Text tpaiTargetPool = lens _tpaiTargetPool (\ s a -> s{_tpaiTargetPool = a}) -- | Multipart request metadata. tpaiPayload :: Lens' TargetPoolsAddInstance TargetPoolsAddInstanceRequest tpaiPayload = lens _tpaiPayload (\ s a -> s{_tpaiPayload = a}) -- | Name of the region scoping this request. tpaiRegion :: Lens' TargetPoolsAddInstance Text tpaiRegion = lens _tpaiRegion (\ s a -> s{_tpaiRegion = a}) instance GoogleRequest TargetPoolsAddInstance where type Rs TargetPoolsAddInstance = Operation type Scopes TargetPoolsAddInstance = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient TargetPoolsAddInstance'{..} = go _tpaiProject _tpaiRegion _tpaiTargetPool (Just AltJSON) _tpaiPayload computeService where go = buildClient (Proxy :: Proxy TargetPoolsAddInstanceResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetPools/AddInstance.hs
mpl-2.0
4,353
0
18
1,046
547
324
223
89
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Logging.Exclusions.Delete -- 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) -- -- Deletes an exclusion. -- -- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.exclusions.delete@. module Network.Google.Resource.Logging.Exclusions.Delete ( -- * REST Resource ExclusionsDeleteResource -- * Creating a Request , exclusionsDelete , ExclusionsDelete -- * Request Lenses , edXgafv , edUploadProtocol , edAccessToken , edUploadType , edName , edCallback ) where import Network.Google.Logging.Types import Network.Google.Prelude -- | A resource alias for @logging.exclusions.delete@ method which the -- 'ExclusionsDelete' request conforms to. type ExclusionsDeleteResource = "v2" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Empty -- | Deletes an exclusion. -- -- /See:/ 'exclusionsDelete' smart constructor. data ExclusionsDelete = ExclusionsDelete' { _edXgafv :: !(Maybe Xgafv) , _edUploadProtocol :: !(Maybe Text) , _edAccessToken :: !(Maybe Text) , _edUploadType :: !(Maybe Text) , _edName :: !Text , _edCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ExclusionsDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'edXgafv' -- -- * 'edUploadProtocol' -- -- * 'edAccessToken' -- -- * 'edUploadType' -- -- * 'edName' -- -- * 'edCallback' exclusionsDelete :: Text -- ^ 'edName' -> ExclusionsDelete exclusionsDelete pEdName_ = ExclusionsDelete' { _edXgafv = Nothing , _edUploadProtocol = Nothing , _edAccessToken = Nothing , _edUploadType = Nothing , _edName = pEdName_ , _edCallback = Nothing } -- | V1 error format. edXgafv :: Lens' ExclusionsDelete (Maybe Xgafv) edXgafv = lens _edXgafv (\ s a -> s{_edXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). edUploadProtocol :: Lens' ExclusionsDelete (Maybe Text) edUploadProtocol = lens _edUploadProtocol (\ s a -> s{_edUploadProtocol = a}) -- | OAuth access token. edAccessToken :: Lens' ExclusionsDelete (Maybe Text) edAccessToken = lens _edAccessToken (\ s a -> s{_edAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). edUploadType :: Lens' ExclusionsDelete (Maybe Text) edUploadType = lens _edUploadType (\ s a -> s{_edUploadType = a}) -- | Required. The resource name of an existing exclusion to delete: -- \"projects\/[PROJECT_ID]\/exclusions\/[EXCLUSION_ID]\" -- \"organizations\/[ORGANIZATION_ID]\/exclusions\/[EXCLUSION_ID]\" -- \"billingAccounts\/[BILLING_ACCOUNT_ID]\/exclusions\/[EXCLUSION_ID]\" -- \"folders\/[FOLDER_ID]\/exclusions\/[EXCLUSION_ID]\" Example: -- \"projects\/my-project-id\/exclusions\/my-exclusion-id\". edName :: Lens' ExclusionsDelete Text edName = lens _edName (\ s a -> s{_edName = a}) -- | JSONP edCallback :: Lens' ExclusionsDelete (Maybe Text) edCallback = lens _edCallback (\ s a -> s{_edCallback = a}) instance GoogleRequest ExclusionsDelete where type Rs ExclusionsDelete = Empty type Scopes ExclusionsDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/logging.admin"] requestClient ExclusionsDelete'{..} = go _edName _edXgafv _edUploadProtocol _edAccessToken _edUploadType _edCallback (Just AltJSON) loggingService where go = buildClient (Proxy :: Proxy ExclusionsDeleteResource) mempty
brendanhay/gogol
gogol-logging/gen/Network/Google/Resource/Logging/Exclusions/Delete.hs
mpl-2.0
4,692
0
15
1,043
702
412
290
100
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.CloudSearch.Debug.Datasources.Items.SearchByViewURL -- 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) -- -- Fetches the item whose viewUrl exactly matches that of the URL provided -- in the request. **Note:** This API requires an admin account to execute. -- -- /See:/ <https://developers.google.com/cloud-search/docs/guides/ Cloud Search API Reference> for @cloudsearch.debug.datasources.items.searchByViewUrl@. module Network.Google.Resource.CloudSearch.Debug.Datasources.Items.SearchByViewURL ( -- * REST Resource DebugDatasourcesItemsSearchByViewURLResource -- * Creating a Request , debugDatasourcesItemsSearchByViewURL , DebugDatasourcesItemsSearchByViewURL -- * Request Lenses , ddisbvuXgafv , ddisbvuUploadProtocol , ddisbvuAccessToken , ddisbvuUploadType , ddisbvuPayload , ddisbvuName , ddisbvuCallback ) where import Network.Google.CloudSearch.Types import Network.Google.Prelude -- | A resource alias for @cloudsearch.debug.datasources.items.searchByViewUrl@ method which the -- 'DebugDatasourcesItemsSearchByViewURL' request conforms to. type DebugDatasourcesItemsSearchByViewURLResource = "v1" :> "debug" :> Capture "name" Text :> "items:searchByViewUrl" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SearchItemsByViewURLRequest :> Post '[JSON] SearchItemsByViewURLResponse -- | Fetches the item whose viewUrl exactly matches that of the URL provided -- in the request. **Note:** This API requires an admin account to execute. -- -- /See:/ 'debugDatasourcesItemsSearchByViewURL' smart constructor. data DebugDatasourcesItemsSearchByViewURL = DebugDatasourcesItemsSearchByViewURL' { _ddisbvuXgafv :: !(Maybe Xgafv) , _ddisbvuUploadProtocol :: !(Maybe Text) , _ddisbvuAccessToken :: !(Maybe Text) , _ddisbvuUploadType :: !(Maybe Text) , _ddisbvuPayload :: !SearchItemsByViewURLRequest , _ddisbvuName :: !Text , _ddisbvuCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DebugDatasourcesItemsSearchByViewURL' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ddisbvuXgafv' -- -- * 'ddisbvuUploadProtocol' -- -- * 'ddisbvuAccessToken' -- -- * 'ddisbvuUploadType' -- -- * 'ddisbvuPayload' -- -- * 'ddisbvuName' -- -- * 'ddisbvuCallback' debugDatasourcesItemsSearchByViewURL :: SearchItemsByViewURLRequest -- ^ 'ddisbvuPayload' -> Text -- ^ 'ddisbvuName' -> DebugDatasourcesItemsSearchByViewURL debugDatasourcesItemsSearchByViewURL pDdisbvuPayload_ pDdisbvuName_ = DebugDatasourcesItemsSearchByViewURL' { _ddisbvuXgafv = Nothing , _ddisbvuUploadProtocol = Nothing , _ddisbvuAccessToken = Nothing , _ddisbvuUploadType = Nothing , _ddisbvuPayload = pDdisbvuPayload_ , _ddisbvuName = pDdisbvuName_ , _ddisbvuCallback = Nothing } -- | V1 error format. ddisbvuXgafv :: Lens' DebugDatasourcesItemsSearchByViewURL (Maybe Xgafv) ddisbvuXgafv = lens _ddisbvuXgafv (\ s a -> s{_ddisbvuXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ddisbvuUploadProtocol :: Lens' DebugDatasourcesItemsSearchByViewURL (Maybe Text) ddisbvuUploadProtocol = lens _ddisbvuUploadProtocol (\ s a -> s{_ddisbvuUploadProtocol = a}) -- | OAuth access token. ddisbvuAccessToken :: Lens' DebugDatasourcesItemsSearchByViewURL (Maybe Text) ddisbvuAccessToken = lens _ddisbvuAccessToken (\ s a -> s{_ddisbvuAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ddisbvuUploadType :: Lens' DebugDatasourcesItemsSearchByViewURL (Maybe Text) ddisbvuUploadType = lens _ddisbvuUploadType (\ s a -> s{_ddisbvuUploadType = a}) -- | Multipart request metadata. ddisbvuPayload :: Lens' DebugDatasourcesItemsSearchByViewURL SearchItemsByViewURLRequest ddisbvuPayload = lens _ddisbvuPayload (\ s a -> s{_ddisbvuPayload = a}) -- | Source name, format: datasources\/{source_id} ddisbvuName :: Lens' DebugDatasourcesItemsSearchByViewURL Text ddisbvuName = lens _ddisbvuName (\ s a -> s{_ddisbvuName = a}) -- | JSONP ddisbvuCallback :: Lens' DebugDatasourcesItemsSearchByViewURL (Maybe Text) ddisbvuCallback = lens _ddisbvuCallback (\ s a -> s{_ddisbvuCallback = a}) instance GoogleRequest DebugDatasourcesItemsSearchByViewURL where type Rs DebugDatasourcesItemsSearchByViewURL = SearchItemsByViewURLResponse type Scopes DebugDatasourcesItemsSearchByViewURL = '["https://www.googleapis.com/auth/cloud_search", "https://www.googleapis.com/auth/cloud_search.debug"] requestClient DebugDatasourcesItemsSearchByViewURL'{..} = go _ddisbvuName _ddisbvuXgafv _ddisbvuUploadProtocol _ddisbvuAccessToken _ddisbvuUploadType _ddisbvuCallback (Just AltJSON) _ddisbvuPayload cloudSearchService where go = buildClient (Proxy :: Proxy DebugDatasourcesItemsSearchByViewURLResource) mempty
brendanhay/gogol
gogol-cloudsearch/gen/Network/Google/Resource/CloudSearch/Debug/Datasources/Items/SearchByViewURL.hs
mpl-2.0
6,268
0
18
1,353
789
461
328
124
1
{-# LANGUAGE ScopedTypeVariables #-} {- The picture DSL. This section introduces the domain-specific language for constructing visualizations. It is divided into three sections: colour schemes, data derivation, and then picture construction. -} module PictureDSL where import Data.List (genericLength) import qualified Graphics.Rendering.OpenGL.GL as GL import Algorithms import AstroData import CellTypes import Colour import Dataset import Graphics import Maths import RectGrid import Render fromFull :: Time -> Species -> VisData fromFull t s = astroFull t s from4 :: Time -> Species -> VisData from4 t s = astroFour t s -- 2. Pictures ------------------------------------------------------ -- -- The Picture type gives the top-level graphics that -- can be generated. These are 2D contour plots, -- 3D isosurface extraction (we allow for > 1 surface -- to be pulled at a time), 3D volume rendering, -- a 2D volumetric slice (smooth-shaded), or a 3D -- scatter plot. For the Contour command, the slice -- plane used is implicit - one of the dataset dimensions -- must resolve to a singleton value, and this is the -- value that is used. -- -- Two kinds of compound picture can be constructed: -- pictures composed within a single frame, or -- pictures composed over time (an animation). -- -- In the case of an animation, the following key -- controls are provided via the user interface: -- s - stop the animation -- g - start the animation running -- < - back one frame -- > - forward one frame data Picture v = Surface Colour (Sampling v) | Slice Colour | Volume Colour | Contour Colour (Sampling v) | Draw [Picture v] | Anim [Picture v] -- View datatype combines a source with a picture description to make a generic -- picture type that is independent of the source data View d v = d :> (Picture v) evalPicture :: (Enum a, Interp a, InvInterp a, Dataset d) => View d a -> IO HsScene evalPicture (source :> (Surface pal level)) = do field <- readData source let values = datastream field (dx,dy,dz) = dimensions $ samplings field mkGrid = cubicGrid (dx, dy, dz) points = mkGrid $ cubicPoints field vcells = mkGrid $ values tVal = toFloat $ head $ samplingToList level colour = transfer pal 1.0 1.0 1.0 1.0 contour = concat $ isosurface tVal vcells points geometry = surfaceGeom contour [colour] return $ Group static [geometry] evalPicture (source :> (Contour pal levels)) = do field <- readData source let (dx,dy) = dimensions2D $ samplings field mkGrid = squareGrid (dx, dy) points = mkGrid $ squarePoints field vcells = mkGrid $ datastream field tVals = fmap toFloat $ samplingToList levels colour = transfer pal 1.0 1.0 (genericLength $ tVals) contours = map (\t -> concat $ isosurface t vcells points) $ tVals geometry = contourGeom contours (map colour [1.0 .. (genericLength $ tVals)]) return $ Group static [geometry] evalPicture (source :> (Slice pal)) = do field <- readData source let values = datastream field (dx,dy,dz) = dimensions $ samplings field points = planePoints $ samplings field colour = transfer pal 1.0 (minimum $ values) (maximum $ values) colours :: [GL.Color4 GL.GLfloat] = map colour values rows = splitInto steps $ zip points colours steps = case slicePlane (samplings field) of X_equals _ -> dy Y_equals _ -> dx Z_equals _ -> dx return $ Group static $ [plane rows] evalPicture (source :> (Volume pal)) = do field <- readData source let values = datastream field (dx,dy,dz) = dimensions $ samplings field points = cubicPoints field colour = transfer pal 0.4 (minimum $ values) (maximum $ values) colours :: [GL.Color4 GL.GLfloat] = map colour values geometry = volumeGeom (dx,dy,dz) points colours return $ Group static [geometry] evalPicture (source :> Draw ps) = do pictures <- sequence $ map (\x -> evalPicture (source :> x) ) ps return $ Group static pictures evalPicture (source :> Anim ps) = do pictures <- sequence $ (map (\x -> evalPicture (source :> x)) ps) return $ Animate animControl True pictures []
kvelicka/Fizz
PictureDSL.hs
lgpl-2.1
4,581
0
15
1,294
1,158
606
552
78
3
module Example where import Induction.Structural -- | A small test envirenment of Ordinals, Naturals, Integers, -- Lists, Trees and Expressions. testEnv :: TyEnv String String testEnv t = case t of "Ord" -> Just [("zero",[]) ,("succ",[Rec "Ord"]) ,("lim",[Exp "Nat -> Ord" ["Nat"]]) ] "Nat" -> Just [("zero",[]) ,("succ",[Rec "Nat"]) ] "Int" -> Just [("pos",[NonRec "Nat"]) ,("neg",[NonRec "Nat"]) ] _ | ("List ",a) <- splitAt 5 t -> Just [("nil",[]) ,("cons",[NonRec a,Rec t]) ] | ("Tree ",a) <- splitAt 5 t -> Just [("leaf",[NonRec a]) ,("fork",[Rec t,Rec t]) ] | ("Tree' ",a) <- splitAt 6 t -> Just [("empty",[]) ,("branch",[Rec t,NonRec a,Rec t]) ] | ("Expr ",v) <- splitAt 5 t -> Just [("var",[NonRec v]) ,("lit",[NonRec "Int"]) ,("add",[Rec t,Rec t]) ,("mul",[Rec t,Rec t]) ,("neg",[Rec t,Rec t]) ] _ -> Nothing -- | Specify the type of every variable, then on which coordinates of -- P to do induction on. This function then takes care of the -- plumbing and prints the results. testStrInd :: [(String,String)] -> [Int] -> IO () testStrInd vars coords = putStrLn $ render $ linObligations strStyle $ unTag (\(x :~ i) -> x ++ show i) $ subtermInduction testEnv vars coords -- Various tests -------------------------------------------------------------- intInd = testStrInd [("X","Int")] intInd2 = testStrInd [("X","Int"),("Y","Int")] intInd3 = testStrInd [("X","Int"),("Y","Int"),("Z","Int")] natInd = testStrInd [("X","Nat")] natInd2 = testStrInd [("X","Nat"),("Y","Nat")] natInd3 = testStrInd [("X","Nat"),("Y","Nat"),("Z","Nat")] listInd = testStrInd [("Xs","List a")] natListInd = testStrInd [("Xs","List Nat")] ordListInd = testStrInd [("Xs","List Ord")] ordInd = testStrInd [("X","Ord")] treeInd = testStrInd [("T","Tree a")] exprInd = testStrInd [("E","Expr a")] tree'Ind = testStrInd [("T","Tree' a")] treeTreeInd = testStrInd [("T","Tree Tree a")]
danr/structural-induction
example/Example.hs
lgpl-3.0
2,351
0
13
750
865
492
373
47
5
{-# LANGUAGE DeriveGeneric #-} {- © Utrecht University (Department of Information and Computing Sciences) -} module Domain.Scenarios.Expression where import Control.Arrow import Data.Binary import qualified Data.Map as M import Data.Maybe import GHC.Generics import Domain.Scenarios.Condition import Domain.Scenarios.Globals import Domain.Scenarios.ScenarioState import qualified Domain.Scenarios.DomainData as DD data Expression = Literal DD.Value | ParameterReference ID (Maybe ID) Calculation | Sum [Expression] | Scale Integer Integer Expression | Choose [(Condition, Expression)] Expression deriving (Show, Read, Eq, Generic) instance Binary Expression data Calculation = CalculateValue | CalculatePercentage deriving (Show, Read, Eq, Generic) instance Binary Calculation evaluateExpression :: TypeMap -> ParameterState -> Expression -> DD.Value evaluateExpression typeMap state expr = case expr of Literal val -> val ParameterReference idref characterIdref calc -> case calc of CalculateValue -> value CalculatePercentage -> DD.VInteger $ round (fromInteger (100 * (fromDDInteger value - imin)) / fromInteger (imax - imin) :: Double) where DD.TSimple (DD.TInteger (Just imin) (Just imax)) = M.findWithDefault unknownParameter idref typeMap unknownParameter = error ("Reference to unknown parameter " ++ idref) where value = getParameterValue state idref characterIdref Sum exprs -> DD.VInteger (sum (map (fromDDInteger . evaluateExpression typeMap state) exprs)) Scale scalar divisor subExpr -> DD.VInteger $ round (fromInteger (fromDDInteger (evaluateExpression typeMap state subExpr) * scalar) / fromInteger divisor :: Double) Choose cases defaultExpr -> evaluateExpression typeMap state $ fromMaybe defaultExpr (lookup True (map (first (evaluateCondition typeMap state)) cases))
UURAGE/ScenarioReasoner
src/Domain/Scenarios/Expression.hs
apache-2.0
1,965
0
20
395
533
280
253
36
6
module Main ( main ) where import IFind.Config import IFind.Opts import IFind.UI import System.Console.CmdArgs import qualified Data.Text as T import qualified Data.Text.IO as TIO iFindOpts :: IFindOpts iFindOpts = IFindOpts { inDir = "." &= help "directory to search recursively" , outFile = Nothing &= help "output file name" , searchRe = "" &= help "initial value of search regex" , noDefaultFilters = False &= help "ignore default directory/path filters found in the config" , caseInsensitive = False &= help "turns on case-insensitive search" } &= program "ifind" &= help ("Interactive 'find' utility, search file names with regexes. " ++ " Search text takes multiple regexes, separated by ! which has" ++ " an effect similar to \".. |grep -v ..\"." ++ " Ctrl-u toggles case (in)sensitive search." ++ " $HOME/.ifind contains default config (default exclusion rules).") main :: IO () main = do opts <- cmdArgs iFindOpts conf <- readConfFile opts fps <- runUI opts conf case outFile opts of Just fname -> TIO.writeFile fname $ T.unlines fps Nothing -> TIO.putStr $ T.unlines fps -- not terribly useful but for debugging
andreyk0/ifind
Main.hs
apache-2.0
1,347
0
12
406
255
134
121
30
2
module Database.VCache.Open ( openVCache ) where import Control.Monad import Control.Exception import System.FileLock (FileLock) import qualified System.FileLock as FileLock import qualified System.EasyFile as EasyFile import qualified System.IO.Error as IOE import Foreign.Storable import Foreign.Marshal.Alloc import Foreign.Ptr import Data.Bits import Data.IORef import Data.Maybe import qualified Data.Map.Strict as Map import qualified Data.ByteString as BS import qualified Data.List as L import Control.Concurrent.MVar import Control.Concurrent.STM.TVar import Control.Concurrent import qualified System.IO as Sys import qualified System.Exit as Sys import Database.LMDB.Raw import Database.VCache.Types import Database.VCache.RWLock import Database.VCache.Aligned import Database.VCache.Write import Database.VCache.Clean -- | Open a VCache with a given database file. -- -- In most cases, a Haskell process should open VCache in the Main -- module then pass it as an argument to the different libraries, -- frameworks, plugins, and other software components that require -- persistent storage. Use vcacheSubdir to progect against namespace -- collisions. -- -- When opening VCache, developers decide the maximum size and the file -- name. For example: -- -- > vc <- openVCache 100 "db" -- -- This would open a VCache whose file-size limit is 100 megabytes, -- with the name "db", plus an additional "db-lock" lockfile. An -- exception will be raised if these files cannot be created, locked, -- or opened. The size limit is passed to LMDB and is separate from -- setVRefsCacheSize. -- -- Once opened, VCache typically remains open until process halt. -- If errors are detected, e.g. due to writing an undefined value -- to a PVar or running out of space, VCache will attempt to halt -- the process. -- openVCache :: Int -> FilePath -> IO VCache openVCache nMB fp = do let (fdir,fn) = EasyFile.splitFileName fp let eBadFile = fp ++ " not recognized as a file name" when (L.null fn) (fail $ "openVCache: " ++ eBadFile) EasyFile.createDirectoryIfMissing True fdir let fpLock = fp ++ "-lock" let nBytes = (max 1 nMB) * 1024 * 1024 mbLock <- FileLock.tryLockFile fpLock FileLock.Exclusive case mbLock of Nothing -> ioError $ IOE.mkIOError IOE.alreadyInUseErrorType "openVCache lockfile" Nothing (Just fpLock) Just fl -> openVC' nBytes fl fp `onException` FileLock.unlockFile fl vcFlags :: [MDB_EnvFlag] vcFlags = [MDB_NOSUBDIR -- open file name, not directory name ,MDB_NOLOCK -- leave lock management to VCache ] -- -- I'm providing a non-empty root bytestring. There are a few reasons -- for this. LMDB doesn't support zero-sized keys. And the empty -- bytestring will indicate anonymous PVars in the allocator. And if -- I ever want PVar roots within VCache, I can use a different prefix. -- -- The maximum path, including the PVar name, is 511 bytes. That is -- enough for almost any use case, especially since roots should not -- depend on domain data. Too large a path results in runtime error. vcRootPath :: BS.ByteString vcRootPath = BS.singleton 47 -- Default address for allocation. We start this high to help -- regulate serialization sizes and simplify debugging. vcAllocStart :: Address vcAllocStart = 999999999 -- Default cache size is somewhat arbitrary. I've chosen to set it -- to about ten megabytes (as documented in the Cache module). vcDefaultCacheLimit :: Int vcDefaultCacheLimit = 10 * 1000 * 1000 -- initial cache size vcInitCacheSizeEst :: CacheSizeEst vcInitCacheSizeEst = CacheSizeEst { csze_addr_size = sz -- err likely on high side to start , csze_addr_sqsz = (sz * sz) } where sz = 2048 -- err likely on high side to start -- Checking for a `-threaded` runtime threaded :: Bool threaded = rtsSupportsBoundThreads openVC' :: Int -> FileLock -> FilePath -> IO VCache openVC' nBytes fl fp = do unless threaded (fail "VCache needs -threaded runtime") dbEnv <- mdb_env_create mdb_env_set_mapsize dbEnv nBytes mdb_env_set_maxdbs dbEnv 5 mdb_env_open dbEnv fp vcFlags flip onException (mdb_env_close dbEnv) $ do -- initial transaction to grab database handles and init allocator txnInit <- mdb_txn_begin dbEnv Nothing False dbiMemory <- mdb_dbi_open' txnInit (Just "@") [MDB_CREATE, MDB_INTEGERKEY] dbiRoots <- mdb_dbi_open' txnInit (Just "/") [MDB_CREATE] dbiHashes <- mdb_dbi_open' txnInit (Just "#") [MDB_CREATE, MDB_INTEGERKEY, MDB_DUPSORT, MDB_DUPFIXED, MDB_INTEGERDUP] dbiRefct <- mdb_dbi_open' txnInit (Just "^") [MDB_CREATE, MDB_INTEGERKEY] dbiRefct0 <- mdb_dbi_open' txnInit (Just "%") [MDB_CREATE, MDB_INTEGERKEY] allocEnd <- findLastAddrAllocated txnInit dbiMemory mdb_txn_commit txnInit -- ephemeral resources let allocStart = nextAllocAddress allocEnd memory <- newMVar (initMemory allocStart) tvWrites <- newTVarIO (Writes Map.empty []) mvSignal <- newMVar () cLimit <- newIORef vcDefaultCacheLimit cSize <- newIORef vcInitCacheSizeEst cVRefs <- newMVar Map.empty ctWrites <- newIORef $ WriteCt 0 0 0 gcStart <- newIORef Nothing gcCount <- newIORef 0 rwLock <- newRWLock -- finalizer, in unlikely event of closure _ <- mkWeakMVar mvSignal $ do mdb_env_close dbEnv FileLock.unlockFile fl let vc = VCache { vcache_path = vcRootPath , vcache_space = VSpace { vcache_lockfile = fl , vcache_db_env = dbEnv , vcache_db_memory = dbiMemory , vcache_db_vroots = dbiRoots , vcache_db_caddrs = dbiHashes , vcache_db_refcts = dbiRefct , vcache_db_refct0 = dbiRefct0 , vcache_memory = memory , vcache_signal = mvSignal , vcache_writes = tvWrites , vcache_rwlock = rwLock , vcache_climit = cLimit , vcache_csize = cSize , vcache_cvrefs = cVRefs , vcache_signal_writes = updWriteCt ctWrites , vcache_ct_writes = ctWrites , vcache_alloc_init = allocStart , vcache_gc_start = gcStart , vcache_gc_count = gcCount } } initVCacheThreads (vcache_space vc) return $! vc -- our allocator should be set for the next *even* address. nextAllocAddress :: Address -> Address nextAllocAddress addr | (0 == (addr .&. 1)) = 2 + addr | otherwise = 1 + addr -- Determine the last VCache VRef address allocated, based on the -- actual database contents. If nothing is findLastAddrAllocated :: MDB_txn -> MDB_dbi' -> IO Address findLastAddrAllocated txn dbiMemory = alloca $ \ pKey -> mdb_cursor_open' txn dbiMemory >>= \ crs -> mdb_cursor_get' MDB_LAST crs pKey nullPtr >>= \ bFound -> mdb_cursor_close' crs >> if (not bFound) then return vcAllocStart else peek pKey >>= \ key -> let bBadSize = fromIntegral (sizeOf vcAllocStart) /= mv_size key in if bBadSize then fail "VCache memory table corrupted" else peekAligned (castPtr (mv_data key)) -- initialize memory based on initial allocation position initMemory :: Address -> Memory initMemory addr = m0 where af = AllocFrame Map.empty Map.empty addr ac = Allocator addr af af af gcf = GCFrame Map.empty gc = GC gcf gcf m0 = Memory Map.empty Map.empty gc ac -- Update write counts. updWriteCt :: IORef WriteCt -> Writes -> IO () updWriteCt var w = modifyIORef' var $ \ wct -> let frmCt = 1 + wct_frames wct in let pvCt = wct_pvars wct + Map.size (write_data w) in let synCt = wct_sync wct + L.length (write_sync w) in WriteCt { wct_frames = frmCt, wct_pvars = pvCt, wct_sync = synCt } -- | Create background threads needed by VCache. initVCacheThreads :: VSpace -> IO () initVCacheThreads vc = begin where begin = do task (writeStep vc) task (cleanStep vc) return () task step = void (forkIO (forever step `catch` onE)) onE :: SomeException -> IO () onE e | isBlockedOnMVar e = return () -- full GC of VCache onE e = do putErrLn "VCache background thread has failed." putErrLn (indent " " (show e)) putErrLn "Halting program." Sys.exitFailure isBlockedOnMVar :: (Exception e) => e -> Bool isBlockedOnMVar = isJust . test . toException where test :: SomeException -> Maybe BlockedIndefinitelyOnMVar test = fromException putErrLn :: String -> IO () putErrLn = Sys.hPutStrLn Sys.stderr indent :: String -> String -> String indent ws = (ws ++) . indent' where indent' ('\n':s) = '\n' : ws ++ indent' s indent' (c:s) = c : indent' s indent' [] = []
bitemyapp/haskell-vcache
hsrc_lib/Database/VCache/Open.hs
bsd-2-clause
9,125
0
22
2,351
1,929
1,020
909
165
3
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -- | Announce things happening in scrobbling process module Control.Scrobbler.Announce ( Announce(..) , pprint , announce ) where import Control.Monad.Trans (MonadIO, liftIO) import Control.Wire import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.List (intercalate) import qualified Data.Text as T import Prelude hiding ((.), id) import Control.Scrobbler.Netwire (mkFixM) import Control.Scrobbler.Types -- | Class of things that can be announced, like -- changed player state or scrobble round success class Announce a where message :: a -> String instance Announce Track where message Track { _title, _artist, _album } = T.unpack $ " " <> _title <> " by " <> _artist <> " from " <> _album instance Announce a => Announce (PlayerStateChange a) where message Stopped = "* Player is idle" message (Started p) = "* Started:\n" <> message p instance Announce a => Announce (Stamped a) where message (Stamped { _untimed, _local }) = " at " <> show _local <> "\n" <> message _untimed instance Announce a => Announce (Scrobble a) where message (Scrobble p) = "* Scrobble candidate:\n" <> message p instance Announce a => Announce (Successes a) where message (Successes ps) = intercalate "\n" ("* Successfully scrobbled:" : fmap message ps) instance Announce ByteString where message bs = "* Raw data: " ++ show (B.unpack bs) -- | 'Announce' in 'IO' pprint :: (MonadIO m, Announce a) => a -> m () pprint = liftIO . putStrLn . message -- | 'Announce'ment 'Wire'. Propagates input announce :: (MonadIO m, Announce a) => Wire (Timed NominalDiffTime ()) e m a a announce = mkFixM $ \_dt p -> pprint p >> return (Right p)
supki/scrobblers
src/Control/Scrobbler/Announce.hs
bsd-2-clause
1,828
0
12
394
536
288
248
35
1
{-# LANGUAGE NamedFieldPuns, RecordWildCards, PatternGuards #-} module Shades(shades) where import Graphics.SpriteKit import Actions import Constants import Convenience import GameState import Random import Data.List shades :: ShadesScene shades = spawnNewblock $ (sceneWithSize (Size width height)) { sceneBackgroundColor = backgroundColour , sceneChildren = [blocks, walls, score] , sceneData = initialSceneState , sceneUpdate = Just update , scenePhysicsWorld = physicsWorld { worldGravity = Vector 0 (-5) , worldContactDidBegin = Just contact } , sceneHandleEvent = Just handleEvent } update :: ShadesScene -> TimeInterval -> ShadesScene update scene@Scene{ sceneData = sceneState@SceneState{..} } _dt = case gameState of Running | leftPressed -> blockLeft scene{ sceneData = sceneState{ leftPressed = False } } | rightPressed -> blockRight scene{ sceneData = sceneState{ rightPressed = False } } | Just n <- bumpScore -> updateScore n scene{ sceneData = sceneState{ bumpScore = Nothing } } | otherwise -> scene Landed -> if sceneResting scene then resting scene else scene GameOver -> gameOver scene gameOver :: ShadesScene -> ShadesScene gameOver scene@Scene{ sceneData = sceneState } = scene{ sceneActionDirectives = [runCustomActionOn "Score" gameOverScore] , sceneChildren = gameOverNotice : sceneChildren scene } where gameOverScore node _ = node{labelText = "Final Score " ++ show (sceneScore sceneState)} -- update score display -- updateScore :: Int -> ShadesScene -> ShadesScene updateScore n scene@Scene{ sceneData = sceneState } = let scene' = scene{ sceneData = sceneState{ sceneScore = newScore, bumpScore = Nothing} } in addSceneActionDirective scene' $ runCustomActionOn "Score" setScore where newScore = sceneScore sceneState + n setScore label@Label{} _dt = label{ labelText = show newScore } bumpScoreCnt :: Int -> SceneState -> SceneState bumpScoreCnt cnt scene = case bumpScore scene of Nothing -> scene {bumpScore = Just cnt} Just n -> scene {bumpScore = Just (n + cnt)} resting :: ShadesScene -> ShadesScene resting scene = case removeColouredRow scene of Nothing -> if row < blocksInCol - 1 then spawnNewblock scene else scene { sceneData = (sceneData scene){ gameState = GameOver}} Just blocks -> scene { sceneData = bumpRowScore $ sceneData scene , sceneActionDirectives = [ runCustomActionOn "Blocks" (setNodeChildren blocks)] } where -- return Nothing if no row of same colour can be found -- otherwise, return list of blocks without that row removeColouredRow :: ShadesScene -> Maybe [ShadesNode] removeColouredRow scene | len == blocksInRow = Just $ filter (\b -> (getRow b) /= row) (nodeChildren $ head $ sceneChildren scene) | otherwise = Nothing blocks = sortOn getRow $ nodeChildren $ head $ sceneChildren scene -- relies on stable pos of children (len, _, row) = foldl findRow (0, NoState, 0) blocks findRow (currLen, col, row) block | currLen == blocksInRow = (currLen, col, row) | col == blockCol && row == blockRow = (currLen + 1, col, row) | otherwise = (1, blockCol, blockRow) where blockRow = getRow block blockCol = nodeUserData block bumpRowScore = bumpScoreCnt 100 setNodeChildren :: [ShadesNode] -> ShadesNode -> TimeInterval -> ShadesNode setNodeChildren newKids node _dt = node{nodeChildren = newKids} spawnNewblock :: ShadesScene -> ShadesScene spawnNewblock scene = sceneLanded{ sceneChildren = addB (sceneChildren sceneLanded) , sceneData = sceneState{ gameState = Running }} -- TODO: why doesn't this work??? -- sceneLanded{ sceneActionDirectives = [runCustomActionOn "Blocks" addNewBlock] -- , sceneData = sceneState { gameState = Running}} where addB (node:cs) = case nodeName node of Just "Blocks" -> ((node{nodeChildren = block col : (nodeChildren node)}) : cs ) _ -> error "spawnNewBock -someone changed the order!" addNewBlock node _dt = node{ nodeChildren = block col : nodeChildren node } (sceneLanded@Scene{ sceneData = sceneState }, col) = randomColour scene blockLeft :: ShadesScene -> ShadesScene blockLeft scene = addSceneActionDirective scene $ runCustomActionOn "Blocks" leftAction blockRight :: ShadesScene -> ShadesScene blockRight scene = addSceneActionDirective scene $ runCustomActionOn "Blocks" rightAction -- TODO: missing down arrow to accelerate block downwards handleEvent :: Event -> SceneState -> Maybe SceneState handleEvent KeyEvent{ keyEventType = KeyDown, keyEventKeyCode = code} state | code == leftArrowKey = Just state{ leftPressed = True } | code == rightArrowKey = Just state{ rightPressed = True } handleEvent _ _ = Nothing contact :: SceneState -> PhysicsContact NodeState -> (Maybe SceneState, Maybe ShadesNode, Maybe ShadesNode) contact state@SceneState{..} PhysicsContact{..} | nodeName contactBodyA == Nothing || nodeName contactBodyB == Nothing = (Nothing, Nothing, Nothing) | isGround contactBodyA = (Just (setLanded state), Nothing, Just $ deactivateBlock contactBodyB) | isGround contactBodyB = (Just (setLanded state), Just $ deactivateBlock contactBodyA, Nothing) -- merge two blocks of the same colour | (sameColour contactBodyA contactBodyB) && (sameColumn contactBodyA contactBodyB) = if (above contactBodyA contactBodyB) then (Just (bumpScoreCnt' $ setLanded state), Just $ deactivateBlock $ darkenBlock contactBodyA, Just $ melt contactBodyB) else (Just (bumpScoreCnt' $ setLanded state), Just $ melt contactBodyA, Just $ deactivateBlock $ darkenBlock contactBodyB ) -- deactivate block | isblock contactBodyA = (Just (setLanded state ), Just $ deactivateBlock contactBodyA, Nothing) | isblock contactBodyB = (Just (setLanded state), Nothing, Just $ deactivateBlock contactBodyB) | otherwise = (Nothing, Nothing, Nothing) where setLanded :: SceneState -> SceneState setLanded state = state{ gameState = Landed} -- bump score count by points for block bumpScoreCnt' = bumpScoreCnt 5 melt node = node{nodeActionDirectives = [runAction $ sequenceActions [ customAction (setName Nothing) , customAction (flip $ \_ -> darkenBlock) , (scaleYTo 0){actionDuration = 1} , removeFromParent ] ]} nextCol node = darkerShade $ nodeUserData node darkenBlock node = node { nodeActionDirectives = [runAction (setTexture $ blockTextures !! (fromEnum $ nextCol node))] , nodeUserData = NodeCol $ nextCol node} sameColumn node1 node2 = getCol node1 == getCol node2 sameColour node1 node2 = (nodeUserData node1 == nodeUserData node2) && (nodeUserData node1 /= NodeCol (maxBound :: NodeColour)) above node1 node2 = getRow node1 > getRow node2 -- convenience functions sceneResting :: ShadesScene -> Bool sceneResting scene = not $ or $ map isMoving(nodeChildren $ head $ sceneChildren scene) where isMoving node = case nodePhysicsBody node of Nothing -> False Just PhysicsBody{bodyVelocity = Vector x y} -> abs x + abs y > epsilon getRow :: ShadesNode -> Int getRow node = round $ ((pointY $ nodePosition node) - blockHeight / 2) / blockHeight getCol node = round $ ((pointX $ nodePosition node) - blockWidth / 2) / blockWidth deactivateBlock :: ShadesNode -> ShadesNode deactivateBlock node = node{nodeName = Just "Landed"} setName :: Maybe String -> ShadesNode -> a -> ShadesNode setName mbName node _ = node{nodeName = mbName} -- create a new active block with random number to determine color block :: NodeColour -> ShadesNode block colour = (spriteWithTexture texture) { nodeUserData = NodeCol colour , nodeName = Just "Block" , nodePosition = Point (width * 0.5) height , nodePhysicsBody = Just $ ( bodyWithRectangleOfSize (Size (blockWidth - 4) blockHeight) Nothing) { bodyCategoryBitMask = categoryBitMask [Block] , bodyAllowsRotation = False , bodyIsDynamic = True , bodyCollisionBitMask = categoryBitMask [World, Block] , bodyContactTestBitMask = categoryBitMask [World, Block] , bodyVelocity = Vector 0 2 , bodyFriction = 0 , bodyRestitution = 0.0 , bodyLinearDamping = 1 } } where texture = blockTextures !! (fromEnum colour) blocks :: ShadesNode blocks = (node []) { nodeUserData = NoState , nodeName = Just "Blocks" } walls :: ShadesNode walls = (node [groundPhysics, leftWall, rightWall]){nodeUserData = NoState} groundPhysics :: ShadesNode groundPhysics = (node []) { nodeUserData = NoState , nodePosition = Point 0 0 , nodePhysicsBody = Just $ (bodyWithEdgeFromPointToPoint (Point 0 0) (Point width 0)) { bodyCategoryBitMask = categoryBitMask [World] , bodyLinearDamping = 1 , bodyRestitution = 0 } , nodeName = Just "Ground" } score :: ShadesNode score = (labelNodeWithFontNamed "MarkerFelt-Wide") { nodeName = Just "Score" , nodeUserData = NoState , nodePosition = Point (width / 2) (3 * height / 4) , nodeZPosition = 100 , labelText = "0" } debug :: ShadesNode debug = (labelNodeWithFontNamed "MarkerFelt-Wide") { nodeName = Just "debug" , nodeUserData = NoState , nodePosition = Point (width / 2) (height / 2) , nodeZPosition = 100 , labelText = "-" } gameOverNotice :: ShadesNode gameOverNotice = (labelNodeWithFontNamed "MarkerFelt-Wide") { nodeUserData = NoState , nodePosition = Point (width / 2) (7 * height / 8) , nodeZPosition = 100 , labelText = "Game Over" } leftWall :: ShadesNode leftWall = (node []) { nodeUserData = NoState , nodePosition = Point 0 0 , nodePhysicsBody = Just $ (bodyWithEdgeFromPointToPoint (Point 0 0) (Point 0 height)) { bodyCategoryBitMask = categoryBitMask [World] } } rightWall :: ShadesNode rightWall = (node []) { nodeUserData = NoState , nodePosition = Point 0 0 , nodePhysicsBody = Just $ (bodyWithEdgeFromPointToPoint (Point width 0) (Point width height)) { bodyCategoryBitMask = categoryBitMask [World] } }
gckeller/shades
Shades.hsproj/Shades.hs
bsd-2-clause
12,209
0
17
4,143
3,021
1,619
1,402
214
4
{-| Module : Module.Run Description : Tests that execute Binary.Neko bytecode Copyright : (c) Petr Penzin, 2015 License : BSD2 Module.Runtainer : [email protected] Stability : stable Portability : cross-platform Execute Binary.Neko bytecode to check compatibility -} module Module.Run where import Test.Tasty import Test.Tasty.HUnit as HU import Data.ByteString.Lazy as BS import Data.Binary.Put import System.Directory import System.Process import System.Random import System.IO import System.Exit import Binary.Neko.Module import Binary.Neko.Hashtbl import Binary.Neko.Globals import Binary.Neko.Instructions -- | Module execution tests runBytecodeTests :: FilePath -- ^ Path to neko executable -> TestTree -- ^ Resulting test tree runBytecodeTests nekoExe = testGroup "Binary.Neko execution tests" [ testCase "Hello world" $ verifyHappy nekoExe (N {globals=[GlobalString "Hello world!\n"], fields=fromStringList["print"], code=[AccGlobal 0, Push, AccBuiltin "print", Call 1]}) "Hello world!\n" ] -- | Wrapper for Binary.Neko interpreting a module interp :: FilePath -- ^ Path to neko executable -> Module -- ^ Module to interpret -> String -- ^ Standard input -> IO (ExitCode, String, String) -- ^ Exit code, stdout, stderr interp exe mod input = randomName >>= \(fileName, modName) -> openFile fileName WriteMode >>= \handle -> hPut handle (runPut $ putModule mod) >> hClose handle >> readProcessWithExitCode exe [modName] input >>= \(a,b,c) -> removeFile fileName >> return (a,b,c) -- | Random file name randomName :: IO (String, String) -- ^ Return file name and a module name randomName = (randomIO :: IO Int) >>= \n -> return ("module" ++ show n ++ ".n", "module" ++ show n) -- | Verify that test runs succesfully and prints the expected string to stdout (nothing on stderr) verifyHappy :: FilePath -- ^ Path to Binary.Neko executable -> Module -- ^ Module to interpret -> String -- ^ Expected output -> Assertion -- ^ HUnit assertion verifyHappy exe m expect = predicable @? "verifyHappy: test failure" where predicable = (interp exe m "") >>= \(exit, out, err) -> return (exit == ExitSuccess && out == expect && Prelude.null err)
ppenzin/neko-lib-hs
src/test/Module/Run.hs
bsd-2-clause
2,372
0
15
544
495
281
214
38
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {- - Early parser for TAGs. Third preliminary version :-). -} module NLP.LTAG.Early3 where import Control.Applicative ((<$>)) import Control.Monad (guard, void) import qualified Control.Monad.RWS.Strict as RWS import Control.Monad.Trans.Maybe (MaybeT(..)) import Control.Monad.Trans.Class (lift) import Data.List (intercalate) import qualified Data.Set as S import Data.Maybe (isNothing, isJust, listToMaybe) import qualified Pipes as P import qualified NLP.LTAG.Tree as G -------------------------------------------------- -- CUSTOM SHOW -------------------------------------------------- class Show a => View a where view :: a -> String instance View String where view x = x instance View Int where view = show -------------------------------------------------- -- VIEW + ORD -------------------------------------------------- class (View a, Ord a) => VOrd a where instance (View a, Ord a) => VOrd a where -------------------------------------------------- -- CORE TYPES -------------------------------------------------- -- | Position in the sentence. type Pos = Int ---------------------- -- Initial Trees ---------------------- -- Each initial tree is factorized into a collection of flat CF -- rules. In order to make sure that this collection of rules -- can be only used to recognize this particular tree, each -- non-terminal is paired with an additional identifier. -- -- Within the context of substitution, both the non-terminal and -- the identifier have to agree. In case of adjunction, only the -- non-terminals have to be equal. -- | Additional identifier. type ID = Int -- | Symbol: a (non-terminal, maybe identifier) pair. type Sym n = (n, Maybe ID) -- | Show the symbol. viewSym :: View n => Sym n -> String viewSym (x, Just i) = "(" ++ view x ++ ", " ++ show i ++ ")" viewSym (x, Nothing) = "(" ++ view x ++ ", _)" -- | Label: a symbol, a terminal or a generalized foot node. -- Generalized in the sense that it can represent not only a foot -- note of an auxiliary tree, but also a non-terminal on the path -- from the root to the real foot note of an auxiliary tree. data Lab n t = NonT (Sym n) | Term t | Foot (Sym n) deriving (Show, Eq, Ord) -- | Show the label. viewLab :: (View n, View t) => Lab n t -> String viewLab (NonT s) = "N" ++ viewSym s viewLab (Term t) = "T(" ++ view t ++ ")" viewLab (Foot s) = "F" ++ viewSym s -- | A rule for initial tree. data Rule n t = Rule { -- | The head of the rule headI :: Sym n -- | The body of the rule , body :: [Lab n t] } deriving (Show, Eq, Ord) -------------------------- -- Rule generation monad -------------------------- -- | Identifier generation monad. type RM n t a = RWS.RWS () [Rule n t] Int a -- | Pull the next identifier. nextID :: RM n t ID nextID = RWS.state $ \i -> (i, i + 1) -- | Save the rule in the writer component of the monad. keepRule :: Rule n t -> RM n t () keepRule = RWS.tell . (:[]) -- | Evaluate the RM monad. runRM :: RM n t a -> (a, [Rule n t]) runRM rm = RWS.evalRWS rm () 0 ----------------------------------------- -- Tree Factorization ----------------------------------------- -- | Take an initial tree and factorize it into a list of rules. treeRules :: Bool -- ^ Is it a top level tree? `True' for -- an entire initial tree, `False' otherwise. -> G.Tree n t -- ^ The tree itself -> RM n t (Lab n t) treeRules isTop G.INode{..} = case subTrees of [] -> do let x = (labelI, Nothing) -- keepRule $ Rule x [] return $ NonT x _ -> do x <- if isTop then return (labelI, Nothing) else (labelI,) . Just <$> nextID xs <- mapM (treeRules False) subTrees keepRule $ Rule x xs return $ NonT x treeRules _ G.FNode{..} = return $ Term labelF ----------------------------------------- -- Auxiliary Tree Factorization ----------------------------------------- -- | Convert an auxiliary tree to a lower-level auxiliary -- representation and a list of corresponding rules which -- represent the "substitution" trees on the left and on the -- right of the spine. auxRules :: Bool -> G.AuxTree n t -> RM n t (Lab n t) -- auxRules :: Bool -> G.AuxTree n t -> RM n t (Maybe (Sym n)) auxRules b G.AuxTree{..} = doit b auxTree auxFoot where -- doit _ G.INode{..} [] = return Nothing doit _ G.INode{..} [] = return $ Foot (labelI, Nothing) doit isTop G.INode{..} (k:ks) = do let (ls, bt, rs) = split k subTrees x <- if isTop then return (labelI, Nothing) else (labelI,) . Just <$> nextID ls' <- mapM (treeRules False) ls bt' <- doit False bt ks rs' <- mapM (treeRules False) rs -- keepAux $ Aux x ls' bt' rs' -- return $ Just x keepRule $ Rule x $ ls' ++ (bt' : rs') return $ Foot x doit _ _ _ = error "auxRules: incorrect path" split = doit [] where doit acc 0 (x:xs) = (reverse acc, x, xs) doit acc k (x:xs) = doit (x:acc) (k-1) xs doit acc _ [] = error "auxRules.split: index to high" -------------------------------------------------- -- CHART STATE ... -- -- ... and chart extending operations -------------------------------------------------- -- | Parsing state: processed initial rule elements and the elements -- yet to process. data State n t = State { -- | The head of the rule represented by the state. root :: Sym n -- | The list of processed elements of the rule, stored in an -- inverse order. , left :: [Lab n t] -- | The list of elements yet to process. , right :: [Lab n t] -- | The starting position. , beg :: Pos -- | The ending position (or rather the position of the dot). , end :: Pos -- | Coordinates of the gap (if applies) , gap :: Maybe (Pos, Pos) } deriving (Show, Eq, Ord) -- | Is it a completed (fully-parsed) state? completed :: State n t -> Bool completed = null . right -- | Does it represent a regular rule? regular :: State n t -> Bool regular = isNothing . gap -- | Does it represent a regular rule? auxiliary :: State n t -> Bool auxiliary = isJust . gap -- | Is it top-level? All top-level states (regular or -- auxiliary) have an underspecified ID in the root symbol. topLevel :: State n t -> Bool topLevel = isNothing . snd . root -- | Is it subsidiary (i.e. not top) level? subLevel :: State n t -> Bool subLevel = isJust . snd . root -- | Deconstruct the right part of the state (i.e. labels yet to -- process) within the MaybeT monad. expects :: Monad m => State n t -> MaybeT m (Lab n t, [Lab n t]) expects = maybeT . decoList . right -- | Print the state. printState :: (View n, View t) => State n t -> IO () printState State{..} = do putStr $ viewSym root putStr " -> " putStr $ intercalate " " $ map viewLab (reverse left) ++ ["*"] ++ map viewLab right putStr " <" putStr $ show beg putStr ", " case gap of Nothing -> return () Just (p, q) -> do putStr $ show p putStr ", " putStr $ show q putStr ", " putStr $ show end putStrLn ">" -------------------------------------------------- -- Earley monad -------------------------------------------------- -- | The state of the earley monad. data EarSt n t = EarSt { -- | The set of processed states. They can still interact -- with other states (i.e. undergo composition) but only with -- those taken off the queue. done :: S.Set (State n t) -- | The set of states waiting on the queue to be processed. -- Invariant: the intersection of `done' and `waiting' states -- is empty. , waiting :: S.Set (State n t) } deriving (Show, Eq, Ord) -- | Earley parser monad. Contains the input sentence (reader) -- and the state of the computation `EarSt'. type Earley n t = RWS.RWST [t] () (EarSt n t) IO -- | Read word from the given position of the input. readInput :: Pos -> MaybeT (Earley n t) t readInput i = do -- ask for the input xs <- RWS.ask -- just a safe way to retrieve the i-th element maybeT $ listToMaybe $ drop i xs -- | Retrieve the set of "done" states. getDone :: Earley n t (S.Set (State n t)) getDone = done <$> RWS.get -- | Add the state to the waiting queue. Check first if it is -- not already in the set of processed (`done') states. pushState :: (Ord t, Ord n) => State n t -> Earley n t () pushState p = RWS.state $ \s -> let waiting' = if S.member p (done s) then waiting s else S.insert p (waiting s) in ((), s {waiting = waiting'}) -- | Remove a state from the queue. In future, the queue -- will be probably replaced by a priority queue which will allow -- to order the computations in some smarter way. popState :: (Ord t, Ord n) => Earley n t (Maybe (State n t)) popState = RWS.state $ \st -> case S.minView (waiting st) of Nothing -> (Nothing, st) Just (x, s) -> (Just x, st {waiting = s}) -- | Add the state to the set of processed (`done') states. saveState :: (Ord t, Ord n) => State n t -> Earley n t () saveState p = RWS.state $ \s -> ((), s {done = S.insert p (done s)}) -- | Perform the earley-style computation given the grammar and -- the input sentence. earley :: (VOrd t, VOrd n) => S.Set (Rule n t) -- ^ The grammar (set of rules) -> [t] -- ^ Input sentence -> IO (S.Set (State n t)) earley gram xs = done . fst <$> RWS.execRWST loop xs st0 where -- we put in the initial state all the states with the dot on -- the left of the body of the rule (-> left = []) on all -- positions of the input sentence. st0 = EarSt S.empty $ S.fromList [ State { root = headI , left = [] , right = body , beg = i, end = i , gap = Nothing } | Rule{..} <- S.toList gram , i <- [0 .. length xs - 1] ] -- the computetion is performed as long as the waiting queue -- is non-empty. loop = popState >>= \mp -> case mp of Nothing -> return () Just p -> step p >> loop -- | Step of the algorithm loop. `p' is the state popped up from -- the queue. step :: (VOrd t, VOrd n) => State n t -> Earley n t () step p = do -- lift $ putStr "PP: " >> print p -- try to scan the state tryScan p P.runListT $ do let each = P.Select . P.each -- for each state in the set of the processed states q <- each . S.toList =<< lift getDone lift $ do tryCompose p q tryCompose q p -- processing of the state is done, store it in `done' saveState p -- | Try to perform SCAN on the given state. tryScan :: (VOrd t, VOrd n) => State n t -> Earley n t () tryScan p = void $ runMaybeT $ do -- read the word immediately following the ending position of -- the state c <- readInput $ end p -- check that the state expects a terminal on the right (Term t, right') <- expects p -- make sure that what the rule expects is consistent with -- the input guard $ c == t -- construct the resultant state let p' = p { end = end p + 1 , left = Term t : left p , right = right' } -- print logging information lift . lift $ do putStr "[S] " >> printState p putStr " : " >> printState p' -- push the resulting state into the waiting queue lift $ pushState p' -- | Try compose the two states using one of the possible -- binary composition operations. tryCompose :: (VOrd t, VOrd n) => State n t -> State n t -> Earley n t () tryCompose p q = do trySubst p q tryAdjoinInit p q tryAdjoinCont p q tryAdjoinTerm p q -- | Try to substitute the non-terminal expected by the second -- state/rule with the first state (if corresponding symbols -- match). While the first state has to represent a regular -- (non-auxiliary) rule, the second state not necessarily. trySubst :: (VOrd t, VOrd n) => State n t -> State n t -> Earley n t () trySubst p q = void $ runMaybeT $ do -- make sure that `p' is a fully-parsed regular rule guard $ completed p && regular p -- make sure `q' is not yet completed and expects -- a non-terminal (NonT x, right') <- expects q -- make sure that `p' begins where `q' ends guard $ beg p == end q -- make sure that the root of `p' matches with the next -- non-terminal of `q'; IDs of the symbols have to be -- the same as well guard $ root p == x -- construct the resultant state let q' = q { end = end p , left = NonT x : left q , right = right' } -- print logging information lift . lift $ do putStr "[U] " >> printState p putStr " + " >> printState q putStr " : " >> printState q' -- push the resulting state into the waiting queue lift $ pushState q' -- | `tryAdjoinInit p q': -- * `p' is a completed state (regular or auxiliary) -- * `q' not completed and expects a *real* foot tryAdjoinInit :: (VOrd n, VOrd t) => State n t -> State n t -> Earley n t () tryAdjoinInit p q = void $ runMaybeT $ do -- make sure that `p' is fully-parsed guard $ completed p -- make sure `q' is not yet completed and expects -- a real (with ID == Nothing) foot (Foot (u, Nothing), right') <- expects q -- make sure that `p' begins where `q' ends, so that the foot -- node of `q' cab be eventually completed with `p', which -- represents (a part of) an adjunction operation guard $ beg p == end q -- make sure that the root of `p' matches with the non-terminal -- of the foot of `q'; IDs of the symbols *do not* have to be -- the same guard $ fst (root p) == u -- construct the resultant state let q' = q { gap = Just (beg p, end p) , end = end p , left = Foot (u, Nothing) : left q , right = right' } -- print logging information lift . lift $ do putStr "[A] " >> printState p putStr " + " >> printState q putStr " : " >> printState q' -- push the resulting state into the waiting queue lift $ pushState q' -- | `tryAdjoinCont p q': -- * `p' is a completed, auxiliary state -- * `q' not completed and expects a *dummy* foot tryAdjoinCont :: (VOrd n, VOrd t) => State n t -> State n t -> Earley n t () tryAdjoinCont p q = void $ runMaybeT $ do -- make sure that `p' is a completed, auxiliary rule guard $ completed p && auxiliary p -- make sure `q' is not yet completed and expects -- a dummy foot (Foot x@(_, Just _), right') <- expects q -- make sure that `p' begins where `q' ends, so that the foot -- node of `q' cab be completed with `p' guard $ beg p == end q -- make sure that the root of `p' matches the non-terminal of -- the foot of `q'; IDs of the symbols *must* match as well guard $ root p == x -- construct the resulting state; the span of the gap of the -- inner state `p' is copied to the outer state based on `q' let q' = q { gap = gap p , end = end p , left = Foot x : left q , right = right' } -- logging info lift . lift $ do putStr "[B] " >> printState p putStr " + " >> printState q putStr " : " >> printState q' -- push the resulting state into the waiting queue lift $ pushState q' -- | Adjoin a fully-parsed auxiliary state to a partially parsed -- tree represented by a fully parsed rule/state. tryAdjoinTerm :: (VOrd t, VOrd n) => State n t -> State n t -> Earley n t () tryAdjoinTerm p q = void $ runMaybeT $ do -- make sure that `p' is a completed, top-level state ... guard $ completed p && topLevel p -- ... and that it is an auxiliary state (gapBeg, gapEnd) <- maybeT $ gap p -- make sure that `q' is completed as well and that it is -- either a regular rule or an intermediate auxiliary rule -- ((<=) used as an implication here!) guard $ completed q && auxiliary q <= subLevel q -- finally, check that the spans match guard $ gapBeg == beg q && gapEnd == end q -- and that non-terminals match (not IDs) guard $ fst (root p) == fst (root q) let q' = q { beg = beg p , end = end p } lift . lift $ do putStr "[C] " >> printState p putStr " + " >> printState q putStr " : " >> printState q' lift $ pushState q' -------------------------------------------------- -- UTILS -------------------------------------------------- -- | Deconstruct list. Utility function. decoList :: [a] -> Maybe (a, [a]) decoList [] = Nothing decoList (y:ys) = Just (y, ys) -- | MaybeT transformer. maybeT :: Monad m => Maybe a -> MaybeT m a maybeT = MaybeT . return
kawu/ltag
src/NLP/LTAG/Early3.hs
bsd-2-clause
17,262
0
15
4,861
4,206
2,195
2,011
-1
-1
{-# LANGUAGE OverloadedStrings #-} -- | The @babel@ package is used to write documents in languages -- other than US English. -- -- CTAN page for babel: <http://ctan.org/pkg/babel>. module Text.LaTeX.Packages.Babel ( -- * Babel package babel -- * Babel languages , Language (..) , uselanguage , LangConf (..) , uselanguageconf -- * Babel commands and environments , selectlanguage , otherlanguage , foreignlanguage ) where import Text.LaTeX.Base import Text.LaTeX.Base.Syntax import Text.LaTeX.Base.Class -- import Data.Text (toLower) -- Babel package -- | Babel package. When writing in a single language, the simplest -- way of using it is with 'uselanguage'. -- -- In the preamble, use the following (if your language of choice is Spanish): -- -- > uselanguage Spanish -- -- To see a list of available languages, check the 'Language' type. -- babel :: PackageName babel = "babel" -- Babel languages -- | Languages. data Language = Bulgarian -- ^ Bulgarian. | Brazilian -- ^ Brazilian Portuguese. | Canadien -- ^ Canadian French. | Czech -- ^ Czech. | Dutch -- ^ Dutch. | English -- ^ English. | Finnish -- ^ Finnish. | Francais -- ^ Parisian French. | French -- ^ French. | FrenchB -- ^ French. | German -- ^ Old German. | NGerman -- ^ New German. | Icelandic -- ^ Icelandic. | Italian -- ^ Italian. | Magyar -- ^ Hungarian. | Portuguese -- ^ Portuguese. | Russian -- ^ Russian. | Spanish -- ^ Spanish. | Ukranian -- ^ Ukranian. deriving Show instance Render Language where render = toLower . fromString . show instance Texy Language where texy = texy . render -- | Import the 'babel' package using a given 'Language'. -- -- > uselanguage l = usepackage [texy l] babel -- -- If you are using more than one language, consider to use -- 'uselanguageconf'. uselanguage :: LaTeXC l => Language -> l uselanguage ln = usepackage [texy ln] babel -- | Language configuration. You may use one with 'uselanguageconf'. data LangConf = LangConf { mainLang :: Language , otherLangs :: [Language] } deriving Show -- | Import the 'label' package using a given language -- configuration, featuring a main language and some -- others. For example: -- -- > uselanguageconf $ LangConf English [German] -- -- This will use English as main language, and German -- as secondary. uselanguageconf :: LaTeXC l => LangConf -> l uselanguageconf lc = usepackage xs babel where x = "main=" <> texy (mainLang lc) xs = x : fmap texy (otherLangs lc) -- | Switch to a given 'Language'. selectlanguage :: LaTeXC l => Language -> l selectlanguage ln = fromLaTeX $ TeXComm "selectlanguage" [FixArg $ texy ln] -- | Use a 'Language' locally. otherlanguage :: LaTeXC l => Language -> l -> l otherlanguage ln = liftL $ TeXEnv "otherlanguage" [FixArg $ texy ln] -- | The function 'foreignlanguage' takes two arguments; the second argument is a -- phrase to be typeset according to the rules of the language named in its first -- argument. foreignlanguage :: LaTeXC l => Language -> l -> l foreignlanguage ln = liftL $ \l -> TeXComm "foreignlanguage" [OptArg $ texy ln, FixArg l]
dmcclean/HaTeX
Text/LaTeX/Packages/Babel.hs
bsd-3-clause
3,201
0
10
685
523
318
205
55
1