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 MagicHash #-}
-----------------------------------------------------------------------------
--
-- GHCi Interactive debugging commands
--
-- Pepe Iborra (supported by Google SoC) 2006
--
-- ToDo: lots of violation of layering here. This module should
-- decide whether it is above the GHC API (import GHC and nothing
-- else) or below it.
--
-----------------------------------------------------------------------------
module Debugger (pprintClosureCommand, showTerm, pprTypeAndContents) where
import Linker
import RtClosureInspect
import GhcMonad
import HscTypes
import Id
import Name
import Var hiding ( varName )
import VarSet
import UniqSupply
import Type
import Kind
import GHC
import Outputable
import PprTyThing
import ErrUtils
import MonadUtils
import DynFlags
import Exception
import Control.Monad
import Data.List
import Data.Maybe
import Data.IORef
import GHC.Exts
-------------------------------------
-- | The :print & friends commands
-------------------------------------
pprintClosureCommand :: GhcMonad m => Bool -> Bool -> String -> m ()
pprintClosureCommand bindThings force str = do
tythings <- (catMaybes . concat) `liftM`
mapM (\w -> GHC.parseName w >>=
mapM GHC.lookupName)
(words str)
let ids = [id | AnId id <- tythings]
-- Obtain the terms and the recovered type information
(subst, terms) <- mapAccumLM go emptyTvSubst ids
-- Apply the substitutions obtained after recovering the types
modifySession $ \hsc_env ->
hsc_env{hsc_IC = substInteractiveContext (hsc_IC hsc_env) subst}
-- Finally, print the Terms
unqual <- GHC.getPrintUnqual
docterms <- mapM showTerm terms
dflags <- getDynFlags
liftIO $ (printOutputForUser dflags unqual . vcat)
(zipWith (\id docterm -> ppr id <+> char '=' <+> docterm)
ids
docterms)
where
-- Do the obtainTerm--bindSuspensions-computeSubstitution dance
go :: GhcMonad m => TvSubst -> Id -> m (TvSubst, Term)
go subst id = do
let id' = id `setIdType` substTy subst (idType id)
term_ <- GHC.obtainTermFromId maxBound force id'
term <- tidyTermTyVars term_
term' <- if bindThings &&
False == isUnliftedTypeKind (termType term)
then bindSuspensions term
else return term
-- Before leaving, we compare the type obtained to see if it's more specific
-- Then, we extract a substitution,
-- mapping the old tyvars to the reconstructed types.
let reconstructed_type = termType term
hsc_env <- getSession
case (improveRTTIType hsc_env (idType id) (reconstructed_type)) of
Nothing -> return (subst, term')
Just subst' -> do { traceOptIf Opt_D_dump_rtti
(fsep $ [text "RTTI Improvement for", ppr id,
text "is the substitution:" , ppr subst'])
; return (subst `unionTvSubst` subst', term')}
tidyTermTyVars :: GhcMonad m => Term -> m Term
tidyTermTyVars t =
withSession $ \hsc_env -> do
let env_tvs = tyThingsTyVars $ ic_tythings $ hsc_IC hsc_env
my_tvs = termTyVars t
tvs = env_tvs `minusVarSet` my_tvs
tyvarOccName = nameOccName . tyVarName
tidyEnv = (initTidyOccEnv (map tyvarOccName (varSetElems tvs))
, env_tvs `intersectVarSet` my_tvs)
return$ mapTermType (snd . tidyOpenType tidyEnv) t
-- | Give names, and bind in the interactive environment, to all the suspensions
-- included (inductively) in a term
bindSuspensions :: GhcMonad m => Term -> m Term
bindSuspensions t = do
hsc_env <- getSession
inScope <- GHC.getBindings
let ictxt = hsc_IC hsc_env
prefix = "_t"
alreadyUsedNames = map (occNameString . nameOccName . getName) inScope
availNames = map ((prefix++) . show) [(1::Int)..] \\ alreadyUsedNames
availNames_var <- liftIO $ newIORef availNames
(t', stuff) <- liftIO $ foldTerm (nameSuspensionsAndGetInfos availNames_var) t
let (names, tys, hvals) = unzip3 stuff
let ids = [ mkVanillaGlobal name ty
| (name,ty) <- zip names tys]
new_ic = extendInteractiveContextWithIds ictxt ids
liftIO $ extendLinkEnv (zip names hvals)
modifySession $ \_ -> hsc_env {hsc_IC = new_ic }
return t'
where
-- Processing suspensions. Give names and recopilate info
nameSuspensionsAndGetInfos :: IORef [String] ->
TermFold (IO (Term, [(Name,Type,HValue)]))
nameSuspensionsAndGetInfos freeNames = TermFold
{
fSuspension = doSuspension freeNames
, fTerm = \ty dc v tt -> do
tt' <- sequence tt
let (terms,names) = unzip tt'
return (Term ty dc v terms, concat names)
, fPrim = \ty n ->return (Prim ty n,[])
, fNewtypeWrap =
\ty dc t -> do
(term, names) <- t
return (NewtypeWrap ty dc term, names)
, fRefWrap = \ty t -> do
(term, names) <- t
return (RefWrap ty term, names)
}
doSuspension freeNames ct ty hval _name = do
name <- atomicModifyIORef freeNames (\x->(tail x, head x))
n <- newGrimName name
return (Suspension ct ty hval (Just n), [(n,ty,hval)])
-- A custom Term printer to enable the use of Show instances
showTerm :: GhcMonad m => Term -> m SDoc
showTerm term = do
dflags <- GHC.getSessionDynFlags
if gopt Opt_PrintEvldWithShow dflags
then cPprTerm (liftM2 (++) (\_y->[cPprShowable]) cPprTermBase) term
else cPprTerm cPprTermBase term
where
cPprShowable prec t@Term{ty=ty, val=val} =
if not (isFullyEvaluatedTerm t)
then return Nothing
else do
hsc_env <- getSession
dflags <- GHC.getSessionDynFlags
do
(new_env, bname) <- bindToFreshName hsc_env ty "showme"
setSession new_env
-- XXX: this tries to disable logging of errors
-- does this still do what it is intended to do
-- with the changed error handling and logging?
let noop_log _ _ _ _ _ = return ()
expr = "show " ++ showPpr dflags bname
_ <- GHC.setSessionDynFlags dflags{log_action=noop_log}
txt_ <- withExtendedLinkEnv [(bname, val)]
(GHC.compileExpr expr)
let myprec = 10 -- application precedence. TODO Infix constructors
let txt = unsafeCoerce# txt_ :: [a]
if not (null txt) then
return $ Just $ cparen (prec >= myprec && needsParens txt)
(text txt)
else return Nothing
`gfinally` do
setSession hsc_env
GHC.setSessionDynFlags dflags
cPprShowable prec NewtypeWrap{ty=new_ty,wrapped_term=t} =
cPprShowable prec t{ty=new_ty}
cPprShowable _ _ = return Nothing
needsParens ('"':_) = False -- some simple heuristics to see whether parens
-- are redundant in an arbitrary Show output
needsParens ('(':_) = False
needsParens txt = ' ' `elem` txt
bindToFreshName hsc_env ty userName = do
name <- newGrimName userName
let id = mkVanillaGlobal name ty
new_ic = extendInteractiveContextWithIds (hsc_IC hsc_env) [id]
return (hsc_env {hsc_IC = new_ic }, name)
-- Create new uniques and give them sequentially numbered names
newGrimName :: MonadIO m => String -> m Name
newGrimName userName = do
us <- liftIO $ mkSplitUniqSupply 'b'
let unique = uniqFromSupply us
occname = mkOccName varName userName
name = mkInternalName unique occname noSrcSpan
return name
pprTypeAndContents :: GhcMonad m => Id -> m SDoc
pprTypeAndContents id = do
dflags <- GHC.getSessionDynFlags
let pcontents = gopt Opt_PrintBindContents dflags
pprdId = (PprTyThing.pprTyThing . AnId) id
if pcontents
then do
let depthBound = 100
-- If the value is an exception, make sure we catch it and
-- show the exception, rather than propagating the exception out.
e_term <- gtry $ GHC.obtainTermFromId depthBound False id
docs_term <- case e_term of
Right term -> showTerm term
Left exn -> return (text "*** Exception:" <+>
text (show (exn :: SomeException)))
return $ pprdId <+> equals <+> docs_term
else return pprdId
--------------------------------------------------------------
-- Utils
traceOptIf :: GhcMonad m => DumpFlag -> SDoc -> m ()
traceOptIf flag doc = do
dflags <- GHC.getSessionDynFlags
when (dopt flag dflags) $ liftIO $ printInfoForUser dflags alwaysQualify doc
| forked-upstream-packages-for-ghcjs/ghc | compiler/ghci/Debugger.hs | bsd-3-clause | 9,324 | 14 | 22 | 2,975 | 2,299 | 1,170 | 1,129 | 172 | 8 |
import qualified Parser as Parser
main :: IO ()
main = print (iterate Parser.byteParserBadOnce 5 !! 100000)
| sdiehl/ghc | testsuite/tests/codeGen/should_run/T15038/test/Main.hs | bsd-3-clause | 109 | 0 | 9 | 18 | 39 | 21 | 18 | 3 | 1 |
-- Copyright (c) 2000 Galois Connections, Inc.
-- All rights reserved. This software is distributed as
-- free software under the license in the file "LICENSE",
-- which is included in the distribution.
module CSG(module Construct,
module Geometry,
module Intersections,
module Interval,
module Misc) where
import Construct
import Geometry
import Intersections
import Interval
import Misc
| ezyang/ghc | testsuite/tests/programs/galois_raytrace/CSG.hs | bsd-3-clause | 436 | 0 | 4 | 102 | 45 | 33 | 12 | 10 | 0 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
module T6129 where
data family D a
data instance D a = DInt
data X a where
X1 :: X DInt
| ghc-android/ghc | testsuite/tests/polykinds/T6129.hs | bsd-3-clause | 213 | 0 | 6 | 55 | 38 | 25 | 13 | 9 | 0 |
module SFML.Audio
(
module SFML.Audio.Listener
, module SFML.Audio.Music
, module SFML.Audio.SFSampled
, module SFML.Audio.SFSound
, module SFML.Audio.SFSoundRecorder
, module SFML.Audio.Sound
, module SFML.Audio.SoundBuffer
, module SFML.Audio.SoundBufferRecorder
, module SFML.Audio.SoundRecorder
, module SFML.Audio.SoundStatus
, module SFML.Audio.SoundStream
, module SFML.Audio.Types
)
where
import SFML.Audio.Listener
import SFML.Audio.Music
import SFML.Audio.SFSampled
import SFML.Audio.SFSound
import SFML.Audio.SFSoundRecorder
import SFML.Audio.Sound
import SFML.Audio.SoundBuffer
import SFML.Audio.SoundBufferRecorder
import SFML.Audio.SoundRecorder
import SFML.Audio.SoundStatus
import SFML.Audio.SoundStream
import SFML.Audio.Types
| SFML-haskell/SFML | src/SFML/Audio.hs | mit | 773 | 0 | 5 | 93 | 164 | 113 | 51 | 26 | 0 |
module Reverse where
reverse :: [a] -> [a]
reverse [] = []
reverse (x:xs) = reverse xs ++ [x]
| kaveet/haskell-snippets | modules/lists/Reverse.hs | mit | 95 | 0 | 7 | 20 | 56 | 31 | 25 | 4 | 1 |
{-# htermination (seq :: b -> a -> a) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data WHNF a = WHNF a ;
enforceWHNF :: WHNF b -> a -> a;
enforceWHNF (WHNF x) y = y;
seq :: a -> b -> b;
seq x y = enforceWHNF (WHNF x) y;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/seq_1.hs | mit | 291 | 0 | 8 | 84 | 118 | 66 | 52 | 8 | 1 |
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
module Spotify (Spotify(..), search, empty) where
import qualified Data.Aeson as Json
import Data.Aeson.TH
-- import System.IO
-- import qualified Data.ByteString.Lazy as L
import Data.Char (toLower)
import Data.ByteString.Char8 (pack)
import qualified Network.HTTP.Client as HTTP
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Models as ItsOn
data Spotify = Spotify deriving Show
-- SPOTIFY MODELS
data Response = Artists { items :: [Model] }
| Albums { items :: [Model] }
| Tracks { items :: [Model] }
deriving Show
data Model = Track { name :: String
, album :: Model
, artists :: [Model]
, preview_url :: String
, available_markets :: [String]
, external_urls :: ExternalUrls
}
| Artist { images :: Maybe [Image]
, href :: String
, name :: String
, external_urls :: ExternalUrls
}
| Album { available_markets :: [String]
, album_type :: String
, images :: Maybe [Image]
, href :: String
, external_urls :: ExternalUrls
, name :: String
}
deriving Show
data Image =
Image { height :: Int
, url :: String
, width :: Int
} deriving Show
newtype ExternalUrls =
ExternalUrls { spotify :: String } deriving Show
-- JSON
$(deriveJSON defaultOptions ''Image)
$(deriveJSON defaultOptions ''ExternalUrls)
$(deriveJSON defaultOptions{ constructorTagModifier = map toLower
, sumEncoding = ObjectWithSingleField
} ''Spotify.Response)
$(deriveJSON defaultOptions{ constructorTagModifier = map toLower
, sumEncoding = defaultTaggedObject{ tagFieldName = "type" }
} ''Model)
-- IT'S ON MODELS
emptyFragment :: Fragment
emptyFragment =
Fragment { service = "Spotify"
, ItsOn.items = []
}
toFragment :: CountryCode -> Spotify.Response -> Fragment
toFragment market response =
case response of
Tracks _ ->
emptyFragment { ItsOn.items = map (toTrack market) (Spotify.items response) }
_ -> emptyFragment
toTrack :: CountryCode -> Model -> Item
toTrack market model =
ItsOn.Track { title = name model
, ItsOn.artists = map name (Spotify.artists model)
, ItsOn.album = name $ Spotify.album model
, urls = Urls { full = getFullUrl model market
, preview = Just $ preview_url model
}
}
where getFullUrl model market =
case isAvailable model market of
True -> Just $ spotify (external_urls model)
False -> Nothing
isAvailable model market =
market `elem` available_markets model
instance Service Spotify where
empty Spotify = emptyFragment
search Spotify request =
do httpRequest <- toHTTPRequest request
response <- HTTP.withManager tlsManagerSettings $ HTTP.httpLbs httpRequest
let result = Json.decode $ HTTP.responseBody response :: Maybe Spotify.Response
case result of
Just r -> return $ toFragment (countryCode request) r
Nothing -> return $ emptyFragment
where toHTTPRequest r =
do initReq <- HTTP.parseUrl "https://api.spotify.com/v1/search"
let req = initReq { HTTP.requestHeaders = headers }
return $ HTTP.setQueryString [ (pack "type", Just $ pack (getType r))
, (pack "limit", Just $ pack (show $ numResults r))
, (pack "q", Just $ pack (term r))
] req
headers = [ ("Content-Type", "application/json") ]
getType request =
case type' request of
TTrack -> "track"
TAlbum -> "album"
-- main :: IO ()
-- main =
-- do
-- putStrLn "Parse album test:"
-- withFile "spotify_api_sample_album_response.json" ReadMode
-- (\handle ->
-- do
-- contents <- L.hGetContents handle
-- let m = Json.decode contents :: Maybe Response
-- putStrLn $ show m
-- )
-- putStrLn "Parse tracks test:"
-- withFile "spotify_api_sample_track_response.json" ReadMode
-- (\handle ->
-- do
-- contents <- L.hGetContents handle
-- let m = Json.decode contents :: Maybe Response
-- putStrLn $ show m
-- )
-- putStrLn "Parse artists test:"
-- withFile "spotify_api_sample_artist_response.json" ReadMode
-- (\handle ->
-- do
-- contents <- L.hGetContents handle
-- let m = Json.decode contents :: Maybe Response
-- putStrLn $ show m
-- )
| stefanodacchille/itson | src/backend/Spotify.hs | mit | 5,246 | 1 | 18 | 1,974 | 1,030 | 584 | 446 | 90 | 2 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Either (
maybeToLeft
, maybeToRight
, leftToMaybe
, rightToMaybe
, maybeToEither
) where
import Data.Function (const)
import Data.Monoid (Monoid, mempty)
import Data.Maybe (Maybe(..), maybe)
import Data.Either (Either(..), either)
leftToMaybe :: Either l r -> Maybe l
leftToMaybe = either Just (const Nothing)
rightToMaybe :: Either l r -> Maybe r
rightToMaybe = either (const Nothing) Just
maybeToRight :: l -> Maybe r -> Either l r
maybeToRight l = maybe (Left l) Right
maybeToLeft :: r -> Maybe l -> Either l r
maybeToLeft r = maybe (Right r) Left
maybeToEither :: Monoid b => (a -> b) -> Maybe a -> b
maybeToEither = maybe mempty
| ardfard/protolude | src/Either.hs | mit | 707 | 0 | 8 | 125 | 264 | 141 | 123 | 22 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.RTCStatsReport
(js_stat, stat, js_names, names, js_getTimestamp, getTimestamp,
js_getId, getId, js_getType, getType, js_getLocal, getLocal,
js_getRemote, getRemote, RTCStatsReport, castToRTCStatsReport,
gTypeRTCStatsReport)
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[\"stat\"]($2)" js_stat ::
RTCStatsReport -> JSString -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.stat Mozilla RTCStatsReport.stat documentation>
stat ::
(MonadIO m, ToJSString name, FromJSString result) =>
RTCStatsReport -> name -> m result
stat self name
= liftIO (fromJSString <$> (js_stat (self) (toJSString name)))
foreign import javascript unsafe "$1[\"names\"]()" js_names ::
RTCStatsReport -> IO JSVal
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.names Mozilla RTCStatsReport.names documentation>
names ::
(MonadIO m, FromJSString result) => RTCStatsReport -> m [result]
names self = liftIO ((js_names (self)) >>= fromJSValUnchecked)
foreign import javascript unsafe "$1[\"timestamp\"]"
js_getTimestamp :: RTCStatsReport -> IO (Nullable Date)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.timestamp Mozilla RTCStatsReport.timestamp documentation>
getTimestamp :: (MonadIO m) => RTCStatsReport -> m (Maybe Date)
getTimestamp self
= liftIO (nullableToMaybe <$> (js_getTimestamp (self)))
foreign import javascript unsafe "$1[\"id\"]" js_getId ::
RTCStatsReport -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.id Mozilla RTCStatsReport.id documentation>
getId ::
(MonadIO m, FromJSString result) => RTCStatsReport -> m result
getId self = liftIO (fromJSString <$> (js_getId (self)))
foreign import javascript unsafe "$1[\"type\"]" js_getType ::
RTCStatsReport -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.type Mozilla RTCStatsReport.type documentation>
getType ::
(MonadIO m, FromJSString result) => RTCStatsReport -> m result
getType self = liftIO (fromJSString <$> (js_getType (self)))
foreign import javascript unsafe "$1[\"local\"]" js_getLocal ::
RTCStatsReport -> IO (Nullable RTCStatsReport)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.local Mozilla RTCStatsReport.local documentation>
getLocal ::
(MonadIO m) => RTCStatsReport -> m (Maybe RTCStatsReport)
getLocal self = liftIO (nullableToMaybe <$> (js_getLocal (self)))
foreign import javascript unsafe "$1[\"remote\"]" js_getRemote ::
RTCStatsReport -> IO (Nullable RTCStatsReport)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.remote Mozilla RTCStatsReport.remote documentation>
getRemote ::
(MonadIO m) => RTCStatsReport -> m (Maybe RTCStatsReport)
getRemote self = liftIO (nullableToMaybe <$> (js_getRemote (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/RTCStatsReport.hs | mit | 3,797 | 44 | 11 | 531 | 908 | 520 | 388 | 57 | 1 |
module Cycles.Maxcy where
import Cycles.Aux
import Data.Bits ( Bits((.&.), (.|.), bit) )
import Data.Function
import Data.List ( foldl', sort, sortBy )
import Data.List.Split ( chunksOf )
import Data.String.Utils ( replace )
import Foreign.C.Types ( CULLong )
import Text.Regex ( subRegex, mkRegex )
-- | 'elist' is edge list and vlist is cycle vertex list
convIndivCycle :: (Integral a, Bits a) => [[a]] -> [a] -> [(Bool, a)]
convIndivCycle elist vlist = loop elist tvlist []
where
loop :: Integral a => [[a]] -> [a] -> [(Bool, a)] -> [(Bool, a)]
loop _ [] output = output
loop elist' vlist' output = loop elist' (tail vlist') (if length vlist' < 2
then output
else (head vlist' < vlist'!!1, elemIndex' (sort (take 2 vlist')) elist' 0):output )
tvlist = wrapAround $ trimList vlist
-- | aVarList is a[var][j]
aVarList :: (Integral a, Bits a, Integral b, Bits b) => [[(Bool, a)]] -> a -> [b]
aVarList cyclelists var = map ((bool . elem var) . map snd) cyclelists
-- | bVarList is b[var][j]
bVarList :: (Integral a, Bits a) => [[(Bool, a)]] -> a -> [a]
bVarList cyclelists var = map (gettf . filter (\x -> snd x == var)) cyclelists
where
gettf :: Integral a => [(Bool, a)] -> a
gettf list = if null list
then 0
else bool $ fst $ head list
-- | This combines the 'aVarList' and 'bVarList' lists to give the combined cVarList
-- | Note: (1-x) == ~x for x <- [0,1]
cVarList :: (Integral a, Bits a) => [a] -> [a] -> [a]
cVarList = zipWith ((.|.) `Data.Function.on` (-) 1)
-- | This combines the 'aVarList' and 'bVarList' lists to give the combined dVarList
dVarList :: (Integral a, Bits a) => [a] -> [a] -> [a]
dVarList = zipWith (\a b -> (1-a) .|. b )
-- | 'listToULL' converts a length <= 64 list of 0,1 values into a single 'CULLong'
-- listToULL :: Integral a => [a] -> CULLong
-- listToULL list = if length list > 64
-- then error "You want to use listToULLs for this (You're using listToULL)."
-- else foldl' (.|.) 0 (zipWith (\x y -> if x == 0 then 0 else bit y) (padMod list 0 64) [0..])
listToULL :: [Int] -> CULLong
listToULL list = if length list > 64
then error "You want to use listToULLs for this (You're using listToULL)."
else foldl' (.|.) 0 (zipWith (\x y -> if x == 0 then 0 else bit y) (padMod list 0 64) [0..])
-- | 'listToULLs' converts a list of length > 64 to a list of 'CULLong' values
-- listToULLs :: Integral a => [a] -> [CULLong]
listToULLs :: [Int] -> [CULLong]
listToULLs list = map listToULL (chunksOf 64 (padMod list 0 64))
-- This adds "LLU" to the end of each number in a string, useful for generating C code with long long unsigned integers
-- However, it is SUPER slow, taking over 63% of the total time...regex's are just stupid slow for this kind of application.
-- addULLs :: String -> String
-- addULLs text = subRegex (mkRegex patc) (subRegex (mkRegex patb) text "\\1LLU}") "\\1LLU,"
-- where
-- patc = "([0-9]{3})(,)"
-- patb = "([0-9]{3})(})"
-- | 'listFirstAnd' replaces a!!0 with b!!0 .&. c!!0
listFirstAnd :: [[CULLong]] -> [[CULLong]] -> [[CULLong]] -> [[CULLong]]
listFirstAnd [] _ _ = []
listFirstAnd a [] _ = a
listFirstAnd a _ [] = a
listFirstAnd a b c = zipWith (.&.) (head b) (head c) : tail a
-- | This function maps snd to the second level of a list of lists
sndMap2 :: [[(a,b)]] -> [[b]]
sndMap2 = map (map snd)
-- | This function gives the largest element of a list greater than '0', or zero if all the elements are negative
maxPositive :: (Ord a, Num a) => [a] -> a
maxPositive = foldl (\sofar next ->if sofar >= next then sofar else next) 0
-- | This function gives the tuple in a list that has the greates positive snd element
maxPositiveSnd :: (Num a, Ord b, Num b) => [(a,b)] -> (a,b)
maxPositiveSnd = foldl (\sofar next -> if snd sofar >= snd next then sofar else next) (-1,-1)
-- | This function gives the maxPositive for a list of lists
listsMaxPositive :: (Ord a, Num a) => [[a]] -> a
listsMaxPositive lists = maxPositive $ map maxPositive lists
-- | This function counts the number of occurances of x in lists
tallyElem :: Eq a => [[a]] -> a -> Int
tallyElem lists x = foldl (\count list ->count + bool (x `elem` list)) 0 lists
-- | This function finds some most commonly occuring snd element in a list of lists
aMostOftenElem :: [[(a, Int)]] -> Int
aMostOftenElem listsOfTups = fst maxTally
where
lists = sndMap2 listsOfTups
tallies = map (\elem ->(elem, tallyElem lists elem)) [0..maxElem]
maxTally = maxPositiveSnd tallies
maxElem = listsMaxPositive lists
-- | This function takes a list of lists of tuples and switches all occurances of 'a' with 'b' and all occurances of 'b' with 'a'.
switchInTupLists :: [[(a, Int)]] -> Int -> Int -> [[(a, Int)]]
switchInTupLists lists a b = switchOne interLists1 interElem b
where
maximum = listsMaxPositive $ sndMap2 lists
interElem = maximum + 1
interLists0 = switchOne lists a interElem
interLists1 = switchOne interLists0 b a
switchOne lists0 a0 b0 = map (map (\e ->if snd e == a0 then (fst e, b0) else e)) lists0
-- | This function makes sure that '0' is a most often snd element in a list of lists
frontLoadTupLists :: [[(a, Int)]] -> [[(a, Int)]]
frontLoadTupLists tuplists = switchInTupLists tuplists 0 (aMostOftenElem tuplists)
-- | This function deletes the cycles which will be nulled out by the first edge being zero, i.e. it deletes cycles made impossible by fixing the 0th edge forward.
-- Additionally, this function re-frontloads the lists so that more maxcy orientations "may" be found more quickly, reducing the need to print cycles.
-- (True, _) if edge is forward in cycle, blist[][] = 0 (is how it's shown to be forward)
trimCycleList :: [[(Bool, Int)]] -> [[(Bool, Int)]]
trimCycleList cyclelist = switchInTupLists refrontloaded 0 (aMostOftenElem refrontloaded)
where
frontloaded = frontLoadTupLists cyclelist
trimmed = map (\cy ->if (True, 0) `elem` cy then tail cy else cy) frontloaded -- if a cycle has (forward,0) then remove it
refrontloaded = frontLoadTupLists cyclelist
addLLUs :: [[CULLong]] -> String
addLLUs list = (\s ->"[" ++ s ++ "]") $ init $ concatMap addLLUsSingleDepth list
where
addLLUsSingleDepth u = (\s ->"[" ++ s ++ "],") $ init $ concatMap (\y ->show y ++ "LLU,") u
-- | This function is a version of 'generateMaxCyCodeAtStart' that is cross-compatible with the previous way of generating the C code to find the maximally cyclic orientations of a graph
generateMaxCyCode :: [[Int]] -> [[Int]] -> Int -> Int -> Int -> String -> (String, String)
generateMaxCyCode graph cycles start end splitbits name = (fst starter start, snd starter)
where
starter = generateMaxCyCodeAtStart graph cycles end splitbits name
-- | This function creates a function which may be mapped to a start value (to reduce overhead in splitting up the files) to produce C code. These C code files may be compiled to produce independent programs, able to be run in parallel or even on seperate machines with different architectures.
-- Assuming variables are unlimited width for the purposes of explaining the logic: (1 is true, 0 is false) (i is the variable index, j is the digit index)
--
-- a[i][j] := is the ith edge in the jth cycle?
--
-- b[i][j] := is the ith edge backward in the jth cycle? (forward is [x,y] -> x<y )
--
-- c[i][j] := ~a[i][j] | ~b[i][j]
--
-- d[i][j] := ~a[i][j] | b[i][j]
--
-- A[i][j] := (up to and inc. the ith var/edge) is it still possible that this digraph has the jth cycle?
--
-- A[0][j] := 1 if j < number of cycles
--
-- y[i][j] := is ith edge backward? (so 0 is forward, 1 is backward)
--
-- A[i][j] := A[i-1][j] & (~y[j] | c[i][j]) & (y[j] | d[i][j]
generateMaxCyCodeAtStart :: [[Int]] -> [[Int]] -> Int -> Int -> String -> (Int -> String, String)
generateMaxCyCodeAtStart graph cycles end splitbits filename = (\start ->unlines introlist ++ (starthere start ++ fout start) ++ unlines (map (`formatByDict` dict) codelist), printout)
where
numedges = length graph
maxedges = numedges - 1
twotothesplitbits = 2^splitbits
printout = unlines ["graph:" ++ show graph,
"cycles:" ++ show cycles,
"cyclelists:" ++ show cyclelists,
"alist:" ++ show alist,
"blist:" ++ show blist,
"clist:",
--printULLs clist,
"dlist:",
--printULLs dlist,
"aalist:"] -- ,
--printULLs aalist ]
cyclelistsUntrimmed = map (sortBySnd . convIndivCycle graph) cycles
cyclelists = trimCycleList cyclelistsUntrimmed
alist = map (aVarList cyclelists) [0..(-1 + length graph)]
blist = map (bVarList cyclelists) [0..(-1 + length graph)]
clist = map listToULLs (zipWith cVarList alist blist)
dlist = map listToULLs (zipWith dVarList alist blist)
aalist' = map (listToULLs . map (const 1)) alist
aalist = listFirstAnd aalist' aalist' dlist
dict = [
(":maxpos", maxpos),
(":endhere", endhere),
--(":starthere", starthere),
(":cstr", cstr),
(":carray", carray),
(":darray", darray),
(":xarray", xarray),
(":aarray", aarray),
(":fops_true", fops_true),
(":fops_false", fops_false),
(":printouter", printouter),
(":counter", counter),
(":sprinter", sprinter),
--(":fout", fout),
(":fputs", fputs)]
--":maxpos" static int maxpos = 2;
maxpos = "static uint_fast32_t maxpos = " ++ show maxedges ++ ";"
--":endhere" static unsigned int endhere = 0;
endhere = "static uint_fast32_t endhere = " ++ show end ++ ";" -- log2(maximum_value + 1)
--":starthere" unsigned int starthere = 0;
starthere = (\startplace ->"uint_fast32_t starthere = " ++ show (2 * startplace) ++ ";\n") :: Int -> String --The '2*' is to bitshift past the fixed '0' at position '0'.
--":cstr" char str[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
cstr = "char str[" ++ show (10 + numedges) ++ "] = {" ++ trim (show $ replicate (10 + numedges) 0) ++ "};" --10 is not very magic, just count the chars in the output and leave a few to spare
--":carray" static unsigned long long int C[3][1] = {{18446744073709551614LLU}, {18446744073709551614LLU}, {18446744073709551613LLU}};
carray = "static uint_fast64_t C[" ++ show (length clist) ++ "][" ++ show (length $ head clist) ++ "] = " ++ replace "]" "}" (replace "[" "{" (addLLUs clist)) ++ ";"
--":darray" static unsigned long long int D[3][1] = {{18446744073709551613LLU}, {18446744073709551613LLU}, {18446744073709551614LLU}};
darray = "static uint_fast64_t D[" ++ show (length dlist) ++ "][" ++ show (length $ head dlist) ++ "] = " ++ replace "]" "}" (replace "[" "{" (addLLUs dlist)) ++ ";"
--":xarray" unsigned int X[3] = {0, 0, 0};
xarray = "uint_fast8_t X[" ++ show (length graph) ++ "] = {" ++ trim (show $ replicate (length graph) 0) ++ "};"
--":aarray" unsigned long long int A[3][1] = {{18446744073709551615LLU}, {18446744073709551615LLU}, {18446744073709551615LLU}};
aarray = "uint_fast64_t A[" ++ show (length graph) ++ "][" ++ show (length $ head aalist) ++ "] = " ++ replace "]" "}" (replace "[" "{" (addLLUs aalist)) ++ ";"
--":fops_true" A[i][0] = A[i-1][0] & C[i][0];
fops_true = unlines $ map (\j -> " A[i][" ++ show j ++ "] = A[i-1][" ++ show j ++ "] & C[i][" ++ show j ++ "];") [0..(length $ init $ head aalist)]
--":fops_false" A[i][0] = A[i-1][0] & D[i][0];
fops_false = unlines $ map (\j -> " A[i][" ++ show j ++ "] = A[i-1][" ++ show j ++ "] & D[i][" ++ show j ++ "];") [0..(length $ init $ head aalist)]
--sprintf(str, "[ ,%5d]\n", this);
printouter_sprint = " sprintf(str, \"[" ++ replicate (length graph) ' ' ++ ",%5d]\\n\", this);"
-- str[1] = X[0] ^ 48;
printouter_xors = unlines [" str[" ++ show i ++ "] = X[" ++ show (i-1) ++ "] ^ 48;" | i <- [1..numedges]]
printouter = unlines ["void printout(){", printouter_sprint, printouter_xors, "}"]
--":counter" this += counter(A[maxpos][0]);
counter = " uint_fast64_t * thisbuf = A[maxpos];\n this = counter(thisbuf);"
--unlines $ map (\i -> concat [" this += counter(A[maxpos][", show i, "]);"]) [0..(length $ tail $ head aalist)]
--":sprinter" sprintf(str, "[%d%d%d,%5d]\n", X[0], X[1], X[2], this );
sprinter = " printout();"
--" sprintf(str, \"[" ++ (concat $ replicate' "%d" (length graph)) ++ ",%5d]\\n\", " ++ (concat (map (\x -> concat ["X[",show x,"],"]) [0..(-1 + length graph)])) ++ "this );"
--":fout" fout = fopen("test_0_0_out.txt", "w");
fout = (\startplace ->"#define fopener fopen(\"" ++ filename ++ "_" ++ show startplace ++ "_" ++ show twotothesplitbits ++ "_out.txt\", \"w\")\n") :: Int -> String
--":fputs" fputs("[[0, 1], [1, 2], [0, 2]]\n", fout);
fputs = " fputs(\"" ++ show graph ++ "\\n\", fout);"
introlist = ["#include <stdio.h>",
"#include <stdint.h>",
"FILE * fout;"]
--"static unsigned long long int ONES = 18446744073709551615LLU;",
--unsigned int starthere = 0;
-- ":starthere",
codelist = ["uint_fast64_t y;",
"uint_fast32_t best = 1;",
"uint_fast32_t i;",
"uint_fast32_t this;",
--static int maxpos = 2;
":maxpos",
--static unsigned int endhere = 0;
":endhere",
--char str[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
":cstr",
--"FILE * fout;",
"",
--static unsigned long long int C[3][1] = {{18446744073709551614LLU}, {18446744073709551614LLU}, {18446744073709551613LLU}};
":carray",
"",
--static unsigned long long int D[3][1] = {{18446744073709551613LLU}, {18446744073709551613LLU}, {18446744073709551614LLU}};
":darray",
"",
--unsigned int X[3] = {0, 0, 0};
":xarray",
"",
--unsigned long long int A[3][1] = {{18446744073709551615LLU}, {18446744073709551615LLU}, {18446744073709551615LLU}};
":aarray",
"",
"#if UINTPTR_MAX == 0xffffffffffffffff // 64-bit. Hopefully this means the cpu has 'popcnt'.",
makeAsmCounter (length graph),
"#elif UINTPTR_MAX == 0xffffffff // 32-bit",
"int counter (unsigned long long i)",
"{",
" unsigned int i1 = i, i2 = i >> 32;",
" i1 = i1 - ((i1 >> 1) & 0x55555555);",
" i2 = i2 - ((i2 >> 1) & 0x55555555);",
" i1 = (i1 & 0x33333333) + ((i1 >> 2) & 0x33333333);",
" i2 = (i2 & 0x33333333) + ((i2 >> 2) & 0x33333333);",
" i1 = (i1 + (i1 >> 4)) & 0xF0F0F0F;",
" i2 = (i2 + (i2 >> 4)) & 0xF0F0F0F;",
" return ((i1 + i2) * 0x1010101) >> 24;",
"}",
"",
"#else",
"#error \"this cpu doesn't seem to be 32-bit or 64-bit. I don't know how to deal with this.\"",
"#endif",
-- Commented out below is the previous version of the 'f' function, which computes the next "which cycles remain" (A[i]), with
-- the original code and some intermediate steps on the way to the current version (marked by '//'). Note that a variable ('y')
-- and five operations have been removed. I did consider an inplicit branch, but found that most possible implementations would
-- have added a few more operations than the branch did on its own. Furthermore, a branch is ~3 cycles (?) and I've removed at
-- least that many.
-- void f(int i, int y0){
-- if(y0){
-- // y = ONES;
-- // A[i][0] = A[i-1][0] & (0 | C[i][0]) & (ONES | D[i][0]);
-- // A[i][0] = A[i-1][0] & ( C[i][0]) & (ONES );
-- // A[i][0] = A[i-1][0] & ( C[i][0]) ;
-- A[i][0] = A[i-1][0] & C[i][0];
-- } else {
-- // y = 0;
-- // A[i][0] = A[i-1][0] & (ONES | C[i][0]) & (0 | D[i][0]);
-- // A[i][0] = A[i-1][0] & (ONES ) & ( D[i][0]);
-- // A[i][0] = A[i-1][0] & ( D[i][0]);
-- A[i][0] = A[i-1][0] & D[i][0];
-- }
-- // A[i][0] = A[i-1][0] & (~y | C[i][0]) & (y | D[i][0]);
-- }
"void f(uint_fast8_t i, uint_fast8_t y0){",
" if(y0){",
":fops_true",
" } else {",
":fops_false",
" }",
"}",
"",
":printouter",
"",
"void checkifbest(){",
--" this = 0;",
-- this += counter(A[maxpos][0]);
":counter",
"",
" if(this == best){",
-- sprintf(str, "[%d%d%d,%5d]\n", X[0], X[1], X[2], this );
":sprinter",
" fwrite(str, 1, sizeof(str), fout);",
" }",
"",
" if(this > best){",
-- sprintf(str, "[%d%d%d,%5d]\n", X[0], X[1], X[2], this );,
":sprinter",
" fwrite(str, 1, sizeof(str), fout);",
" best = this;",
" }",
"",
"}",
"",
"int r(){",
" goto startnocarry;",
" ",
" startnocarry:",
" if(i == maxpos){",
" if(X[i]){",
" X[i] = 0;",
" i--;",
" goto startcarry;",
" }else{",
" f(i, 0);",
" checkifbest();",
" X[i] = 1;",
" f(i, 1);",
" checkifbest();",
" X[i] = 0;",
" i--;",
" goto startcarry;",
" }",
" }else{",
" f(i, X[i]);",
" i++;",
" goto startnocarry;",
" }",
" ",
" startcarry:",
" if(X[i] && (i != endhere)){",
" X[i] = 0;",
" i--;",
" goto startcarry;",
" }else{",
" if(i == endhere){",
" goto end;",
" }else{",
" X[i] = 1;",
" f(i, 1);",
" i++;",
" goto startnocarry;",
" }",
" }",
"",
" end:",
" return 0;",
"}",
"int main(){",
-- fout = fopen("test_0_0_out.txt", "w");
"fout = fopener;",
--":fout",
-- fputs("[[0, 1], [1, 2], [0, 2]]\n", fout);
":fputs",
" if(endhere){",
" uint_fast8_t bitpos = 0;",
" uint_fast8_t thisbit;",
" while(starthere){",
" thisbit = starthere & 1;",
" X[bitpos] = thisbit;",
" f(bitpos, thisbit);",
" bitpos++;",
" starthere >>= 1;",
" }",
" i = endhere;",
" r();",
" }else{",
" i = 0;",
" r();",
" }",
" fwrite(\"FINISHED.\", 1, 9, fout);",
" fclose(fout);",
" return 0;",
"}",
""]
-- | This generates the inline assembly for the popcount of four 64-bit unsigned integers
makeAsmCounter4 :: Int -> String
makeAsmCounter4 j = unlines [" __asm__(",
" \"popcnt %4, %4 \\n\\t\"",
" \"add %4, %0 \\n\\t\"",
" \"popcnt %5, %5 \\n\\t\"",
" \"add %5, %1 \\n\\t\"",
" \"popcnt %6, %6 \\n\\t\"",
" \"add %6, %2 \\n\\t\"",
" \"popcnt %7, %7 \\n\\t\"",
" \"add %7, %3 \\n\\t\"",
" : \"+r\" (cnt[" ++ j0 ++ "]), \"+r\" (cnt[" ++ j1 ++ "]), \"+r\" (cnt[" ++ j2 ++ "]), \"+r\" (cnt[" ++ j3 ++ "])",
" : \"r\" (buf[" ++ j0 ++ "]), \"r\" (buf[" ++ j1 ++ "]), \"r\" (buf[" ++ j2 ++ "]), \"r\" (buf[" ++ j3 ++ "]));"]
where
j0 = show (j+0)
j1 = show (j+1)
j2 = show (j+2)
j3 = show (j+3)
-- | This generates the inline assembly for the popcount of two 64-bit unsigned integers
makeAsmCounter2 :: Int -> String
makeAsmCounter2 j = unlines [" __asm__(",
" \"popcnt %2, %2 \\n\\t\"",
" \"add %2, %0 \\n\\t\"",
" \"popcnt %3, %3 \\n\\t\"",
" \"add %3, %1 \\n\\t\"",
" : \"+r\" (cnt[" ++ j0 ++ "]), \"+r\" (cnt[" ++ j1 ++ "])",
" : \"r\" (buf[" ++ j0 ++ "]), \"r\" (buf[" ++ j1 ++ "]));"]
where
j0 = show (j+0)
j1 = show (j+1)
-- | This generates the inline assembly for the popcount of one 64-bit unsigned integer
makeAsmCounter1 :: Int -> String
makeAsmCounter1 j = unlines [" __asm__(",
" \"popcnt %1, %1 \\n\\t\"",
" \"add %1, %0 \\n\\t\"",
" : \"+r\" (cnt[" ++ j0 ++ "])",
" : \"r\" (buf[" ++ j0 ++ "]));"]
where
j0 = show (j+0)
-- | This generates the inline assembly for the popcount of arbitrarily many 64-bit unsigned integers
makeAsmCounterN :: Int -> String
makeAsmCounterN n = expand ([], 0, n)
where
expand (code, at, max)
| (max - at) >= 4 = expand (code ++ makeAsmCounter4 at, at + 4, max)
| (max - at) >= 2 = expand (code ++ makeAsmCounter2 at, at + 2, max)
| (max - at) >= 1 = expand (code ++ makeAsmCounter1 at, at + 1, max)
| otherwise = code
-- | This generates the C code for a function utilizing inline assembly to find the total popcount of a length 'n' uint64_t buffer
makeAsmCounter n = unlines ["int counter (uint64_t * buf){",
" uint64_t cnt[" ++ show n ++ "];",
unlines [" cnt[" ++ show i ++ "] = 0;" | i <- [0..(n-1)]],
makeAsmCounterN n,
"",
concat $ " return cnt[0]" : [" + cnt[" ++ show k ++ "]" | k <- [1..(n-1)]] ++ [";"],
"}"]
-- | This makes a CULLong into a more or less readable string for debugging
listFromULL :: CULLong -> String
listFromULL 0 = []
listFromULL x = listFromULL (div x 2) ++ show (x .&. 1)
-- | This makes a [[CULLong]] into a more or less readable string for debugging
printULLs :: [[CULLong]] -> String
printULLs = unlines . map (show . map listFromULL)
-- | This sorts a list of tuples by the snd element
sortBySnd :: Ord b => [(a,b)] -> [(a,b)]
sortBySnd = sortBy (compare `Data.Function.on` snd)
| michaeljklein/HCy2C | Cycles/Maxcy.hs | mit | 24,857 | 0 | 17 | 8,941 | 4,459 | 2,516 | 1,943 | 313 | 3 |
-- | This module contains functions that act on actions.
module Game.Cosanostra.Action
( actionTraits
, actTurn
, actTraceTurn
, actPhase
, actTracePhase
, targetSelectors
, messagesFor
) where
import Game.Cosanostra.Effect
import Game.Cosanostra.Faction
import Game.Cosanostra.Lenses
import Game.Cosanostra.Types
import Game.Cosanostra.Selectors
import Control.Lens
import qualified Data.Map.Strict as M
import Data.List
import Data.Maybe
import qualified Data.Set as S
actionTraits :: Actions -> Action -> ActionTraits
actionTraits actions action = fromJust $ actions ^. at action
actTurn :: Act -> Turn
actTurn act = actTraceTurn (act ^. actTrace)
actTraceTurn :: ActTrace -> Turn
actTraceTurn fromPlan@ActFromPlan{} = fromPlan ^?! actTracePlanTurn
actTraceTurn fromRewrite@ActFromRewrite{} =
actTraceTurn (fromRewrite ^?! actTraceDependentTrace)
actPhase :: Act -> Phase
actPhase act = actTracePhase (act ^. actTrace)
actTracePhase :: ActTrace -> Phase
actTracePhase fromPlan@ActFromPlan{} = fromPlan ^?! actTracePlanPhase
actTracePhase fromRewrite@ActFromRewrite{} =
actTracePhase (fromRewrite ^?! actTraceDependentTrace)
-- | Gets the list of target selectors for a given action.
targetSelectors :: ActionType -> [Selector]
targetSelectors FruitVend{} = [alive]
targetSelectors Greet{} = [alive]
targetSelectors Visit{} = [alive]
targetSelectors Roleblock{} = [alive]
targetSelectors Rolestop{} = [otherAlive]
targetSelectors Protect{} = [otherAlive]
targetSelectors Kill{} = [alive]
targetSelectors StrongmanKill{} = [alive]
targetSelectors DesperadoKill{} = [alive]
targetSelectors KamikazeKill{} = [alive]
targetSelectors Suicide{} = []
targetSelectors Drive{} = [otherAlive, otherAlive]
targetSelectors Redirect{} = [otherAlive, alive]
targetSelectors Deflect{} = [otherAlive, alive]
targetSelectors Bodyguard{} = [otherAlive]
targetSelectors Hide{} = [otherAlive]
targetSelectors Jail{} = [otherAlive]
targetSelectors Babysit{} = [otherAlive]
targetSelectors Frame{} = [alive]
targetSelectors Commute{} = []
targetSelectors Recruit{} = [alive]
targetSelectors Vanillaize{} = [alive]
targetSelectors Watch{} = [alive]
targetSelectors Track{} = [alive]
targetSelectors Voyeur{} = [alive]
targetSelectors Follow{} = [alive]
targetSelectors Investigate{} = [alive]
targetSelectors RoleInvestigate{} = [alive]
targetSelectors ForensicInvestigate{} = [dead]
targetSelectors Pardon{} = [otherAlive]
targetSelectors Veto{} = []
targetSelectors StealVote{} = [otherAlive]
targetSelectors weak@Weak{} =
targetSelectors (weak ^?! actionTypeRealActionType)
-- | Gets the list of messages that should be delivered when an act is enacted.
messagesFor :: ActionType -> Players -> Actions -> [Act] -> Act -> M.Map Player [Message]
messagesFor weak@Weak{} players actions acts act =
messagesFor (weak ^?! actionTypeRealActionType) players actions acts act
messagesFor Watch{} players actions acts act =
M.fromList [(act ^. actSource, [Message
{ _messageInfo = PlayersInfo { _messageInfoPlayers = actual `S.union` faked }
, _messageActTrace = act ^. actTrace
, _messageAssociatesWithAct = True
}])]
where
turn = actTurn act
phase = actPhase act
acts' = takeWhile (\act' -> actPhase act' == phase &&
actTurn act' == turn) acts
source = act ^. actSource
[target] = act ^. actTargets
actual = S.fromList [act' ^. actSource
| act' <- acts'
, act /= act'
, target `elem` (act' ^. actTargets)
, let (Just aTraits) = actions ^. at (act' ^. actAction)
, not (aTraits ^. actionTraitsNinja)
]
faked
| isJust (target ^. to (playerEffects players source turn phase)
. to (effectsByTurn (actTurn act))
. to effectsCauseOfDeath) =
S.fromList [player
| player <- playerKeys players
, not (null (player ^. to (playerEffects players source turn phase)
. to (effectsByType _Gravedigger)))
]
| otherwise = S.empty
messagesFor Track{} players actions acts act =
M.fromList [(act ^. actSource, [Message
{ _messageInfo = PlayersInfo
{ _messageInfoPlayers = actual `S.union` faked
}
, _messageActTrace = act ^. actTrace
, _messageAssociatesWithAct = True
}])]
where
turn = actTurn act
phase = actPhase act
acts' = takeWhile (\act' -> actPhase act' == actPhase act &&
actTurn act' == actTurn act) acts
source = act ^. actSource
[target] = act ^. actTargets
actual = S.fromList [target'
| act' <- acts'
, act /= act'
, target == act' ^. actSource
, let (Just aTraits) = actions ^. at (act' ^. actAction)
, not (aTraits ^. actionTraitsNinja)
, target' <- act' ^. actTargets
]
faked
| not (null (target ^. to (playerEffects players source turn phase)
. to (effectsByType _Gravedigger))) =
S.fromList [player
| player <- playerKeys players
, isJust (player ^. to (playerEffects players source turn phase)
. to (effectsByTurn turn)
. to effectsCauseOfDeath)
]
| otherwise = S.empty
messagesFor Voyeur{} players actions acts act =
M.fromList [(act ^. actSource, [Message
{ _messageInfo = ActionsInfo
{ _messageInfoActions = actual `S.union` faked
}
, _messageActTrace = act ^. actTrace
, _messageAssociatesWithAct = True
}])]
where
turn = actTurn act
phase = actPhase act
acts' = takeWhile (\act' -> actPhase act' == actPhase act &&
actTurn act' == actTurn act) acts
source = act ^. actSource
[target] = act ^. actTargets
actual = S.fromList [action'
| act' <- acts'
, act /= act'
, target `elem` (act' ^. actTargets)
, let action' = act' ^. actAction
, let (Just aTraits) = actions ^. at action'
, not (aTraits ^. actionTraitsNinja)
]
faked
| isJust (target ^. to (playerEffects players source turn phase)
. to (effectsByTurn turn)
. to effectsCauseOfDeath) =
S.fromList [effect ^?! effectType . effectTypeGravedig
| effect <- target ^. to (playerEffects players source turn phase)
. to (effectsByType _Gravedigger)
]
| otherwise = S.empty
messagesFor Follow{} players actions acts act =
M.fromList [(act ^. actSource, [Message
{ _messageInfo = ActionsInfo { _messageInfoActions = actual `S.union` faked }
, _messageActTrace = act ^. actTrace
, _messageAssociatesWithAct = True
}])]
where
turn = actTurn act
phase = actPhase act
acts' = takeWhile (\act' -> actPhase act' == actPhase act &&
actTurn act' == actTurn act) acts
source = act ^. actSource
[target] = act ^. actTargets
actual = S.fromList [action'
| act' <- acts'
, act /= act'
, target == act' ^. actSource
, let action' = act' ^. actAction
, let (Just aTraits) = actions ^. at action'
, not (aTraits ^. actionTraitsNinja)
]
faked
| any (isJust . (^. to (playerEffects players source turn phase)
. to (effectsByTurn (actTurn act))
. to effectsCauseOfDeath))
(playerKeys players) =
S.fromList [effect ^?! effectType . effectTypeGravedig
| effect <- target ^. to (playerEffects players source turn phase)
. to (effectsByType _Gravedigger)
]
| otherwise = S.empty
messagesFor actionType@Investigate{} players _ _ act =
M.fromList [(act ^. actSource, [Message
{ _messageInfo = GuiltInfo { _messageInfoIsGuilty = result }
, _messageActTrace = act ^. actTrace
, _messageAssociatesWithAct = True
}])]
where
turn = actTurn act
phase = actPhase act
source = act ^. actSource
[target] = act ^. actTargets
guiltyFactions = actionType ^. actionTypeGuiltyFactions
result = isJust $ find check (target ^. to (playerEffects players source turn phase))
check effect@Effect{_effectType = Recruited{}} =
(effect ^?! effectType . effectTypeRecruitedFaction) `S.member` guiltyFactions
check effect@Effect{_effectType = Framed{}} =
(effect ^?! effectType . effectTypeFramedFaction) `S.member` guiltyFactions
check _ = False
messagesFor RoleInvestigate{} _ _ _ act =
M.fromList [(act ^. actSource, [Message
{ _messageInfo = RoleInfo { _messageInfoPlayer = target }
, _messageActTrace = act ^. actTrace
, _messageAssociatesWithAct = True
}])]
where
[target] = act ^. actTargets
messagesFor ForensicInvestigate{} players actions acts act =
M.fromList [(act ^. actSource, [Message
{ _messageInfo = PlayersInfo { _messageInfoPlayers = actual `S.union` faked }
, _messageActTrace = act ^. actTrace
, _messageAssociatesWithAct = True
}])]
where
turn = actTurn act
phase = actPhase act
source = act ^. actSource
[target] = act ^. actTargets
actual = S.fromList [act' ^. actSource
| act' <- acts
, act /= act'
, target `elem` (act' ^. actTargets)
, let (Just aTraits) = actions ^. at (act' ^. actAction)
, not (aTraits ^. actionTraitsNinja)
]
faked
| target ^. to (playerEffects players source turn phase)
. to effectsCauseOfDeath /= Just Lynched =
S.fromList [player
| player <- playerKeys players
, not (null (player ^. to (playerEffects players source turn phase)
. to (effectsByType _Gravedigger)))
]
| otherwise = S.empty
messagesFor FruitVend{} _ _ _ act =
M.fromList [(target, [Message
{ _messageInfo = FruitInfo
, _messageActTrace = act ^. actTrace
, _messageAssociatesWithAct = False
}])]
where
[target] = act ^. actTargets
messagesFor Greet{} players _ _ act =
M.fromList [(target, [Message
{ _messageInfo = GreetingInfo
{ _messageInfoGreeter = source
, _messageInfoGreeterFaction =
source ^. to (playerEffects players source turn phase)
. to effectsFaction
}
, _messageActTrace = act ^. actTrace
, _messageAssociatesWithAct = False
}])]
where
turn = actTurn act
phase = actPhase act
source = act ^. actSource
[target] = act ^. actTargets
messagesFor _ _ _ _ _ = M.empty
| rfw/cosanostra | src/Game/Cosanostra/Action.hs | mit | 11,689 | 0 | 20 | 3,840 | 3,375 | 1,778 | 1,597 | -1 | -1 |
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE Safe #-}
module Control.Concurrent.Transactional.Event (
Event,
module Control.Concurrent.Transactional.Event.Class,
-- * Synchronization
sync, syncID,
-- * Swapping
swap,
-- * Merging and Splitting
merge, tee, split,
-- * Threading
forkEvent, forkEventCancel, forkEventHandle, forkServer,
-- * Time
module Control.Concurrent.Transactional.Event.Time,
-- * Unsafe
unsafeLiftIO,
) where
import Control.Concurrent.Transactional.Event.Base
import Control.Concurrent.Transactional.Event.Class
import Control.Concurrent.Transactional.Event.Time
import Control.Concurrent.Transactional.EventHandle
import Data.List.Util
import Control.Applicative ((<|>))
import Control.Monad (join, msum)
import Data.Unique (Unique)
-- |Forks a new thread that continuously synchronizes on
-- an event parametrized by a state value. The result of
-- the event is fed back into itself as input.
forkServer :: a -> (a -> Event a) -> Event (Unique, EventHandle)
forkServer value step = forkEventHandle $ \close ->
let closeEvent = fmap return close
loopIO = join . sync . loopEvent
loopEvent x = closeEvent <|> do
x' <- step x
loopEvent x' <|> return (loopIO x')
in
closeEvent <|> return (loopIO value) <|> loopEvent value
-- |Concurrently evaluates an event that will be cancelled when the returned
-- handle goes out of scope.
forkEventHandle :: (Event () -> Event (IO ())) -> Event (Unique, EventHandle)
forkEventHandle event = do
(handle, close) <- newEventHandle
output <- forkEvent $ event close
return (output, handle)
-- |Concurrently evaluates an event that may be cancelled.
forkEventCancel :: (Event () -> Event (IO ())) -> Event (Unique, Event ())
forkEventCancel event = do
(waitFront, waitBack) <- swap
output <- forkEvent $ event $ waitFront ()
return (output, waitBack ())
-- |Merges a list of events. The resulting event will wait for all the source
-- events to synchronize before returning a value. Unlike
-- 'Control.Monad.sequence', the resulting event will accept the source events
-- in any order, preventing possible deadlocks.
merge :: [Event a] -> Event [a]
merge [] = return []
merge xs = do
(l, c, r) <- msum $
map (\(l, c, r) -> fmap (\c' -> (l, c', r)) c) $
splits xs
l' <- merge l
r' <- merge r
return $ l' ++ (c : r')
-- |Splits an event into two events that will be notified
-- simultaneously when the original event is fired.
tee :: Event a -> Event (Event a, Event a)
tee event = do
(send, receive) <- swap
let client = receive ()
server = do
x <- event
send x
return x
output = client <|> server
return (output, output)
-- |Splits an event into a user defined number of events that will be
-- notified simultaneously when the original event is fired.
split :: Int -> Event a -> Event [Event a]
split 0 _ = return []
split count event = do
(x, y) <- tee event
xs <- split (count - 1) y
return (x:xs)
| YellPika/Hannel | src/Control/Concurrent/Transactional/Event.hs | mit | 3,135 | 0 | 17 | 736 | 848 | 456 | 392 | 62 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Query.InsertAnswers where
import qualified Data.List as L (head)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.Transaction
import Import hiding (Query)
import Opaleye hiding (not, null)
import qualified Opaleye as O
import Query.Model
import Query.Types
insertAnswers :: [(QuestionData, SurveyInput)] -> Connection -> IO ()
insertAnswers answers conn = do
let dataInputs = second (\(InputData d) -> d) <$> filter (isData . snd) answers
let otherInputs = second (\(InputOther d) -> d) <$> filter (isOther . snd) answers
withTransactionSerializable conn $ do
(insertedOthers :: [RatingData]) <- if not $ null otherInputs
then mconcat <$> mapM (\d -> runInsertReturning conn ratingTable d id) (convertNewOther <$> otherInputs)
else return []
let allInputs = zip (fst $ unzip otherInputs) insertedOthers ++ dataInputs
participant <- runInsertReturning conn participantTable newParticipant id
_ <- runInsertMany conn answerTable (convertInput (L.head participant) <$> allInputs)
return ()
newParticipant :: ParticipantWriteColumns
newParticipant = Participant { participantId = ParticipantId Nothing }
convertNewOther :: (QuestionData, Text) -> RatingWriteColumns
convertNewOther (question, newRating) = Rating {
ratingId = RatingId Nothing,
ratingSort = pgInt4 $ negate 1,
ratingValue = pgStrictText newRating,
ratingDevGiven = pgBool False,
ratingQgroupId = QgroupId $ pgInt4 $ unQgroupId $ questionQgroupId question
}
convertInput :: ParticipantData -> (QuestionData, RatingData) -> AnswerWriteColumns
convertInput participant (question, rating) = Answer {
answerId = AnswerId Nothing,
answerRatingId = RatingId $ pgInt4 $ unRatingId $ ratingId rating,
answerQuestionId = QuestionId $ pgInt4 $ unQuestionId $ questionId question,
answerParticipantId = ParticipantId $ pgInt4 $ unParticipantId $ participantId participant
}
| ForestPhoenix/FPSurvey | Query/InsertAnswers.hs | mit | 2,233 | 0 | 17 | 586 | 577 | 310 | 267 | 37 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
-- {-# LANGUAGE MagicHash #-}
module BrodyPrelude where
import qualified GHC.Types (Bool(True, False))
import Data.Char -- as Prelude.Data.Char
import GHC.Char (eqChar)
-- import GHC.Prim (eqChar#)
--import GHC.Prim (eqChar#)
type String = [Char]
data Bool = True | False
not :: Bool -> Bool
not True = False
not False = True
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
class Show a where
show :: a -> String
instance Show Bool where
show True = "True"
show False = "False"
instance Eq Char where
x == y = case (x `eqChar` y) of
GHC.Types.True -> True
GHC.Types.False -> False
x /= y = not (x == y)
instance Show [Char] where
show s = s
-- instance Show String where
-- show s = s | brodyberg/Notes | FindingSuccessAndFailure/validation-book/lib/BrodyPrelude.hs | mit | 776 | 0 | 9 | 180 | 258 | 146 | 112 | 25 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html
module Stratosphere.Resources.DAXCluster where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.DAXClusterSSESpecification
-- | Full data type definition for DAXCluster. See 'daxCluster' for a more
-- convenient constructor.
data DAXCluster =
DAXCluster
{ _dAXClusterAvailabilityZones :: Maybe (ValList Text)
, _dAXClusterClusterName :: Maybe (Val Text)
, _dAXClusterDescription :: Maybe (Val Text)
, _dAXClusterIAMRoleARN :: Val Text
, _dAXClusterNodeType :: Val Text
, _dAXClusterNotificationTopicARN :: Maybe (Val Text)
, _dAXClusterParameterGroupName :: Maybe (Val Text)
, _dAXClusterPreferredMaintenanceWindow :: Maybe (Val Text)
, _dAXClusterReplicationFactor :: Val Integer
, _dAXClusterSSESpecification :: Maybe DAXClusterSSESpecification
, _dAXClusterSecurityGroupIds :: Maybe (ValList Text)
, _dAXClusterSubnetGroupName :: Maybe (Val Text)
, _dAXClusterTags :: Maybe Object
} deriving (Show, Eq)
instance ToResourceProperties DAXCluster where
toResourceProperties DAXCluster{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::DAX::Cluster"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ fmap (("AvailabilityZones",) . toJSON) _dAXClusterAvailabilityZones
, fmap (("ClusterName",) . toJSON) _dAXClusterClusterName
, fmap (("Description",) . toJSON) _dAXClusterDescription
, (Just . ("IAMRoleARN",) . toJSON) _dAXClusterIAMRoleARN
, (Just . ("NodeType",) . toJSON) _dAXClusterNodeType
, fmap (("NotificationTopicARN",) . toJSON) _dAXClusterNotificationTopicARN
, fmap (("ParameterGroupName",) . toJSON) _dAXClusterParameterGroupName
, fmap (("PreferredMaintenanceWindow",) . toJSON) _dAXClusterPreferredMaintenanceWindow
, (Just . ("ReplicationFactor",) . toJSON) _dAXClusterReplicationFactor
, fmap (("SSESpecification",) . toJSON) _dAXClusterSSESpecification
, fmap (("SecurityGroupIds",) . toJSON) _dAXClusterSecurityGroupIds
, fmap (("SubnetGroupName",) . toJSON) _dAXClusterSubnetGroupName
, fmap (("Tags",) . toJSON) _dAXClusterTags
]
}
-- | Constructor for 'DAXCluster' containing required fields as arguments.
daxCluster
:: Val Text -- ^ 'daxcIAMRoleARN'
-> Val Text -- ^ 'daxcNodeType'
-> Val Integer -- ^ 'daxcReplicationFactor'
-> DAXCluster
daxCluster iAMRoleARNarg nodeTypearg replicationFactorarg =
DAXCluster
{ _dAXClusterAvailabilityZones = Nothing
, _dAXClusterClusterName = Nothing
, _dAXClusterDescription = Nothing
, _dAXClusterIAMRoleARN = iAMRoleARNarg
, _dAXClusterNodeType = nodeTypearg
, _dAXClusterNotificationTopicARN = Nothing
, _dAXClusterParameterGroupName = Nothing
, _dAXClusterPreferredMaintenanceWindow = Nothing
, _dAXClusterReplicationFactor = replicationFactorarg
, _dAXClusterSSESpecification = Nothing
, _dAXClusterSecurityGroupIds = Nothing
, _dAXClusterSubnetGroupName = Nothing
, _dAXClusterTags = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-availabilityzones
daxcAvailabilityZones :: Lens' DAXCluster (Maybe (ValList Text))
daxcAvailabilityZones = lens _dAXClusterAvailabilityZones (\s a -> s { _dAXClusterAvailabilityZones = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-clustername
daxcClusterName :: Lens' DAXCluster (Maybe (Val Text))
daxcClusterName = lens _dAXClusterClusterName (\s a -> s { _dAXClusterClusterName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-description
daxcDescription :: Lens' DAXCluster (Maybe (Val Text))
daxcDescription = lens _dAXClusterDescription (\s a -> s { _dAXClusterDescription = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-iamrolearn
daxcIAMRoleARN :: Lens' DAXCluster (Val Text)
daxcIAMRoleARN = lens _dAXClusterIAMRoleARN (\s a -> s { _dAXClusterIAMRoleARN = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-nodetype
daxcNodeType :: Lens' DAXCluster (Val Text)
daxcNodeType = lens _dAXClusterNodeType (\s a -> s { _dAXClusterNodeType = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-notificationtopicarn
daxcNotificationTopicARN :: Lens' DAXCluster (Maybe (Val Text))
daxcNotificationTopicARN = lens _dAXClusterNotificationTopicARN (\s a -> s { _dAXClusterNotificationTopicARN = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-parametergroupname
daxcParameterGroupName :: Lens' DAXCluster (Maybe (Val Text))
daxcParameterGroupName = lens _dAXClusterParameterGroupName (\s a -> s { _dAXClusterParameterGroupName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-preferredmaintenancewindow
daxcPreferredMaintenanceWindow :: Lens' DAXCluster (Maybe (Val Text))
daxcPreferredMaintenanceWindow = lens _dAXClusterPreferredMaintenanceWindow (\s a -> s { _dAXClusterPreferredMaintenanceWindow = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-replicationfactor
daxcReplicationFactor :: Lens' DAXCluster (Val Integer)
daxcReplicationFactor = lens _dAXClusterReplicationFactor (\s a -> s { _dAXClusterReplicationFactor = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-ssespecification
daxcSSESpecification :: Lens' DAXCluster (Maybe DAXClusterSSESpecification)
daxcSSESpecification = lens _dAXClusterSSESpecification (\s a -> s { _dAXClusterSSESpecification = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-securitygroupids
daxcSecurityGroupIds :: Lens' DAXCluster (Maybe (ValList Text))
daxcSecurityGroupIds = lens _dAXClusterSecurityGroupIds (\s a -> s { _dAXClusterSecurityGroupIds = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-subnetgroupname
daxcSubnetGroupName :: Lens' DAXCluster (Maybe (Val Text))
daxcSubnetGroupName = lens _dAXClusterSubnetGroupName (\s a -> s { _dAXClusterSubnetGroupName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-tags
daxcTags :: Lens' DAXCluster (Maybe Object)
daxcTags = lens _dAXClusterTags (\s a -> s { _dAXClusterTags = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/DAXCluster.hs | mit | 6,982 | 0 | 15 | 833 | 1,261 | 712 | 549 | 88 | 1 |
module HaskQuest.Game.Objects
( module HaskQuest.Game.Objects.Item
, module HaskQuest.Game.Objects.ItemMap
, module HaskQuest.Game.Objects.Room
, module HaskQuest.Game.Objects.RoomMap
) where
import HaskQuest.Game.Objects.Item
import HaskQuest.Game.Objects.ItemMap
import HaskQuest.Game.Objects.Room
import HaskQuest.Game.Objects.RoomMap
| pdarragh/HaskQuest | src/HaskQuest/Game/Objects.hs | mit | 359 | 0 | 5 | 45 | 69 | 50 | 19 | 9 | 0 |
module Caesar (caesar, uncaesar) where
import Data.Char
caesar, uncaesar :: (Integral a) => a -> String -> String
caesar k = map f
where f c = case generalCategory c of
LowercaseLetter -> addChar 'a' k c
UppercaseLetter -> addChar 'A' k c
_ -> c
uncaesar k = caesar (-k)
addChar :: (Integral a) => Char -> a -> Char -> Char
addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c
| rickerbh/AoC | AoC2016/src/Caesar.hs | mit | 528 | 0 | 12 | 174 | 212 | 111 | 101 | 13 | 3 |
{-# LANGUAGE BangPatterns #-}
module ObjectBehavior (aicube, camera) where
import Data.Maybe (fromJust)
import FRP.Yampa.Core
import FRP.Yampa
import Camera
import IdentityList
import MD3
import Matrix
import Object
import GameInputParser
ray ::
(Double, Double, Double) ->
(Double, Double, Double) -> ILKey -> ILKey -> Object
ray (!x, !y, !z) (!vx, !vy, !vz) firedfrom iD
= arr
(\ oi ->
let clippedPos = oiCollisionPos oi in
let grounded = oiOnLand oi in ((), (clippedPos, grounded)))
>>>
(first (after 0.25 ()) >>>
arr
(\ (timeout, (clippedPos, grounded)) ->
(grounded, (clippedPos, timeout))))
>>>
(first (iPre False <<< identity) >>>
arr
(\ (cl, (clippedPos, timeout)) ->
let (vvx, vvy, vvz) = normalise $ vectorSub end start in
(clippedPos, (cl, timeout, vvx, vvy, vvz))))
>>>
(first (iPre start <<< arr not0) >>>
arr
(\ (clip, (cl, timeout, vvx, vvy, vvz)) ->
(vvx, (cl, clip, timeout, vvy, vvz))))
>>>
(first (arr (\ vvx -> 7500 * vvx) >>> integral) >>>
arr
(\ (ucx, (cl, clip, timeout, vvy, vvz)) ->
(vvy, (cl, clip, timeout, ucx, vvz))))
>>>
(first (arr (\ vvy -> 7500 * vvy) >>> integral) >>>
arr
(\ (ucy, (cl, clip, timeout, ucx, vvz)) ->
(vvz, (cl, clip, timeout, ucx, ucy))))
>>>
(first (arr (\ vvz -> 7500 * vvz) >>> integral) >>>
arr
(\ (ucz, (cl, clip, timeout, ucx, ucy)) ->
(cl, (cl, clip, timeout, ucx, ucy, ucz))))
>>>
(first edge >>>
arr
(\ (clipev, (cl, clip, timeout, ucx, ucy, ucz)) ->
ObjOutput{ooObsObjState =
OOSRay{rayStart = start, rayEnd = clip,
rayUC = vectorAdd start (ucx, ucy, ucz), clipped = cl,
firedFrom = firedfrom},
ooKillReq = timeout, ooSpawnReq = noEvent,
ooSendMessage =
clipev `tag` [(firedfrom, (iD, Coord clip))]}))
where (start, end) = firePos (x, y, z) (vx, vy, vz)
_ = normalise $ vectorSub end start
not0 c
| c /= (0, 0, 0) = c
| otherwise = (x, y, z)
projectile :: (Vec3, Vec3) -> ILKey -> ILKey -> Object
projectile ((sx, sy, sz), (vx, vy, vz)) firedfrom _
= arr
(\ oi ->
let grounded = oiOnLand oi in
let hits = oiHit oi in (hits, grounded))
>>>
(first identity >>> arr (\ (hit, grounded) -> (grounded, hit))) >>>
((first (iPre False <<< identity) >>> first edge) >>>
arr (\ (clipEv, hit) -> ((), (clipEv, hit))))
>>>
(first (arr (\ () -> 1500 * vx) >>> imIntegral sx) >>>
arr (\ (x, (clipEv, hit)) -> ((), (clipEv, hit, x))))
>>>
(first (arr (\ () -> 1500 * vy) >>> imIntegral sy) >>>
arr (\ (y, (clipEv, hit, x)) -> ((), (clipEv, hit, x, y))))
>>>
(first (arr (\ () -> 1500 * vz) >>> imIntegral sz) >>>
arr
(\ (z, (clipEv, hit, x, y)) ->
((x, y, z), (clipEv, hit, x, y, z))))
>>>
(first (iPre (sx, sy, sz) <<< identity) >>>
arr
(\ (oldpos, (clipEv, hit, x, y, z)) ->
((clipEv, hit), (oldpos, x, y, z))))
>>>
(first
(arr (\ (clipEv, hit) -> (isEvent clipEv || isEvent hit)) >>> edge)
>>>
arr
(\ (hitEv, (oldpos, x, y, z)) ->
ObjOutput{ooObsObjState =
OOSProjectile{projectileOldPos = oldpos,
projectileNewPos = (x, y, z),
firedFrom = firedfrom},
ooKillReq = hitEv, ooSpawnReq = noEvent,
ooSendMessage = noEvent}))
camera ::
Camera ->
[(String, AnimState, AnimState)] ->
[(ILKey, Message)] -> ILKey -> Object
camera cam _ _ iD
= arr
(\ oi ->
let gi = oiGameInput oi in
let clippedcam = oiCollision oi in
let grounded = oiOnLand oi in
let msgs = oiMessage oi in
(gi, (clippedcam, gi, grounded, msgs, oi)))
>>>
(first ptrPos >>>
arr
(\ (pPos, (clippedcam, gi, grounded, msgs, oi)) ->
(gi, (clippedcam, gi, grounded, msgs, oi, pPos))))
>>>
(first (movementKS 400) >>>
arr
(\ (forwardVel, (clippedcam, gi, grounded, msgs, oi, pPos)) ->
(gi, (clippedcam, forwardVel, gi, grounded, msgs, oi, pPos))))
>>>
(first (strafeKS 400) >>>
arr
(\ (strafeVel,
(clippedcam, forwardVel, gi, grounded, msgs, oi, pPos))
->
(gi,
(clippedcam, forwardVel, gi, grounded, msgs, oi, pPos,
strafeVel))))
>>>
(first lbp >>>
arr
(\ (trigger,
(clippedcam, forwardVel, gi, grounded, msgs, oi, pPos, strafeVel))
->
(gi,
(clippedcam, forwardVel, gi, grounded, msgs, oi, pPos, strafeVel,
trigger))))
>>>
(first rbp >>>
arr
(\ (rtrigger,
(clippedcam, forwardVel, gi, grounded, msgs, oi, pPos, strafeVel,
trigger))
->
(gi,
(clippedcam, forwardVel, gi, grounded, msgs, oi, pPos, rtrigger,
strafeVel, trigger))))
>>>
(first getDt >>>
arr
(\ (dt,
(clippedcam, forwardVel, gi, grounded, msgs, oi, pPos, rtrigger,
strafeVel, trigger))
->
((clippedcam, pPos),
(clippedcam, dt, forwardVel, gi, grounded, msgs, oi, rtrigger,
strafeVel, trigger))))
>>>
(first
(arr (\ (clippedcam, pPos) -> (pPos, clippedcam)) >>>
(iPre cam <<< arr setView))
>>>
arr
(\ (cam1,
(clippedcam, dt, forwardVel, gi, grounded, msgs, oi, rtrigger,
strafeVel, trigger))
->
((cam1, dt, forwardVel),
(cam1, clippedcam, dt, gi, grounded, msgs, oi, rtrigger, strafeVel,
trigger))))
>>>
(first
(arr (\ (cam1, dt, forwardVel) -> (forwardVel * dt, cam1)) >>>
moves)
>>>
arr
(\ (cam2,
(cam1, clippedcam, dt, gi, grounded, msgs, oi, rtrigger, strafeVel,
trigger))
->
((cam2, dt, strafeVel),
(cam1, clippedcam, gi, grounded, msgs, oi, rtrigger, trigger))))
>>>
(first
(arr (\ (cam2, dt, strafeVel) -> (strafeVel * dt, cam2)) >>>
strafes)
>>>
arr
(\ (cam3,
(cam1, clippedcam, gi, grounded, msgs, oi, rtrigger, trigger))
->
((gi, grounded),
(cam1, cam3, clippedcam, msgs, oi, rtrigger, trigger))))
>>>
(first (arr (\ (gi, grounded) -> (grounded, gi)) >>> fallingp) >>>
arr
(\ (yVel, (cam1, cam3, clippedcam, msgs, oi, rtrigger, trigger)) ->
((cam3, yVel), (cam1, clippedcam, msgs, oi, rtrigger, trigger))))
>>>
((first (arr dropCam) >>>
loop
(arr
(\ ((cam4, (cam1, clippedcam, msgs, oi, rtrigger, trigger)),
msgn)
->
((msgn, msgs, rtrigger),
(cam1, cam4, clippedcam, msgs, oi, rtrigger, trigger)))
>>>
(first
(arr
(\ (msgn, msgs, rtrigger) ->
if isEvent rtrigger then ([], msgn) else (getMsg0 msgs msgn, msgn))
>>> (iPre ([], []) <<< identity))
>>>
arr
(\ ((msgn, msgi),
(cam1, cam4, clippedcam, msgs, oi, rtrigger, trigger))
->
((cam1, cam4, clippedcam, msgi, msgs, oi, rtrigger,
trigger),
msgn)))))
>>>
arr
(\ (cam1, cam4, clippedcam, msgi, msgs, oi, rtrigger, trigger) ->
(oi, (cam1, cam4, clippedcam, msgi, msgs, rtrigger, trigger))))
>>>
((first (arr oiHit >>> (iPre noEvent <<< identity))
>>>
loop
(arr
(\ ((hitEv,
(cam1, cam4, clippedcam, msgi, msgs, rtrigger, trigger)),
currentHealth)
->
((currentHealth, hitEv),
(cam1, cam4, clippedcam, msgi, msgs, rtrigger, trigger)))
>>>
(first
(arr
(\ (currentHealth, hitEv) ->
if isEvent hitEv then currentHealth -
realToFrac
(length (fromEvent hitEv) * 3) else currentHealth)
>>> (iPre 100 <<< identity))
>>>
arr
(\ (currentHealth,
(cam1, cam4, clippedcam, msgi, msgs, rtrigger,
trigger))
->
((cam1, cam4, clippedcam, currentHealth, msgi, msgs,
rtrigger, trigger),
currentHealth)))))
>>>
arr
(\ (cam1, cam4, clippedcam, currentHealth, msgi, msgs, rtrigger,
trigger)
->
(msgs,
(cam1, cam4, clippedcam, currentHealth, msgi, rtrigger,
trigger))))
>>>
((first (iPre noEvent <<< identity) >>>
loop
(arr
(\ ((msges,
(cam1, cam4, clippedcam, currentHealth, msgi, rtrigger,
trigger)),
kills)
->
((kills, msges),
(cam1, cam4, clippedcam, currentHealth, msges, msgi,
rtrigger, trigger)))
>>>
(first
(arr
(\ (kills, msges) ->
kills + length (findKills (event2List msges)))
>>> (iPre 0 <<< identity))
>>>
arr
(\ (kills,
(cam1, cam4, clippedcam, currentHealth, msges,
msgi, rtrigger, trigger))
->
((cam1, cam4, clippedcam, currentHealth, kills,
msges, msgi, rtrigger, trigger),
kills)))))
>>>
arr
(\ (cam1, cam4, clippedcam, currentHealth, kills, msges, msgi,
rtrigger, trigger)
->
((msgi, rtrigger),
(cam1, cam4, clippedcam, currentHealth, kills, msges,
trigger))))
>>>
(first
(arr (\ (msgi, rtrigger) -> (rtrigger, msgi)) >>>
(iPre (noEvent, []) <<< identity))
>>>
arr
(\ ((rev, msgi2),
(cam1, cam4, clippedcam, currentHealth, kills, msges,
trigger))
->
(clippedcam,
(cam1, cam4, currentHealth, kills, msges, msgi2, rev,
trigger))))
>>>
(first (iPre cam <<< identity) >>>
arr
(\ (ccam,
(cam1, cam4, currentHealth, kills, msges, msgi2, rev,
trigger))
->
ObjOutput{ooSpawnReq =
trigger `tag`
[ray (cpos cam1) (viewPos cam1) iD],
ooObsObjState =
OOSCamera{newCam = cam4, oldCam = cam1,
health = currentHealth, ammo = 100,
score = kills,
cood =
if isEvent rev then reverse $
map getCoordFromMsg
msgi2 else []},
ooKillReq = noEvent,
ooSendMessage =
case event2List msges of
[] -> noEvent
_ -> Event () `tag`
(case
findEnemies
(event2List msges)
of
[] -> []
_ -> [toTargetPosition iD
(cpos ccam)
(head
(findEnemies
(event2List
msges)))])}))
event2List :: Event [a] -> [a]
event2List ev
| isEvent ev = fromEvent ev
| otherwise = []
getMsg0 ::
Event [(ILKey, Message)] ->
[(ILKey, Message)] -> [(ILKey, Message)]
getMsg0 ev ls
= if isEvent ev then (case findCoords (fromEvent ev) ++ ls of
x -> x) else ls
findKills :: [(ILKey, Message)] -> [ILKey]
findKills ((k, EnemyDown) : kmsgs) = k : findKills kmsgs
findKills ((_, _) : kmsgs) = findKills kmsgs
findKills [] = []
findEnemies :: [(ILKey, Message)] -> [ILKey]
findEnemies ((k, PlayerLockedOn) : kmsgs) = k : findEnemies kmsgs
findEnemies ((_, _) : kmsgs) = findEnemies kmsgs
findEnemies [] = []
toTargetPosition ::
ILKey -> Vec3 -> ILKey -> (ILKey, (ILKey, Message))
toTargetPosition iD position contact
= (contact, (iD, TargetPosition position))
findCoords :: [(ILKey, Message)] -> [(ILKey, Message)]
findCoords ((k, Coord x) : kmsgs)
= (k, Coord x) : findCoords kmsgs
findCoords ((_, _) : kmsgs) = findCoords kmsgs
findCoords [] = []
getCoordFromMsg :: (ILKey, Message) -> Vec3
getCoordFromMsg (_, Coord xyz) = xyz
getCoordFromMsg _ = (0,0,0)
aicube ::
(Double, Double, Double) ->
(Double, Double, Double) ->
[(Double, Double, Double)] ->
String -> (AnimState, AnimState) -> ILKey -> Object
aicube (x, y, z) size waypoints modelname (ua, la) iD
= ((arr (\ oi -> let gi = oiGameInput oi in (gi, oi)) >>>
first getT)
>>>
arr
(\ (t, oi) ->
let hitList = oiHit oi in
let enemySighted = oiVisibleObjs oi in
(hitList, (enemySighted, hitList, oi, t))))
>>>
(first
(arr
(\ hitList ->
if isEvent hitList then getFire (snd (head (fromEvent hitList))) else Nothing)
>>> (iPre Nothing <<< identity))
>>>
arr
(\ (hitSource, (enemySighted, hitList, oi, t)) ->
(hitSource, (enemySighted, hitList, hitSource, oi, t))))
>>>
((first (arr (/= Nothing) >>> edge) >>>
loop
(arr
(\ ((hitev1, (enemySighted, hitList, hitSource, oi, t)),
currentHealth)
->
((currentHealth, hitList),
(enemySighted, hitSource, hitev1, oi, t)))
>>>
(first
(arr
(\ (currentHealth, hitList) ->
if isEvent hitList then currentHealth - 3 else currentHealth)
>>> (iPre 100 <<< identity))
>>>
arr
(\ (currentHealth, (enemySighted, hitSource, hitev1, oi, t)) ->
((currentHealth, enemySighted, hitSource, hitev1, oi, t),
currentHealth)))))
>>>
arr
(\ (currentHealth, enemySighted, hitSource, hitev1, oi, t) ->
(currentHealth,
(currentHealth, enemySighted, hitSource, hitev1, oi, t))))
>>>
((first (arr (<= 0) >>> edge)
>>>
loop
(arr
(\ ((hitev,
(currentHealth, enemySighted, hitSource, hitev1, oi, t)),
isDead)
->
((hitev, isDead),
(currentHealth, enemySighted, hitSource, hitev, hitev1, oi, t)))
>>>
(first
(arr
(\ (hitev, isDead) ->
isEvent hitev || isDead)
>>> (iPre False <<< identity))
>>>
arr
(\ (isDead,
(currentHealth, enemySighted, hitSource, hitev, hitev1, oi, t))
->
((currentHealth, enemySighted, hitSource, hitev, hitev1, isDead,
oi, t),
isDead)))))
>>>
arr
(\ (currentHealth, enemySighted, hitSource, hitev, hitev1, isDead,
oi, t)
->
((enemySighted, isDead),
(currentHealth, enemySighted, hitSource, hitev, hitev1, isDead, oi,
t))))
>>>
(((first
(arr
(\ (enemySighted, isDead) ->
isEvent enemySighted && not isDead)
>>> (iPre noEvent <<< edge))
>>>
loop
(arr
(\ ((enemyS,
(currentHealth, enemySighted, hitSource, hitev, hitev1, isDead, oi,
t)),
enemy)
->
((enemy, enemySighted),
(currentHealth, enemyS, enemySighted, hitSource, hitev, hitev1,
isDead, oi, t)))
>>>
(first
(arr
(\ (enemy, enemySighted) ->
if isEvent enemySighted then enemySighted else enemy)
>>> (iPre noEvent <<< identity))
>>>
arr
(\ (enemy,
(currentHealth, enemyS, enemySighted, hitSource, hitev, hitev1,
isDead, oi, t))
->
((currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, oi, t),
enemy)))))
>>>
loop
(arr
(\ ((currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, oi, t),
targ)
->
((enemySighted, targ),
(currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, oi, t)))
>>>
(first
(arr
(\ (enemySighted, targ) ->
if isEvent enemySighted then cpos (oldCam (snd (head (fromEvent enemySighted)))) else targ)
>>> (iPre (0, 0, 0) <<< identity))
>>>
arr
(\ (targ,
(currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, oi, t))
->
((currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, oi, t, targ),
targ)))))
>>>
arr
(\ (currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, oi, t, targ)
->
(oi,
(currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, oi, t, targ))))
>>>
(first
(arr oiMessage >>> (iPre noEvent <<< identity))
>>>
arr
(\ (msgs,
(currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, oi, t, targ))
->
((isDead, msgs),
(currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, msgs, oi, t, targ))))
>>>
(first
(arr
(\ (isDead, msgs) ->
(isEvent msgs && not isDead) && (case getTargetPosition (fromEvent msgs) of
Just _ -> True
_ -> False))
>>> edge)
>>>
arr
(\ (msgReceived,
(currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, msgs, oi, t, targ))
->
((isDead, msgs),
(currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, msgReceived, oi, t, targ))))
>>>
(first
(arr
(\ (isDead, msgs) ->
(isEvent msgs && not isDead) && (case getTargetPosition2 (fromEvent msgs) of
Just _ -> True
_ -> False))
>>> edge)
>>>
arr
(\ (respond2Attack,
(currentHealth, enemy, enemyS, enemySighted, hitSource, hitev,
hitev1, isDead, msgReceived, oi, t, targ))
->
((enemySighted, msgReceived),
(currentHealth, enemy, enemyS, hitSource, hitev, hitev1, isDead,
oi, respond2Attack, t, targ))))
>>>
(first
(arr
(\ (enemySighted, msgReceived) ->
isNoEvent enemySighted && isNoEvent msgReceived)
>>> (iPre noEvent <<< edge))
>>>
arr
(\ (targetLost1,
(currentHealth, enemy, enemyS, hitSource, hitev, hitev1, isDead,
oi, respond2Attack, t, targ))
->
((enemyS, targetLost1),
(currentHealth, enemy, enemyS, hitSource, hitev, hitev1, isDead,
oi, respond2Attack, t, targ, targetLost1))))
>>>
(first
(arr
(\ (enemyS, targetLost1) ->
((),
(enemyS `tag` constant noEvent) `lMerge`
(targetLost1 `tag` repeatedly 0.5 (Event ()))))
>>> rSwitch (constant noEvent))
>>>
loop
(arr
(\ ((_,
(currentHealth, enemy, enemyS, hitSource, hitev, hitev1, isDead,
oi, respond2Attack, t, targ, targetLost1)),
~(angle, lEndEv, oldPos, uEndEv))
->
((angle, enemyS, hitev, lEndEv, oi, oldPos, respond2Attack,
uEndEv),
(currentHealth, enemy, hitSource, hitev, hitev1, isDead, t, targ,
targetLost1)))
>>>
(first
(arr
(\ (angle, enemyS, hitev, lEndEv, oi, oldPos, respond2Attack,
uEndEv)
->
((oi, uEndEv, lEndEv),
(enemyS `tag` turnToFaceTarget (oldPos, angle)) `lMerge`
respond2Attack
`tag` turnToFaceTarget (oldPos, angle)
`lMerge` hitev
`tag` playDead oldPos angle))
>>> drSwitch (followWayPoints (x, y, z) waypoints))
>>>
arr
(\ ((newPos, oldPos, angle, ptch, attack,
(upperIdx, lowerIdx)),
(currentHealth, enemy, hitSource, hitev, hitev1, isDead, t,
targ, targetLost1))
->
((t, upperIdx),
(angle, attack, currentHealth, enemy, hitSource, hitev,
hitev1, isDead, lowerIdx, newPos, oldPos, ptch, t, targ,
targetLost1))))
>>>
(first (updateAnimSF ua) >>>
arr
(\ ((uEndEv, upperstate),
(angle, attack, currentHealth, enemy, hitSource, hitev,
hitev1, isDead, lowerIdx, newPos, oldPos, ptch, t, targ,
targetLost1))
->
((lowerIdx, t),
(angle, attack, currentHealth, enemy, hitSource, hitev,
hitev1, isDead, newPos, oldPos, ptch, targ, targetLost1,
uEndEv, upperstate))))
>>>
(first
(arr (\ (lowerIdx, t) -> (t, lowerIdx)) >>> updateAnimSF la)
>>>
arr
(\ ((lEndEv, lowerstate),
(angle, attack, currentHealth, enemy, hitSource, hitev,
hitev1, isDead, newPos, oldPos, ptch, targ,
targetLost1, uEndEv, upperstate))
->
((angle, attack, currentHealth, enemy, hitSource, hitev,
hitev1, isDead, lowerstate, newPos, oldPos, ptch,
targ, targetLost1, upperstate),
(angle, lEndEv, oldPos, uEndEv))))))
>>>
arr
(\ (angle, attack, currentHealth, enemy, hitSource, hitev, hitev1,
isDead, lowerstate, newPos, oldPos, ptch, targ, targetLost1,
upperstate)
->
let f = 1 in
ObjOutput{ooObsObjState =
OOSAICube{oosNewCubePos = newPos,
oosOldCubePos = oldPos, oosCubeSize = size,
oosCubeAngle = angle, oosCubePitch = ptch,
upperAnim = upperstate,
lowerAnim = lowerstate,
health = currentHealth, target = targ,
fade = f, modelName = modelname},
ooKillReq = noEvent,
ooSpawnReq =
attack `tag`
[projectile (getMuzzlePoint (oldPos, targ)) iD],
ooSendMessage =
hitev `tag`
(if isDead then [] else [(fromJust hitSource, (iD, EnemyDown))])
`lMerge` targetLost1
`tag`
[(fst (head (fromEvent enemy)), (iD, PlayerLockedOn))]
`lMerge` hitev1
`tag` [(fromJust hitSource, (iD, PlayerLockedOn2))]})
getFire :: ObsObjState -> Maybe ILKey
getFire obj
| isRay obj = Just (firedFrom obj)
| otherwise = Nothing
getTargetPosition :: [(ILKey, Message)] -> Maybe Vec3
getTargetPosition ((_, TargetPosition pos) : _) = Just pos
getTargetPosition (_ : rest) = getTargetPosition rest
getTargetPosition [] = Nothing
getTargetPosition2 :: [(ILKey, Message)] -> Maybe Vec3
getTargetPosition2 ((_, TargetPosition2 pos) : _) = Just pos
getTargetPosition2 (_ : rest) = getTargetPosition2 rest
getTargetPosition2 [] = Nothing
getMuzzlePoint :: (Vec3, Vec3) -> (Vec3, Vec3)
getMuzzlePoint ((x, y, z), (ox, oy, oz))
= let (x3, _, z3)
= normalise (vectorSub (ox, oy + 45, oz) (x, y, z))
(x7, _, z7) = normalise (vectorSub (ox, 0, oz) (x, 0, z))
(x4, _, z4) = normalise $ crossProd (x3, 0, z3) (0, 1, 0)
(x5, y5, z5)
= (x + (x7 * (- 18.55)) + (x4 * 9.6), y + 4,
z + (z7 * (- 18.55)) + (z4 * 9.6))
(x12, y12, z12)
= normalise (vectorSub (ox, oy - 5, oz) (x, y, z))
(x6, y6, z6)
= vectorAdd (x5, y5, z5) (x12 * 42, y12 * 42, z12 * 42)
(x9, y9, z9) = normalise (vectorSub (x6, y6, z6) (x5, y5, z5))
(x10, y10, z10) = normalise $ crossProd (x9, y9, z9) (0, 1, 0)
(x13, y13, z13)
= normalise $ crossProd (x9, y9, z9) (x10, y10, z10)
muzzlePoint
= vectorAdd (x6, y6, z6)
(x13 * (- 9.5), y13 * (- 9.5), z13 * (- 9.5))
muzzleEnd
= vectorAdd (x5, y5, z5)
(x13 * (- 9.5), y13 * (- 9.5), z13 * (- 9.5))
fireVec = normalise (vectorSub muzzlePoint muzzleEnd)
in (muzzlePoint, fireVec)
falling :: SF (Bool, GameInput, Double) Double
falling
= loop
(arr
(\ ((lnd, _, dt), pos) ->
if lnd then (- 0.5) else pos - (6 * 200 * dt))
>>> ((iPre 0 <<< identity) >>> arr (\ pos -> (pos, pos))))
turnToFaceTarget ::
(Vec3, Double) ->
SF (ObjInput, Event (), Event ())
(Vec3, Vec3, Double, Double, Event (), (Int, Int))
turnToFaceTarget (currentPos, initialAngle)
= arr
(\ (oi, ev1, ev2) ->
let gi = oiGameInput oi in
let clippedPos = oiCollisionPos oi in
let grounded = oiOnLand oi in
(gi, (clippedPos, ev1, ev2, gi, grounded, oi)))
>>>
((first getDt >>>
loop
(arr
(\ ((dt, (clippedPos, ev1, ev2, gi, grounded, oi)), cnt) ->
(cnt, (clippedPos, dt, ev1, ev2, gi, grounded, oi)))
>>>
(first (arr (+ 1) >>> (iPre 0 <<< identity)) >>>
arr
(\ (cnt, (clippedPos, dt, ev1, ev2, gi, grounded, oi)) ->
((clippedPos, cnt, dt, ev1, ev2, gi, grounded, oi), cnt)))))
>>>
arr
(\ (clippedPos, cnt, dt, ev1, ev2, gi, grounded, oi) ->
(clippedPos, (cnt, dt, ev1, ev2, gi, grounded, oi))))
>>>
(first (iPre currentPos <<< identity) >>>
arr
(\ ((ox1, oy1, oz1), (cnt, dt, ev1, ev2, gi, grounded, oi)) ->
((cnt, ox1, oy1, oz1), (dt, ev1, ev2, gi, grounded, oi))))
>>>
(first
(arr
(\ (cnt, ox1, oy1, oz1) ->
if cnt > (3 :: Int) && (ox1, oy1, oz1) /= currentPos then (ox1, oy1, oz1) else currentPos)
>>> identity)
>>>
arr
(\ ((ox, oy, oz), (dt, ev1, ev2, gi, grounded, oi)) ->
((dt, gi, grounded), (ev1, ev2, oi, ox, oy, oz))))
>>>
((((((first
(arr (\ (dt, gi, grounded) -> (grounded, gi, dt)) >>>
(iPre 0 <<< falling))
>>>
arr
(\ (yVel, (ev1, ev2, oi, ox, oy, oz)) ->
let enemySighted = oiVisibleObjs oi in
(enemySighted, ev1, ev2, ox, oy, oz, yVel)))
>>>
loop
(arr
(\ ((enemySighted, ev1, ev2, ox, oy, oz, yVel), targetAnglei) ->
((enemySighted, ox, oy, oz, targetAnglei),
(enemySighted, ev1, ev2, ox, oy, oz, yVel)))
>>>
(first
(arr
(\ (enemySighted, ox, oy, oz, targetAnglei) ->
if isEvent enemySighted then getAngle
((ox, oy, oz),
cpos
(oldCam (snd (head (fromEvent enemySighted))))) else targetAnglei)
>>> (iPre initialAngle <<< identity))
>>>
arr
(\ (targetAnglei, (enemySighted, ev1, ev2, ox, oy, oz, yVel)) ->
((enemySighted, ev1, ev2, ox, oy, oz, targetAnglei, yVel),
targetAnglei)))))
>>>
loop
(arr
(\ ((enemySighted, ev1, ev2, ox, oy, oz, targetAnglei, yVel),
angle)
->
let targetAngle
= if
abs (angle - targetAnglei) <
abs (angle - (targetAnglei + 360)) then targetAnglei else targetAnglei + 360
in
let angularV
= if True then (if abs (angle - targetAngle) > 2 then (if angle < targetAngle then 270 else (- 270)) else targetAngle - angle) else 0
in
(angularV,
(enemySighted, ev1, ev2, ox, oy, oz, targetAngle, yVel)))
>>>
(first ((initialAngle +) ^<< integral) >>>
arr
(\ (angle, (enemySighted, ev1, ev2, ox, oy, oz, targetAngle, yVel))
->
let legState
= if abs (angle - targetAngle) < 2 then idleLegs else turn
in
((ev2, legState),
(angle, enemySighted, ev1, legState, ox, oy, oz, targetAngle,
yVel))))
>>>
(first
(arr
(\ (ev2, legState) -> ((legState == idleLegs) && isEvent ev2))
>>> edge)
>>>
arr
(\ (switch2idle,
(angle, enemySighted, ev1, legState, ox, oy, oz, targetAngle,
yVel))
->
(legState,
(angle, enemySighted, ev1, ox, oy, oz, switch2idle, targetAngle,
yVel))))
>>>
(first (arr (== turn) >>> edge) >>>
arr
(\ (turning,
(angle, enemySighted, ev1, ox, oy, oz, switch2idle,
targetAngle, yVel))
->
((switch2idle, turning),
(angle, enemySighted, ev1, ox, oy, oz, targetAngle, yVel))))
>>>
(first
(arr
(\ (switch2idle, turning) ->
((),
turning `tag` constant turn `lMerge` switch2idle `tag`
constant idleLegs))
>>> drSwitch (constant stand))
>>>
arr
(\ (legsAnim,
(angle, enemySighted, ev1, ox, oy, oz, targetAngle, yVel))
->
((angle, enemySighted, ev1, legsAnim, ox, oy, oz, targetAngle,
yVel),
angle)))))
>>>
loop
(arr
(\ ((angle, enemySighted, ev1, legsAnim, ox, oy, oz, targetAngle,
yVel),
targetPitch)
->
((enemySighted, ox, oy, oz, targetPitch),
(angle, enemySighted, ev1, legsAnim, ox, oy, oz, targetAngle,
yVel)))
>>>
(first
(arr
(\ (enemySighted, ox, oy, oz, targetPitch) ->
if isEvent enemySighted then getVertAngle
((ox, oy, oz),
vectorAdd
(cpos
(oldCam (snd (head (fromEvent enemySighted)))))
(0, - 5, 0)) else targetPitch)
>>> (iPre 0 <<< identity))
>>>
arr
(\ (targetPitch,
(angle, enemySighted, ev1, legsAnim, ox, oy, oz, targetAngle,
yVel))
->
((angle, enemySighted, ev1, legsAnim, ox, oy, oz, targetAngle,
targetPitch, yVel),
targetPitch)))))
>>>
loop
(arr
(\ ((angle, enemySighted, ev1, legsAnim, ox, oy, oz, targetAngle,
targetPitch, yVel),
ptch)
->
let angularVP
= if abs (ptch - targetPitch) > 2 then (if targetPitch < ptch then (- 90) else 90) else targetPitch - ptch
in
(angularVP,
(angle, enemySighted, ev1, legsAnim, ox, oy, oz, targetAngle,
targetPitch, yVel)))
>>>
(first ((0 +) ^<< integral) >>>
arr
(\ (ptch,
(angle, enemySighted, ev1, legsAnim, ox, oy, oz, targetAngle,
targetPitch, yVel))
->
((angle, enemySighted, ev1, legsAnim, ox, oy, oz, ptch,
targetAngle, targetPitch, yVel),
ptch)))))
>>>
arr
(\ (angle, enemySighted, ev1, legsAnim, ox, oy, oz, ptch,
targetAngle, targetPitch, yVel)
->
(ev1,
(angle, enemySighted, legsAnim, ox, oy, oz, ptch, targetAngle,
targetPitch, yVel))))
>>>
(first (arr isEvent >>> (iPre noEvent <<< edge))
>>>
arr
(\ (attack,
(angle, enemySighted, legsAnim, ox, oy, oz, ptch, targetAngle,
targetPitch, yVel))
->
((angle, enemySighted, ptch, targetAngle, targetPitch),
(angle, attack, legsAnim, ox, oy, oz, ptch, yVel))))
>>>
(first
(arr
(\ (angle, enemySighted, ptch, targetAngle, targetPitch) ->
if
(abs (ptch - targetPitch) < 6) && (abs (angle - targetAngle) < 6)
&& isEvent enemySighted then attack1 else stand)
>>> (iPre stand <<< identity))
>>>
arr
(\ (torsoAnim, (angle, attack, legsAnim, ox, oy, oz, ptch, yVel))
->
((ox, oy + yVel, oz), (ox, oy, oz), angle, ptch, attack,
(torsoAnim, legsAnim))))
followWayPoints ::
Vec3 ->
[Vec3] ->
SF (ObjInput, Event (), Event ())
(Vec3, Vec3, Double, Double, Event (), (Int, Int))
followWayPoints (x, y, z) waypoints
= arr
(\ (oi, ev1, ev2) ->
let gi = oiGameInput oi in
let clippedPos = oiCollisionPos oi in
let grounded = oiOnLand oi in
(clippedPos, (ev1, ev2, gi, grounded, oi)))
>>>
(first (iPre (x, y, z) <<< identity) >>>
arr
(\ ((ox, oy, oz), (ev1, ev2, gi, grounded, oi)) ->
(gi, (ev1, ev2, gi, grounded, oi, ox, oy, oz))))
>>>
(first getT >>>
arr
(\ (_, (ev1, ev2, gi, grounded, oi, ox, oy, oz)) ->
(gi, (ev1, ev2, gi, grounded, oi, ox, oy, oz))))
>>>
(first getDt >>>
arr
(\ (dt, (ev1, ev2, gi, grounded, oi, ox, oy, oz)) ->
((dt, gi, grounded), (dt, ev1, ev2, oi, ox, oy, oz))))
>>>
(first
(arr (\ (dt, gi, grounded) -> (grounded, gi, dt)) >>>
(iPre 0 <<< falling))
>>>
loop
(arr
(\ ((yVel, (dt, ev1, ev2, oi, ox, oy, oz)), wpl) ->
(wpl, (dt, ev1, ev2, oi, ox, oy, oz, yVel)))
>>>
(first (iPre (cycle waypoints) <<< identity) >>>
arr
(\ (wps, (dt, ev1, ev2, oi, ox, oy, oz, yVel)) ->
let [wp1, wp2] = take 2 wps in
let (pastWp, (dx, _, dz)) = stepdist wp1 wp2 (ox, oy, oz) 100 dt
in
(pastWp,
(dx, dz, ev1, ev2, oi, ox, oy, oz, pastWp, wp2, wps, yVel))))
>>>
(first edge >>>
arr
(\ (pastEv,
(dx, dz, ev1, ev2, oi, ox, oy, oz, pastWp, wp2, wps, yVel))
->
let angle = getAngle ((ox, oy, oz), (ox + dx, oy + yVel, oz + dz))
in
let newPos = (ox + dx, oy + yVel, oz + dz) in
((angle, ev1, ev2, newPos, oi, pastEv, wp2),
(angle, newPos, ox, oy, oz, pastWp, wps))))
>>>
(first
(arr
(\ (angle, ev1, ev2, newPos, oi, pastEv, wp2) ->
((oi, ev1, ev2),
pastEv `tag` turnToNextWp angle (getAngle (newPos, wp2))))
>>>
rSwitch
(constant (True, False, getAngle ((x, y, z), head waypoints))))
>>>
arr
(\ ((notturning, largeEnough, turnAngle),
(angle, newPos, ox, oy, oz, pastWp, wps))
->
let wpl
= if pastWp && (not largeEnough || notturning) then tail wps else wps
in
((angle, largeEnough, newPos, notturning, ox, oy, oz, turnAngle),
wpl)))))
>>>
arr
(\ (angle, largeEnough, newPos, notturning, ox, oy, oz, turnAngle)
->
let holdAngle
| not largeEnough = angle
| notturning = angle
| otherwise = turnAngle
in
let legAnim
| not largeEnough = walk
| notturning = walk
| otherwise = turn
in
(newPos, (ox, oy, oz), holdAngle, 0, noEvent, (stand, legAnim)))
turnToNextWp ::
Double ->
Double -> SF (ObjInput, Event (), Event ()) (Bool, Bool, Double)
turnToNextWp currentangle nextAngle
= ((arr
(\ (_, _, lev) ->
let targetAngle
= if
abs (currentangle - nextAngle) <
abs (currentangle - (nextAngle + 360)) then nextAngle else nextAngle + 360
in (lev, targetAngle))
>>>
loop
(arr
(\ ((lev, targetAngle), angle) ->
let angularV
= if abs (angle - targetAngle) > 3 then (if angle < targetAngle then 360 else (- 360)) else targetAngle - angle
in (angularV, (lev, targetAngle)))
>>>
(first ((currentangle +) ^<< integral) >>>
arr
(\ (angle, (lev, targetAngle)) ->
((angle, lev, targetAngle), angle)))))
>>>
arr
(\ (angle, lev, targetAngle) ->
let legState
= if abs (angle - targetAngle) < 3 then idleLegs else turn
in ((legState, lev), (angle, targetAngle))))
>>>
(first
(arr (\ (legState, lev) -> (legState == idleLegs && isEvent lev))
>>> (iPre noEvent <<< edge))
>>>
first
(arr (\ switch2idle -> ((), switch2idle `tag` constant True)) >>>
rSwitch (constant False)))
>>>
arr
(\ (ret, (angle, targetAngle)) ->
(ret, abs (currentangle - targetAngle) > 30, angle))
stepdist ::
Vec3 -> Vec3 -> Vec3 -> Double -> Double -> (Bool, Vec3)
stepdist (wx1, _, wz1) (_, _, _) (x, _, z) vel dt
= let (dx, _, dz) = normalise $ vectorSub (wx1, 0, wz1) (x, 0, z)
distance = sqrt (((x - wx1) * (x - wx1)) + ((z - wz1) * (z - wz1)))
remvel = distance * (distance / (vel * dt))
in
if distance > (vel * dt) then (False, (dx * vel * dt, 0, dz * vel * dt)) else (True, (dx * remvel, 0, dz * remvel))
playDead ::
Vec3 ->
Double ->
SF (ObjInput, Event (), Event ())
(Vec3, Vec3, Double, Double, Event (), (Int, Int))
playDead start angle
= arr (\ (_, ev1, _) -> ev1) >>>
(notYet >>> arr (\ ev -> ((), ev `tag` constant dead1))) >>>
(drSwitch (constant death1) >>>
arr
(\ death -> (start, start, angle, 0, noEvent, (death, death))))
getAngle :: (Vec3, Vec3) -> Double
getAngle ((x, _, z), (vx, _, vz))
= let angle
= acos $
dotProd (normalise $ vectorSub (vx, 0, vz) (x, 0, z)) (1, 0, 0)
in
if vz > z then 360 - (angle * 180 / pi) else angle * 180 / pi
getVertAngle :: (Vec3, Vec3) -> Double
getVertAngle ((x, y, z), (vx, vy, vz))
= let angle1
= acos $
dotProd (normalise $ vectorSub (vx, vy, vz) (x, y, z)) (0, 1, 0)
in ((angle1 * 180 / pi) - 90)
updateAnimSF :: AnimState -> SF (Double, Int) (Event (), AnimState)
updateAnimSF iAnim
= loop
(arr
(\ ((tme, animIndex), anim2) ->
((anim2, animIndex, tme), animIndex))
>>>
(first
(arr (\ (anim2, animIndex, tme) -> (animIndex, tme, anim2)) >>>
(iPre (False, iAnim) <<< arr updateAnim))
>>>
arr
(\ ((hasLooped, anim2), animIndex) ->
((anim2, animIndex, hasLooped), anim2))))
>>>
arr
(\ (anim2, animIndex, hasLooped) ->
(if hasLooped then (if animIndex == dead1 then (noEvent, anim2) else (Event (), anim2)) else (noEvent, anim2)))
moves :: SF (Double, Camera) Camera
moves
= arr
(\ (speed, cam) ->
let (x, y, z) = cpos cam
(vpx, vpy, vpz) = viewPos cam
strafevec
= normalise
(crossProd (vectorSub (viewPos cam) (cpos cam)) (upVec cam))
(vx, _, vz) = normalise (crossProd (upVec cam) strafevec)
newx = (vx * speed)
newz = (vz * speed)
newvx = (vx * speed)
newvz = (vz * speed)
in
Camera{cpos = (x + newx, y, z + newz),
viewPos = (vpx + newvx, vpy, vpz + newvz), upVec = upVec cam})
strafes :: SF (Double, Camera) Camera
strafes
= arr
(\ (speed, cam) ->
let (sx, _, sz)
= normalise
(crossProd (vectorSub (viewPos cam) (cpos cam)) (upVec cam))
(x, y, z) = cpos cam
(vx, vy, vz) = viewPos cam
newx = (sx * speed)
newz = (sz * speed)
newvx = (sx * speed)
newvz = (sz * speed)
in
Camera{cpos = (x + newx, y, z + newz),
viewPos = (vx + newvx, vy, vz + newvz), upVec = upVec cam})
movementKS :: Double -> SF GameInput Double
movementKS speed
= keyStat >>>
loop
(arr (uncurry nextSpeed) >>>
((iPre 0 <<< identity) >>> arr (\ v -> (v, v))))
where nextSpeed key v
| key == Event ('w', True) = speed
| key == Event ('s', True) = - speed
| key == Event ('w', False) || key == Event ('s', False) = 0
| otherwise = v
strafeKS :: Double -> SF GameInput Double
strafeKS speed
= keyStat >>>
loop
(arr (uncurry nextSpeed) >>>
((iPre 0 <<< identity) >>> arr (\ v -> (v, v))))
where nextSpeed key v
| key == Event ('d', True) = speed
| key == Event ('a', True) = - speed
| key == Event ('d', False) || key == Event ('a', False) = 0
| otherwise = v
fallingp :: SF (Bool, GameInput) Double
fallingp
= arr (\ (lnd, gi) -> (gi, lnd)) >>>
(first keyStat >>> arr (\ (key, lnd) -> (key, (key, lnd)))) >>>
(first (arr (\ key -> key == Event ('e', True)) >>> arr jump2Vel)
>>> arr (\ (_, (key, lnd)) -> ((key, lnd), (key, lnd))))
>>>
(first
(arr (\ (key, lnd) -> key == Event ('e', True) && lnd)
>>> arr bool2Ev)
>>> arr (\ (jumping, (key, lnd)) -> (lnd, (jumping, key, lnd))))
>>>
((first (arr (== True) >>> edge) >>>
loop
(arr
(\ ((landed, (jumping, key, lnd)), middleOfJump) ->
((key, lnd, middleOfJump), (jumping, lnd, landed)))
>>>
(first
(arr
(\ (key, lnd, middleOfJump) ->
(not middleOfJump && key == Event ('e', True) && lnd) || (not lnd && middleOfJump))
>>> (iPre False <<< identity))
>>>
arr
(\ (middleOfJump, (jumping, lnd, landed)) ->
((jumping, lnd, landed, middleOfJump), middleOfJump)))))
>>>
arr
(\ (jumping, lnd, landed, middleOfJump) ->
((lnd, middleOfJump), (jumping, landed))))
>>>
(first
(arr
(\ (lnd, middleOfJump) ->
(not lnd && not middleOfJump))
>>> edge)
>>>
arr
(\ (notlanded, (jumping, landed)) ->
((),
(jumping `tag` falling' (- 200 :: Double) (40 :: Double)) `lMerge`
(landed `tag` constant (- 5.0e-2))
`lMerge`
(notlanded `tag` falling' (- 200 :: Double) (0 :: Double)))))
>>> drSwitch (falling' (- 200 :: Double) (0 :: Double))
falling' :: Double -> Double -> SF () Double
falling' grav int
= arr (\ () -> grav) >>> (integral >>> arr (+ int)) >>> integral
bool2Ev :: Bool -> Event ()
bool2Ev b
| b = Event ()
| otherwise = noEvent
jump2Vel :: Bool -> Double
jump2Vel b
| b = 40
| otherwise = 0
| pushkinma/frag | src/ObjectBehavior.hs | gpl-2.0 | 61,281 | 1 | 40 | 34,097 | 16,546 | 9,728 | 6,818 | 1,178 | 12 |
-- Author: Maciej Bendkowski
-- <maciej.bendkowski@tcs.uj.edu.pl>
module BZBW where
import Definitions
-- Translates the given Black-White tree
-- to a corresponding Zigzag free tree.
bwToBz :: BWTree -> BZTree
bwToBz (Black Leaf Leaf) = Node BZLeaf BZLeaf
bwToBz (Black t @ (Black _ _) Leaf) = Node BZLeaf (bwToBz t)
bwToBz (Black t @ (White _ _) Leaf) = bwToBz t
bwToBz (White Leaf Leaf) = Node (Node BZLeaf BZLeaf) BZLeaf
bwToBz (White t @ (White _ _) Leaf) = Node (bwToBz t) BZLeaf
bwToBz (White Leaf t @ (Black _ _)) = Node (Node BZLeaf BZLeaf) (bwToBz t)
bwToBz (White t t') = Node (bwToBz t) (bwToBz t')
-- Translates the given Zigzag free tree to a
-- corresponding black rooted Black-White tree.
bzToBwB :: BZTree -> BWTree
bzToBwB (Node BZLeaf BZLeaf) = Black Leaf Leaf
bzToBwB (Node BZLeaf t @ (Node _ _)) = Black (bzToBwB t) Leaf
bzToBwB (Node (Node BZLeaf BZLeaf) BZLeaf) = bzToBwB' Leaf Leaf
bzToBwB (Node t BZLeaf) = bzToBwB' (bzToBwW t) Leaf
bzToBwB (Node (Node BZLeaf BZLeaf) t') = bzToBwB' Leaf (bzToBwB t')
bzToBwB (Node t t') = bzToBwB' (bzToBwW t) (bzToBwB t')
-- Helper function.
bzToBwB' :: BWTree -> BWTree -> BWTree
bzToBwB' x y = Black (White x y) Leaf
-- Translates the given Zigzag free tree to a
-- corresponding white rooted Black-White tree.
bzToBwW :: BZTree -> BWTree
bzToBwW (Node (Node BZLeaf BZLeaf) BZLeaf) = White Leaf Leaf
bzToBwW (Node (Node BZLeaf BZLeaf) t) = White Leaf (bzToBwB t)
bzToBwW (Node t BZLeaf) = White (bzToBwW t) Leaf
bzToBwW (Node t t') = White (bzToBwW t) (bzToBwB t')
| maciej-bendkowski/natural-counting-of-lambda-terms | src/BZBW.hs | gpl-2.0 | 1,658 | 5 | 10 | 400 | 631 | 312 | 319 | 24 | 1 |
module Flowskell.Viewer where
import Control.Monad (when)
import Graphics.UI.GLUT hiding (Bool, Float)
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import System.Directory (getModificationTime, doesFileExist)
import Flowskell.State
import Flowskell.Interpreter (initSchemeEnv, initPrimitives)
import Flowskell.InputActions (
actionReloadSource, motionHandler, mouseHandler,
keyboardMouseHandler)
import Flowskell.Display (
initDisplay, reshapeHandler, displayHandler)
viewer = do
(_, [filename]) <- getArgsAndInitialize
state <- makeState filename
initDisplay state
extraPrimitives <- initPrimitives state
let initFunc' = initSchemeEnv extraPrimitives
initFunc state $= Just initFunc'
env <- initFunc' filename
environment state $= Just env
idleCallback $= Just (idle state)
-- Flowskell.Display
displayCallback $= displayHandler state
reshapeCallback $= Just (reshapeHandler state)
-- Flowskell.InputActions
motionCallback $= Just (motionHandler state)
mouseCallback $= Just (mouseHandler state)
keyboardMouseCallback $= Just (keyboardMouseHandler state)
-- GLUT main loop
mainLoop
-- |Idle function. Check modifcation date of the current source file
-- and reload the environment when it has changed.
idle state = do
now <- getCurrentTime
lastCheckTime <- get $ lastReloadCheck state
when (diffUTCTime now lastCheckTime > 0.5) $ do
Just env <- get $ environment state
doesFileExist (source state) >>= \x -> when x $ do
modTime <- getModificationTime (source state)
lastModTime <- get $ lastSourceModification state
when (lastModTime < modTime) $ actionReloadSource state
lastSourceModification state $= modTime
lastReloadCheck state $= now
lastFPSTime <- get $ lastFrameCounterTime state
when (diffUTCTime now lastFPSTime > 0.75) $ do
cnt <- get $ frameCounter state
framesPerSecond state $= (fromIntegral cnt / realToFrac (diffUTCTime now lastFPSTime))
frameCounter state $= 0
lastFrameCounterTime state $= now
postRedisplay Nothing
| lordi/flowskell | src/Flowskell/Viewer.hs | gpl-2.0 | 2,070 | 0 | 18 | 362 | 577 | 275 | 302 | 46 | 1 |
#!runghc
import Control.Concurrent
import System.Environment
import GHC.IO.Handle
import GHC.IO.Handle.FD
main = do
[t]<-getArgs
getContents>>=mapM_ (\l->(putStrLn l>>hFlush stdout>>threadDelay (read t*1000))).lines
| ducis/multitouch-visualizer | slow_print.hs | gpl-2.0 | 218 | 0 | 17 | 21 | 90 | 48 | 42 | 7 | 1 |
module Experimentation.P14 (p14_test) where
import Test.HUnit
import Data.List
dupli_rec :: [a] -> [a]
dupli_rec [] = []
dupli_rec (a:as) = (a : []) ++ (a : []) ++ dupli_rec as
dupli_rec_2 :: [a] -> [a]
dupli_rec_2 [] = []
dupli_rec_2 (a:as) = doubl a ++ dupli_rec_2 as
where
doubl a = a : (a : [])
{- wrong -}
dupli_rec_3 :: [a] -> [a]
dupli_rec_3 [] = []
{-dupli_rec_3 lst = [ x | x <- (lst ++ lst) ] -}
dupli_rec_3 lst = concat $ [ y : [y] | y <- lst ]
dupli_fold l = foldl (\acc b -> acc ++ [b,b]) [] l
dupli_map l = fst ( (mapAccumL (\acc b -> (acc ++ [b,b],b)) [] l) )
-- Tests
test_dupli_rec = TestCase $ do
assertEqual "for (dupli_rec [1..3])" [1,1,2,2,3,3] (dupli_rec [1..3])
assertEqual "for (dupli_rec [1])" [1,1] (dupli_rec [1])
assertEqual "for (dupli_rec [])" 0 (length (dupli_rec []))
assertEqual "for (dupli_rec 'abc')" ['a','a','b','b','c','c'] (dupli_rec "abc")
test_dupli_rec_2 = TestCase $ do
assertEqual "for (dupli_rec [1..3])" [1,1,2,2,3,3] (dupli_rec_2 [1..3])
assertEqual "for (dupli_rec [1])" [1,1] (dupli_rec_2 [1])
assertEqual "for (dupli_rec [])" 0 (length (dupli_rec_2 []))
assertEqual "for (dupli_rec 'abc')" ['a','a','b','b','c','c'] (dupli_rec_2 "abc")
test_dupli_rec_3 = TestCase $ do
assertEqual "for (dupli_rec [1..3])" [1,1,2,2,3,3] (dupli_rec_3 [1..3])
assertEqual "for (dupli_rec [1])" [1,1] (dupli_rec_3 [1])
assertEqual "for (dupli_rec [])" 0 (length (dupli_rec_3 []))
assertEqual "for (dupli_rec 'abc')" ['a','a','b','b','c','c'] (dupli_rec_3 "abc")
test_dupli_fold = TestCase $ do
assertEqual "for (dupli_fold [1,2,3])" [1,1,2,2,3,3] (dupli_fold [1,2,3])
test_dupli_map = TestCase $ do
assertEqual "for (dupli_map [1,2,3])" [1,1,2,2,3,3] (dupli_map [1,2,3])
p14_test = do
runTestTT p14_tests
p14_tests = TestList [
TestLabel "test_dupli_rec" test_dupli_rec,
TestLabel "test_dupli_rec_2" test_dupli_rec_2,
TestLabel "test_dupli_rec_3" test_dupli_rec_3,
TestLabel "test_dupli_fold" test_dupli_fold,
TestLabel "test_dupli_map" test_dupli_map
]
| adarqui/99problems-hs | Experimentation/P14.hs | gpl-3.0 | 2,025 | 0 | 13 | 316 | 872 | 472 | 400 | 42 | 1 |
module LipidHaskell where
import Lipid.Blocks
import Lipid.FattyAcid
import Lipid.Glycerolipid
| Michaelt293/Lipid-Haskell | src/LipidHaskell.hs | gpl-3.0 | 96 | 0 | 4 | 10 | 19 | 12 | 7 | 4 | 0 |
{-# LANGUAGE StandaloneDeriving #-}
{-|
A simple 'Amount' is some quantity of money, shares, or anything else.
It has a (possibly null) 'Commodity' and a numeric quantity:
@
$1
£-50
EUR 3.44
GOOG 500
1.5h
90 apples
0
@
It may also have an assigned 'Price', representing this amount's per-unit
or total cost in a different commodity. If present, this is rendered like
so:
@
EUR 2 \@ $1.50 (unit price)
EUR 2 \@\@ $3 (total price)
@
A 'MixedAmount' is zero or more simple amounts, so can represent multiple
commodities; this is the type most often used:
@
0
$50 + EUR 3
16h + $13.55 + AAPL 500 + 6 oranges
@
When a mixed amount has been \"normalised\", it has no more than one amount
in each commodity and no zero amounts; or it has just a single zero amount
and no others.
Limited arithmetic with simple and mixed amounts is supported, best used
with similar amounts since it mostly ignores assigned prices and commodity
exchange rates.
-}
module Hledger.Data.Amount (
-- * Amount
nullamt,
amountWithCommodity,
canonicaliseAmountCommodity,
setAmountPrecision,
-- ** arithmetic
costOfAmount,
divideAmount,
-- ** rendering
showAmount,
showAmountDebug,
showAmountWithoutPrice,
maxprecision,
maxprecisionwithpoint,
-- * MixedAmount
nullmixedamt,
missingamt,
amounts,
normaliseMixedAmountPreservingFirstPrice,
canonicaliseMixedAmountCommodity,
mixedAmountWithCommodity,
setMixedAmountPrecision,
-- ** arithmetic
costOfMixedAmount,
divideMixedAmount,
isNegativeMixedAmount,
isZeroMixedAmount,
isReallyZeroMixedAmountCost,
-- ** rendering
showMixedAmount,
showMixedAmountDebug,
showMixedAmountWithoutPrice,
showMixedAmountWithPrecision,
-- * misc.
tests_Hledger_Data_Amount
) where
import Data.Char (isDigit)
import Data.List
import Data.Map (findWithDefault)
import Test.HUnit
import Text.Printf
import qualified Data.Map as Map
import Hledger.Data.Types
import Hledger.Data.Commodity
import Hledger.Utils
deriving instance Show HistoricalPrice
-------------------------------------------------------------------------------
-- Amount
instance Show Amount where show = showAmount
instance Num Amount where
abs (Amount c q p) = Amount c (abs q) p
signum (Amount c q p) = Amount c (signum q) p
fromInteger i = Amount (comm "") (fromInteger i) Nothing
negate a@Amount{quantity=q} = a{quantity=(-q)}
(+) = similarAmountsOp (+)
(-) = similarAmountsOp (-)
(*) = similarAmountsOp (*)
-- | The empty simple amount.
nullamt :: Amount
nullamt = Amount unknown 0 Nothing
-- | Apply a binary arithmetic operator to two amounts, ignoring and
-- discarding any assigned prices, and converting the first to the
-- commodity of the second in a simplistic way (1-1 exchange rate).
-- The highest precision of either amount is preserved in the result.
similarAmountsOp :: (Double -> Double -> Double) -> Amount -> Amount -> Amount
similarAmountsOp op a@(Amount Commodity{precision=ap} _ _) (Amount bc@Commodity{precision=bp} bq _) =
Amount bc{precision=max ap bp} (quantity (amountWithCommodity bc a) `op` bq) Nothing
-- | Convert an amount to the specified commodity, ignoring and discarding
-- any assigned prices and assuming an exchange rate of 1.
amountWithCommodity :: Commodity -> Amount -> Amount
amountWithCommodity c (Amount _ q _) = Amount c q Nothing
-- | Convert an amount to the commodity of its assigned price, if any. Notes:
--
-- - price amounts must be MixedAmounts with exactly one component Amount (or there will be a runtime error)
--
-- - price amounts should be positive, though this is not currently enforced
costOfAmount :: Amount -> Amount
costOfAmount a@(Amount _ q price) =
case price of
Nothing -> a
Just (UnitPrice (Mixed [Amount pc pq Nothing])) -> Amount pc (pq*q) Nothing
Just (TotalPrice (Mixed [Amount pc pq Nothing])) -> Amount pc (pq*signum q) Nothing
_ -> error' "costOfAmount: Malformed price encountered, programmer error"
-- | Divide an amount's quantity by a constant.
divideAmount :: Amount -> Double -> Amount
divideAmount a@Amount{quantity=q} d = a{quantity=q/d}
-- | Is this amount negative ? The price is ignored.
isNegativeAmount :: Amount -> Bool
isNegativeAmount Amount{quantity=q} = q < 0
-- | Does this amount appear to be zero when displayed with its given precision ?
isZeroAmount :: Amount -> Bool
isZeroAmount = null . filter (`elem` "123456789") . showAmountWithoutPriceOrCommodity
-- | Is this amount "really" zero, regardless of the display precision ?
-- Since we are using floating point, for now just test to some high precision.
isReallyZeroAmount :: Amount -> Bool
isReallyZeroAmount = null . filter (`elem` "123456789") . printf ("%."++show zeroprecision++"f") . quantity
where zeroprecision = 8
-- | Get the string representation of an amount, based on its commodity's
-- display settings except using the specified precision.
showAmountWithPrecision :: Int -> Amount -> String
showAmountWithPrecision p = showAmount . setAmountPrecision p
-- | Set the display precision in the amount's commodity.
setAmountPrecision :: Int -> Amount -> Amount
setAmountPrecision p a@Amount{commodity=c} = a{commodity=c{precision=p}}
-- | Get the unambiguous string representation of an amount, for debugging.
showAmountDebug :: Amount -> String
showAmountDebug (Amount c q pri) = printf "Amount {commodity = %s, quantity = %s, price = %s}"
(show c) (show q) (maybe "" showPriceDebug pri)
-- | Get the string representation of an amount, without any \@ price.
showAmountWithoutPrice :: Amount -> String
showAmountWithoutPrice a = showAmount a{price=Nothing}
-- | Get the string representation of an amount, without any price or commodity symbol.
showAmountWithoutPriceOrCommodity :: Amount -> String
showAmountWithoutPriceOrCommodity a@Amount{commodity=c} = showAmount a{commodity=c{symbol=""}, price=Nothing}
showPrice :: Price -> String
showPrice (UnitPrice pa) = " @ " ++ showMixedAmount pa
showPrice (TotalPrice pa) = " @@ " ++ showMixedAmount pa
showPriceDebug :: Price -> String
showPriceDebug (UnitPrice pa) = " @ " ++ showMixedAmountDebug pa
showPriceDebug (TotalPrice pa) = " @@ " ++ showMixedAmountDebug pa
-- | Get the string representation of an amount, based on its commodity's
-- display settings. String representations equivalent to zero are
-- converted to just \"0\".
showAmount :: Amount -> String
showAmount (Amount (Commodity {symbol="AUTO"}) _ _) = "" -- can appear in an error message
showAmount a@(Amount (Commodity {symbol=sym,side=side,spaced=spaced}) _ pri) =
case side of
L -> printf "%s%s%s%s" sym' space quantity' price
R -> printf "%s%s%s%s" quantity' space sym' price
where
quantity = showamountquantity a
displayingzero = null $ filter (`elem` "123456789") $ quantity
(quantity',sym') | displayingzero = ("0","")
| otherwise = (quantity,quoteCommoditySymbolIfNeeded sym)
space = if (not (null sym') && spaced) then " " else ""
price = maybe "" showPrice pri
-- | Get the string representation of the number part of of an amount,
-- using the display settings from its commodity.
showamountquantity :: Amount -> String
showamountquantity (Amount (Commodity {decimalpoint=d,precision=p,separator=s,separatorpositions=spos}) q _) =
punctuatenumber d s spos $ qstr
where
-- isint n = fromIntegral (round n) == n
qstr -- p == maxprecision && isint q = printf "%d" (round q::Integer)
| p == maxprecisionwithpoint = printf "%f" q
| p == maxprecision = chopdotzero $ printf "%f" q
| otherwise = printf ("%."++show p++"f") q
-- | Replace a number string's decimal point with the specified character,
-- and add the specified digit group separators.
punctuatenumber :: Char -> Char -> [Int] -> String -> String
punctuatenumber dec sep grps str = sign ++ reverse (addseps sep (extend grps) (reverse int)) ++ frac''
where
(sign,num) = break isDigit str
(int,frac) = break (=='.') num
frac' = dropWhile (=='.') frac
frac'' | null frac' = ""
| otherwise = dec:frac'
extend [] = []
extend gs = init gs ++ repeat (last gs)
addseps _ [] str = str
addseps sep (g:gs) str
| length str <= g = str
| otherwise = let (s,rest) = splitAt g str
in s ++ [sep] ++ addseps sep gs rest
chopdotzero str = reverse $ case reverse str of
'0':'.':s -> s
s -> s
-- | For rendering: a special precision value which means show all available digits.
maxprecision :: Int
maxprecision = 999998
-- | For rendering: a special precision value which forces display of a decimal point.
maxprecisionwithpoint :: Int
maxprecisionwithpoint = 999999
-- | Replace an amount's commodity with the canonicalised version from
-- the provided commodity map.
canonicaliseAmountCommodity :: Maybe (Map.Map String Commodity) -> Amount -> Amount
canonicaliseAmountCommodity Nothing = id
canonicaliseAmountCommodity (Just canonicalcommoditymap) = fixamount
where
-- like journalCanonicaliseAmounts
fixamount a@Amount{commodity=c} = a{commodity=fixcommodity c}
fixcommodity c@Commodity{symbol=s} = findWithDefault c s canonicalcommoditymap
-------------------------------------------------------------------------------
-- MixedAmount
instance Show MixedAmount where show = showMixedAmount
instance Num MixedAmount where
fromInteger i = Mixed [Amount (comm "") (fromInteger i) Nothing]
negate (Mixed as) = Mixed $ map negate as
(+) (Mixed as) (Mixed bs) = normaliseMixedAmountPreservingPrices $ Mixed $ as ++ bs
(*) = error' "programming error, mixed amounts do not support multiplication"
abs = error' "programming error, mixed amounts do not support abs"
signum = error' "programming error, mixed amounts do not support signum"
-- | The empty mixed amount.
nullmixedamt :: MixedAmount
nullmixedamt = Mixed []
-- | A temporary value for parsed transactions which had no amount specified.
missingamt :: MixedAmount
missingamt = Mixed [Amount unknown{symbol="AUTO"} 0 Nothing]
-- | Simplify a mixed amount's component amounts: combine amounts with
-- the same commodity and price. Also remove any zero amounts and
-- replace an empty amount list with a single zero amount.
normaliseMixedAmountPreservingPrices :: MixedAmount -> MixedAmount
normaliseMixedAmountPreservingPrices (Mixed as) = Mixed as''
where
as'' = if null nonzeros then [nullamt] else nonzeros
(_,nonzeros) = partition (\a -> isReallyZeroAmount a && Mixed [a] /= missingamt) as'
as' = map sumAmountsUsingFirstPrice $ group $ sort as
sort = sortBy (\a1 a2 -> compare (sym a1,price a1) (sym a2,price a2))
group = groupBy (\a1 a2 -> sym a1 == sym a2 && price a1 == price a2)
sym = symbol . commodity
-- | Simplify a mixed amount's component amounts: combine amounts with
-- the same commodity, using the first amount's price for subsequent
-- amounts in each commodity (ie, this function alters the amount and
-- is best used as a rendering helper.). Also remove any zero amounts
-- and replace an empty amount list with a single zero amount.
normaliseMixedAmountPreservingFirstPrice :: MixedAmount -> MixedAmount
normaliseMixedAmountPreservingFirstPrice (Mixed as) = Mixed as''
where
as'' = if null nonzeros then [nullamt] else nonzeros
(_,nonzeros) = partition (\a -> isReallyZeroAmount a && Mixed [a] /= missingamt) as'
as' = map sumAmountsUsingFirstPrice $ group $ sort as
sort = sortBy (\a1 a2 -> compare (sym a1) (sym a2))
group = groupBy (\a1 a2 -> sym a1 == sym a2)
sym = symbol . commodity
-- discardPrice :: Amount -> Amount
-- discardPrice a = a{price=Nothing}
-- discardPrices :: MixedAmount -> MixedAmount
-- discardPrices (Mixed as) = Mixed $ map discardPrice as
sumAmountsUsingFirstPrice [] = nullamt
sumAmountsUsingFirstPrice as = (sum as){price=price $ head as}
-- | Get a mixed amount's component amounts.
amounts :: MixedAmount -> [Amount]
amounts (Mixed as) = as
-- | Convert a mixed amount's component amounts to the commodity of their
-- assigned price, if any.
costOfMixedAmount :: MixedAmount -> MixedAmount
costOfMixedAmount (Mixed as) = Mixed $ map costOfAmount as
-- | Divide a mixed amount's quantities by a constant.
divideMixedAmount :: MixedAmount -> Double -> MixedAmount
divideMixedAmount (Mixed as) d = Mixed $ map (flip divideAmount d) as
-- | Is this mixed amount negative, if it can be normalised to a single commodity ?
isNegativeMixedAmount :: MixedAmount -> Maybe Bool
isNegativeMixedAmount m = case as of [a] -> Just $ isNegativeAmount a
_ -> Nothing
where as = amounts $ normaliseMixedAmountPreservingFirstPrice m
-- | Does this mixed amount appear to be zero when displayed with its given precision ?
isZeroMixedAmount :: MixedAmount -> Bool
isZeroMixedAmount = all isZeroAmount . amounts . normaliseMixedAmountPreservingFirstPrice
-- | Is this mixed amount "really" zero ? See isReallyZeroAmount.
isReallyZeroMixedAmount :: MixedAmount -> Bool
isReallyZeroMixedAmount = all isReallyZeroAmount . amounts . normaliseMixedAmountPreservingFirstPrice
-- | Is this mixed amount "really" zero, after converting to cost
-- commodities where possible ?
isReallyZeroMixedAmountCost :: MixedAmount -> Bool
isReallyZeroMixedAmountCost = isReallyZeroMixedAmount . costOfMixedAmount
-- -- | Convert a mixed amount to the specified commodity, assuming an exchange rate of 1.
mixedAmountWithCommodity :: Commodity -> MixedAmount -> Amount
mixedAmountWithCommodity c (Mixed as) = Amount c total Nothing
where
total = sum $ map (quantity . amountWithCommodity c) as
-- -- | MixedAmount derived Eq instance in Types.hs doesn't know that we
-- -- want $0 = EUR0 = 0. Yet we don't want to drag all this code over there.
-- -- For now, use this when cross-commodity zero equality is important.
-- mixedAmountEquals :: MixedAmount -> MixedAmount -> Bool
-- mixedAmountEquals a b = amounts a' == amounts b' || (isZeroMixedAmount a' && isZeroMixedAmount b')
-- where a' = normaliseMixedAmountPreservingFirstPrice a
-- b' = normaliseMixedAmountPreservingFirstPrice b
-- | Get the string representation of a mixed amount, showing each of
-- its component amounts. NB a mixed amount can have an empty amounts
-- list in which case it shows as \"\".
showMixedAmount :: MixedAmount -> String
showMixedAmount m = vConcatRightAligned $ map show $ amounts $ normaliseMixedAmountPreservingFirstPrice m
-- | Set the display precision in the amount's commodities.
setMixedAmountPrecision :: Int -> MixedAmount -> MixedAmount
setMixedAmountPrecision p (Mixed as) = Mixed $ map (setAmountPrecision p) as
-- | Get the string representation of a mixed amount, showing each of its
-- component amounts with the specified precision, ignoring their
-- commoditys' display precision settings.
showMixedAmountWithPrecision :: Int -> MixedAmount -> String
showMixedAmountWithPrecision p m =
vConcatRightAligned $ map (showAmountWithPrecision p) $ amounts $ normaliseMixedAmountPreservingFirstPrice m
-- | Get an unambiguous string representation of a mixed amount for debugging.
showMixedAmountDebug :: MixedAmount -> String
showMixedAmountDebug m = printf "Mixed [%s]" as
where as = intercalate "\n " $ map showAmountDebug $ amounts $ normaliseMixedAmountPreservingFirstPrice m
-- | Get the string representation of a mixed amount, but without
-- any \@ prices.
showMixedAmountWithoutPrice :: MixedAmount -> String
showMixedAmountWithoutPrice m = concat $ intersperse "\n" $ map showfixedwidth as
where
(Mixed as) = normaliseMixedAmountPreservingFirstPrice $ stripPrices m
stripPrices (Mixed as) = Mixed $ map stripprice as where stripprice a = a{price=Nothing}
width = maximum $ map (length . show) as
showfixedwidth = printf (printf "%%%ds" width) . showAmountWithoutPrice
-- | Replace a mixed amount's commodity with the canonicalised version from
-- the provided commodity map.
canonicaliseMixedAmountCommodity :: Maybe (Map.Map String Commodity) -> MixedAmount -> MixedAmount
canonicaliseMixedAmountCommodity canonicalcommoditymap (Mixed as) = Mixed $ map (canonicaliseAmountCommodity canonicalcommoditymap) as
-------------------------------------------------------------------------------
-- misc
tests_Hledger_Data_Amount = TestList [
-- Amount
"costOfAmount" ~: do
costOfAmount (euros 1) `is` euros 1
costOfAmount (euros 2){price=Just $ UnitPrice $ Mixed [dollars 2]} `is` dollars 4
costOfAmount (euros 1){price=Just $ TotalPrice $ Mixed [dollars 2]} `is` dollars 2
costOfAmount (euros (-1)){price=Just $ TotalPrice $ Mixed [dollars 2]} `is` dollars (-2)
,"isZeroAmount" ~: do
assertBool "" $ isZeroAmount $ Amount unknown 0 Nothing
assertBool "" $ isZeroAmount $ dollars 0
,"negating amounts" ~: do
let a = dollars 1
negate a `is` a{quantity=(-1)}
let b = (dollars 1){price=Just $ UnitPrice $ Mixed [euros 2]}
negate b `is` b{quantity=(-1)}
,"adding amounts" ~: do
let a1 = dollars 1.23
let a2 = dollars (-1.23)
let a3 = dollars (-1.23)
(a1 + a2) `is` Amount (comm "$") 0 Nothing
(a1 + a3) `is` Amount (comm "$") 0 Nothing
(a2 + a3) `is` Amount (comm "$") (-2.46) Nothing
(a3 + a3) `is` Amount (comm "$") (-2.46) Nothing
sum [a1,a2,a3,-a3] `is` Amount (comm "$") 0 Nothing
-- highest precision is preserved
let ap1 = (dollars 1){commodity=dollar{precision=1}}
ap3 = (dollars 1){commodity=dollar{precision=3}}
(sum [ap1,ap3]) `is` ap3{quantity=2}
(sum [ap3,ap1]) `is` ap3{quantity=2}
-- adding different commodities assumes conversion rate 1
assertBool "" $ isZeroAmount (a1 - euros 1.23)
,"showAmount" ~: do
showAmount (dollars 0 + pounds 0) `is` "0"
-- MixedAmount
,"normaliseMixedAmountPreservingFirstPrice" ~: do
normaliseMixedAmountPreservingFirstPrice (Mixed []) `is` Mixed [nullamt]
assertBool "" $ isZeroMixedAmount $ normaliseMixedAmountPreservingFirstPrice (Mixed [Amount {commodity=dollar, quantity=10, price=Nothing}
,Amount {commodity=dollar, quantity=10, price=Just (TotalPrice (Mixed [Amount {commodity=euro, quantity=7, price=Nothing}]))}
,Amount {commodity=dollar, quantity=(-10), price=Nothing}
,Amount {commodity=dollar, quantity=(-10), price=Just (TotalPrice (Mixed [Amount {commodity=euro, quantity=7, price=Nothing}]))}
])
,"adding mixed amounts" ~: do
let dollar0 = dollar{precision=0}
(sum $ map (Mixed . (\a -> [a]))
[Amount dollar 1.25 Nothing,
Amount dollar0 (-1) Nothing,
Amount dollar (-0.25) Nothing])
`is` Mixed [Amount unknown 0 Nothing]
,"showMixedAmount" ~: do
showMixedAmount (Mixed [dollars 1]) `is` "$1.00"
showMixedAmount (Mixed [(dollars 1){price=Just $ UnitPrice $ Mixed [euros 2]}]) `is` "$1.00 @ €2.00"
showMixedAmount (Mixed [dollars 0]) `is` "0"
showMixedAmount (Mixed []) `is` "0"
showMixedAmount missingamt `is` ""
,"showMixedAmountWithoutPrice" ~: do
let a = (dollars 1){price=Just $ UnitPrice $ Mixed [euros 2]}
showMixedAmountWithoutPrice (Mixed [a]) `is` "$1.00"
showMixedAmountWithoutPrice (Mixed [a, (-a)]) `is` "0"
]
| Lainepress/hledger | hledger-lib/Hledger/Data/Amount.hs | gpl-3.0 | 19,823 | 28 | 25 | 4,048 | 4,626 | 2,484 | 2,142 | 254 | 4 |
{-# LANGUAGE TemplateHaskell, TypeFamilies, DeriveDataTypeable, TupleSections, OverloadedStrings #-}
import Network.IRC.Bot
import Network.IRC (Message)
import qualified Network.IRC as IRC
import Data.Set as S
import Data.Map as M
import Data.List as L
import Data.Maybe as L (mapMaybe, maybeToList)
import Data.ByteString.Char8 as BSC
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Typeable
import Control.Concurrent
import Control.Monad
import Control.Monad.Trans
import Control.Monad.State.Class
import Control.Monad.Reader.Class
import Data.Monoid
import Network.IRC.Bot.Part.Ping
import Network.IRC.Bot.Part.Channels
import Data.Acid
import Data.Acid.Advanced
import Data.SafeCopy
-------- Settings --------
nickName :: ByteString
nickName = "snowbot"
realName :: ByteString
realName = "Snowdrift bot - development"
botChannel :: ByteString
botChannel = "#snowdrift"
--------------------------
type UserName = ByteString
data TimeSlice = TimeSlice
{ tsJoined :: Set UserName
, tsLeft :: Set UserName
, tsMessages :: [Message]
} deriving (Typeable)
data UserPrefs = UserPrefs { upDoLog :: Bool } deriving (Show, Typeable)
defaultUserPrefs = UserPrefs { upDoLog = False }
data BotState = BotState
{ bsLog :: Map UTCTime TimeSlice
, bsUserPrefs :: Map UserName UserPrefs
, bsMemos :: Map UserName [Memo]
} deriving (Typeable)
data Memo = Memo
{ memoTime :: UTCTime
, memoSender :: UserName
, memoContent :: ByteString
} deriving (Show, Typeable)
$(deriveSafeCopy 0 'base ''UserPrefs)
$(deriveSafeCopy 0 'base ''IRC.Prefix)
$(deriveSafeCopy 0 'base ''Message)
$(deriveSafeCopy 0 'base ''TimeSlice)
$(deriveSafeCopy 0 'base ''BotState)
$(deriveSafeCopy 0 'base ''Memo)
instance Monoid TimeSlice where
mappend a b = TimeSlice
{ tsJoined = tsJoined a `mappend` tsJoined b
, tsLeft = tsLeft a `mappend` tsLeft b
, tsMessages = tsMessages a `mappend` tsMessages b
}
mempty = TimeSlice { tsJoined = mempty, tsLeft = mempty, tsMessages = mempty }
getLog :: Query BotState (Map UTCTime TimeSlice)
getLog = ask >>= return . bsLog
getUserPrefs :: UserName -> Query BotState (Maybe UserPrefs)
getUserPrefs user = ask >>= return . M.lookup user . bsUserPrefs
getAllUserPrefs :: Query BotState (Map UserName UserPrefs)
getAllUserPrefs = ask >>= return . bsUserPrefs
getMemos :: UserName -> Query BotState [Memo]
getMemos user = ask >>= return . join . L.maybeToList . M.lookup user . bsMemos
setDoLog :: UserName -> Bool -> Update BotState ()
setDoLog user do_log = modify $ \ (BotState log prefs memos) -> BotState log (M.insertWith (\ _ prefs -> prefs { upDoLog = do_log }) user (defaultUserPrefs { upDoLog = do_log }) prefs) memos
logMessage :: UTCTime -> Message -> Update BotState ()
logMessage time message = modify $ \ (BotState log users memos) -> BotState (M.insertWith mappend time (TimeSlice S.empty S.empty [message]) log) users memos
logArrival :: UTCTime -> UserName -> Update BotState ()
logArrival time user = modify $ \ (BotState log users memos) -> BotState (M.insertWith mappend time (TimeSlice (S.singleton user) S.empty []) log) (M.insertWith (flip const) user defaultUserPrefs users) memos
logDeparture :: UTCTime -> UserName -> Update BotState ()
logDeparture time user = modify $ \ (BotState log users memos) -> BotState (M.insertWith mappend time (TimeSlice S.empty (S.singleton user) []) log) users memos
recordMemo :: UserName -> UserName -> UTCTime -> ByteString -> Update BotState ()
recordMemo sender recipient time content = modify $ \ (BotState log users memos) ->
let appendMemo :: Memo -> Maybe [Memo] -> Maybe [Memo]
appendMemo m (Just ms) = Just $ m:ms
appendMemo m Nothing = Just [m]
memo = Memo time sender content
memos' = M.insertWith mappend recipient [memo] memos
in BotState log users memos'
clearMemos :: UserName -> Update BotState ()
clearMemos user = modify $ \ (BotState l u _) -> BotState l u M.empty
forgetUser :: UserName -> Update BotState ()
forgetUser user = modify $ \ (BotState log users memos) -> BotState log (M.delete user users) memos
$(makeAcidic ''BotState [ 'getLog, 'getAllUserPrefs, 'getUserPrefs
, 'setDoLog, 'logMessage, 'logArrival, 'logDeparture
, 'forgetUser
, 'getMemos, 'recordMemo, 'clearMemos
])
greeting :: [ByteString]
greeting =
[ BSC.replicate 60 '*'
, "* Welcome to " <> botChannel <> "!"
, "* This bot provides some basic logging, to fill gaps when users are offline."
, "*"
, "* Respond with one of the following commands:"
, "* log"
, "* enable logging"
, "*"
, "* nolog"
, "* disable logging"
, "*"
, BSC.replicate 60 '*'
]
memoToMessageFor :: UserName -> Memo -> Message
memoToMessageFor recipient (Memo time sender content) = IRC.privmsg recipient text
where time' = BSC.pack (show time)
sender' = "<" <> sender <> "> "
text = time' <> ": " <> sender' <> content
notice :: UserName -> ByteString -> Message
notice nick msg = IRC.Message Nothing "NOTICE" [nick,msg]
logPart :: AcidState BotState -> BotPartT IO ()
logPart database = do
time <- lift getCurrentTime
message <- askMessage
let sendMemos :: UserName -> BotPartT IO ()
sendMemos user = do
memos <- query' database $ GetMemos user
sendMessage $ case memos of
[] -> notice user "no memos"
_ -> IRC.privmsg user "some memos were left for you:"
forM_ (L.reverse memos) (sendMessage . memoToMessageFor user)
update' database $ ClearMemos user
departing :: BotPartT IO ()
departing = do
IRC.NickName user _ _ <- maybeZero $ IRC.msg_prefix message
logM Normal $ "NOTING THAT USER DEPARTED: " <> user
update' database $ LogDeparture time user
arriving :: BotPartT IO ()
arriving = do
IRC.NickName user _ _ <- maybeZero $ IRC.msg_prefix message
guard $ user /= nickName
guard $ user /= nickName <> "-devel"
prefs <- query' database $ GetUserPrefs user
log <- query' database GetLog
sendMemos user
case prefs of
Just x | upDoLog x -> do
let messages :: [(UTCTime, Message)]
messages = M.foldlWithKey (\ l t ts -> L.map (t ,) (tsMessages ts) ++ if (S.member user (tsLeft ts)) then [] else l) [] log
renderMessage :: UTCTime -> Message -> Maybe ByteString
renderMessage t (IRC.Message (Just (IRC.NickName name _ _)) "PRIVMSG" (sender:msg:_)) = Just $ BSC.pack (show t) <> ": <" <> name <> "> " <> msg
renderMessage _ _ = Nothing
case messages of
[] -> sendMessage $ notice user "no missed messages"
_ -> let msg_list = "you missed the following while away: " : L.reverse (L.mapMaybe (uncurry renderMessage) messages)
in forM_ msg_list $ sendMessage . IRC.privmsg user
Nothing -> forM_ greeting $ sendMessage . IRC.privmsg user
_ -> return ()
logM Normal $ "NOTING THAT USER ARRIVED: " <> user
update' database $ LogArrival time user
messaged :: BotPartT IO ()
messaged = do
IRC.NickName user _ _ <- maybeZero $ IRC.msg_prefix message
let channel : msg : _ = IRC.msg_params message
when (channel == botChannel) $
update' database (LogMessage time message)
let highlights :: [ByteString] -> ByteString -> Bool
highlights (x:_) nick = L.any (== x) validHighlights
where suffixes = ["", ":", ","]
validHighlights = L.map (nick <>) suffixes
highlights [] _ = False
msg' = BSC.split ' ' msg
isPrivateMessage = channel == nickName
isCommand = (channel == botChannel && msg' `highlights` nickName) || isPrivateMessage
guard isCommand
let command = if isPrivateMessage
then msg'
else L.tail msg'
case command of
["log"] -> do
update' database $ SetDoLog user True
if isPrivateMessage
then sendMessage $ IRC.privmsg user "when you log in, you'll be sent messages since you last left"
else sendMessage $ IRC.privmsg channel (user <> ", when you log in, you'll be sent messages since you last left")
["nolog"] -> do
update' database $ SetDoLog user False
if isPrivateMessage
then sendMessage $ IRC.privmsg user "you will no longer be sent messages on your return"
else sendMessage $ IRC.privmsg channel (user <> ", you will no longer be sent messages on your return")
["forget"] -> update' database $ ForgetUser user
["memos"] -> do
sendMemos user
("memo":recipient:content) | not $ L.null content -> do
let content' = BSC.concat (L.intersperse " " content)
logM Normal $ "Recorded memo from " <> user <> " for " <> recipient <> " with content \"" <> content' <> "\""
update' database $ RecordMemo user recipient time content'
if isPrivateMessage
then sendMessage $ IRC.privmsg user "Memo recorded."
else sendMessage $ IRC.privmsg channel (user <> ", memo recorded.")
-- unknown command
(n:_) | isPrivateMessage -> sendMessage $ IRC.privmsg user "what?"
| otherwise -> sendMessage $ IRC.privmsg channel (user <> ", what?")
-- empty command (happens when you just highlight the bot in the channel)
_ | isPrivateMessage -> sendMessage $ IRC.privmsg user "what?"
| otherwise -> sendMessage $ IRC.privmsg channel (user <> ", what?")
case IRC.msg_command message of
"PRIVMSG" -> messaged
"QUIT" -> departing
"PART" -> departing
"JOIN" -> arriving
cmd -> logM Normal $ BSC.pack (show time) <> ": unrecognized command: " <> cmd
main = do
database <- openLocalState (BotState M.empty M.empty M.empty)
let channels = S.singleton botChannel
config = nullBotConf
{ logger = stdoutLogger Debug
, host = "irc.freenode.net"
, nick = nickName
, user = nullUser
{ username = nickName
, hostname = "localhost"
, servername = "irc.freenode.net"
, realname = realName
}
, channels = channels
, limits = Just (10, 100)
}
(channels_tvar, channels_part) <- initChannelsPart channels
(threads, _) <- simpleBot config [pingPart, logPart database, channels_part]
forever $ do
threadDelay $ 60 * 1000 * 1000
| wolftune/snowbot | Main.hs | gpl-3.0 | 11,922 | 65 | 20 | 3,987 | 3,134 | 1,659 | 1,475 | 218 | 22 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Sandbox (
Sandbox, runSandbox, delay,
-- * Nodes
randomNode, addPeer
) where
import Control.Concurrent ( threadDelay )
import Control.Concurrent.STM
import Control.Monad.RWS.Strict
import System.Random ( StdGen, mkStdGen )
import Logging
import Network
import Node
import Types
newtype Sandbox a = Sandbox { unSandbox :: RWST Environment () State IO a }
deriving ( Applicative, Functor, Monad, MonadReader Environment, MonadState State, MonadIO )
type SandboxNode = Node MsgPassAddress
data Environment = Env
{ envNet :: ! MsgPassNet
}
data State = State
{ stNodes :: ! [SandboxNode]
, stRng :: ! StdGen
}
runSandbox :: Sandbox a -> IO a
runSandbox s = do
net <- mkMsgPassNet
initLogging
let
env = Env net
st = State [] (mkStdGen 23)
fmap fst $ evalRWST (unSandbox s) env st
delay :: Int -> Sandbox ()
delay d = liftIO $ threadDelay d
liftSTM :: STM a -> Sandbox a
liftSTM = liftIO . atomically
randomNode :: Sandbox SandboxNode
randomNode = do
nid <- get >>= \s -> let (i, g') = randomId (stRng s) in put s { stRng = g' } >> return i
node <- liftIO $ mkNode (NodeInfo nid [])
na <- reader envNet >>= liftIO . (mkAddress node)
liftSTM $ modifyTVar' (nodeIdentity node) $ \oid -> oid { nodeAddresses = [na] }
liftIO . putStrLn $ "created node " ++ show nid
return node
addPeer
:: SandboxNode -- ^ the node whose peer list gets the other node added
-> SandboxNode -- ^ the node to announce to the first node
-> Sandbox ()
addPeer n1 n2 = liftIO $ atomically $ do
oid <- readTVar $ nodeIdentity n2
mergeNodeInfo n1 oid
| waldheinz/ads | src/sandbox/Sandbox.hs | gpl-3.0 | 1,730 | 6 | 16 | 440 | 564 | 293 | 271 | 53 | 1 |
module Tests.CheckSpec (spec) where
import Data.Either (isRight)
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Check
import Reduce
import Representation
import Tests.ReprGen
import Tests.Util
spec :: Spec
spec = do
describe "checkTerm" $
modifyMaxDiscardRatio (10 *) $ do
it "reduction of type checked term produces normal form" $ property $ \obj ->
isRight (checkObject obj Star) ==> (nfObject (reduceObject obj))
-- I hate unit tests, but I should at least test this term.
it "\\a : *. \\x : a. x has type @a : *. @x : a. a" $
checkObject (Fun (Just "a") (C Star) (Fun (Just "x") (O (Var "a" 0)) (Var "x" 0))) Star
`shouldBe`
Right (O (Prod (Just "a") (C Star) (Prod (Just "x") (O (Var "a" 0)) (Var "a" 1))))
| lambda-11235/ttyped | test/Tests/CheckSpec.hs | gpl-3.0 | 804 | 0 | 21 | 187 | 284 | 148 | 136 | 20 | 1 |
(,) Int Bool ~ (Int, Bool) | hmemcpy/milewski-ctfp-pdf | src/content/3.2/code/haskell/snippet09.hs | gpl-3.0 | 26 | 2 | 6 | 5 | 22 | 11 | 11 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.SourceRepo.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.SourceRepo.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | The format of the Cloud Pub\/Sub messages.
data PubsubConfigMessageFormat
= MessageFormatUnspecified
-- ^ @MESSAGE_FORMAT_UNSPECIFIED@
-- Unspecified.
| Protobuf
-- ^ @PROTOBUF@
-- The message payload is a serialized protocol buffer of SourceRepoEvent.
| JSON
-- ^ @JSON@
-- The message payload is a JSON string of SourceRepoEvent.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PubsubConfigMessageFormat
instance FromHttpApiData PubsubConfigMessageFormat where
parseQueryParam = \case
"MESSAGE_FORMAT_UNSPECIFIED" -> Right MessageFormatUnspecified
"PROTOBUF" -> Right Protobuf
"JSON" -> Right JSON
x -> Left ("Unable to parse PubsubConfigMessageFormat from: " <> x)
instance ToHttpApiData PubsubConfigMessageFormat where
toQueryParam = \case
MessageFormatUnspecified -> "MESSAGE_FORMAT_UNSPECIFIED"
Protobuf -> "PROTOBUF"
JSON -> "JSON"
instance FromJSON PubsubConfigMessageFormat where
parseJSON = parseJSONText "PubsubConfigMessageFormat"
instance ToJSON PubsubConfigMessageFormat where
toJSON = toJSONText
-- | The log type that this config enables.
data AuditLogConfigLogType
= LogTypeUnspecified
-- ^ @LOG_TYPE_UNSPECIFIED@
-- Default case. Should never be this.
| AdminRead
-- ^ @ADMIN_READ@
-- Admin reads. Example: CloudIAM getIamPolicy
| DataWrite
-- ^ @DATA_WRITE@
-- Data writes. Example: CloudSQL Users create
| DataRead
-- ^ @DATA_READ@
-- Data reads. Example: CloudSQL Users list
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AuditLogConfigLogType
instance FromHttpApiData AuditLogConfigLogType where
parseQueryParam = \case
"LOG_TYPE_UNSPECIFIED" -> Right LogTypeUnspecified
"ADMIN_READ" -> Right AdminRead
"DATA_WRITE" -> Right DataWrite
"DATA_READ" -> Right DataRead
x -> Left ("Unable to parse AuditLogConfigLogType from: " <> x)
instance ToHttpApiData AuditLogConfigLogType where
toQueryParam = \case
LogTypeUnspecified -> "LOG_TYPE_UNSPECIFIED"
AdminRead -> "ADMIN_READ"
DataWrite -> "DATA_WRITE"
DataRead -> "DATA_READ"
instance FromJSON AuditLogConfigLogType where
parseJSON = parseJSONText "AuditLogConfigLogType"
instance ToJSON AuditLogConfigLogType where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
| brendanhay/gogol | gogol-sourcerepo/gen/Network/Google/SourceRepo/Types/Sum.hs | mpl-2.0 | 3,693 | 0 | 11 | 848 | 581 | 317 | 264 | 71 | 0 |
module Module.TremRelay (mdl) where
import Module hiding (send)
import Module.State
import Network.Socket
import Control.DeepSeq
import Control.Exception
import Control.Monad
import System.IO
import Send
import Irc.Protocol
--import Tremulous.Util
mdl :: Module State
mdl = Module
{ modName = "tremrelay"
, modInit = do
Config{tremdedhost, tremdedchan, tremdedfifo} <- gets config
sendchan <- gets sendchan
sock <- mInit [tremdedhost] $ initSock tremdedhost
relay <- mInit [recase tremdedchan, tremdedfifo] $ forkIO $ tremToIrc (sendIrc sendchan) tremdedchan tremdedfifo
modifyCom $ \x -> x {relay = TremRelay sock relay}
, modFinish = do
(TremRelay s t) <- getsCom relay
let g f = maybe (return ()) (io . f)
g sClose s
g killThread t
modifyCom $ \x -> x {relay = TremRelay Nothing Nothing}
, modList = [("trem" , (comRelay , 1 , Peon , "<<message>>"
, "Send a message to a trem server."))]
}
where sendIrc chan = atomically . writeTChan chan . strict . responseToIrc
mInit c f = if all (not . null) c then Just <$> io f else return Nothing
initSock :: String -> IO Socket
initSock ipport = do
let (ip, port) = getIP ipport
host <- getDNS ip port
sock <- socket (dnsFamily host) Datagram defaultProtocol
connect sock (dnsAddress host)
return sock
comRelay :: Command State
comRelay mess = do
TremRelay maybesock _ <- getsCom relay
Nocase sender <- asks nickName
rcon <- gets (tremdedrcon . config)
tremchan <- gets (tremdedchan . config)
okey <- (tremchan /=) <$> asks channel
case maybesock of
Nothing -> Error >>> "Deactivated."
Just _ | okey -> Error >>> "Only active for " ++ recase tremchan ++ "."
Just sock -> do
io $ send sock $ "\xFF\xFF\xFF\xFFrcon "++rcon++" chat ^7[^5IRC^7] "++sender++": ^2" ++ mess
return ()
-- The fifo has to be opened in ReadWriteMode to prevent it from reaching EOF right away.
-- Nothing will ever be written to it however.
tremToIrc :: (IRC -> IO ()) -> Nocase -> FilePath -> IO ()
tremToIrc echo ircchan fifo = bracket (openFile fifo ReadWriteMode) hClose $ \hdl -> do
hSetBuffering hdl NoBuffering
forever $ do
tremline <- dropWhile invalid `liftM` hGetLine hdl
case uncurry tline =<< fbreak tremline of
Nothing -> return ()
Just a -> echo $ Msg ircchan a
where
fbreak x = case break (==':') x of
(a, ':':' ':b) -> Just (a, b)
_ -> Nothing
invalid x = isSpace x || x == ']' || isControl x
--For 1.2
--Say: 0 "^5C^7adynum^5.^7ddos^7": ^2irc: lol
tline :: String -> String -> Maybe String
tline "Say" x = case stripInfix ": ^2irc: " . dropOneWord $ x of
Just (name, m) -> Just $ "<[T] " ++ ircifyColors name ++ "> " ++ removeColors m
Nothing -> Nothing
tline "say" x = case stripInfix ": irc: " x of
Just (name, m) -> Just $ "<[T] " ++ ircifyColors name ++ "> " ++ removeColors m
Nothing -> Nothing
tline _ _ = Nothing
dropOneWord :: String -> String
dropOneWord = dropWhile isSpace . dropWhile (not . isSpace)
| DDOS-code/rivertam | src/Module/TremRelay.hs | agpl-3.0 | 2,953 | 55 | 19 | 605 | 1,152 | 568 | 584 | -1 | -1 |
module Net.DigitalOcean (module X) where
import Net.DigitalOcean.Config as X
import Net.DigitalOcean.Actions as X
import Net.DigitalOcean.Regions as X
import Net.DigitalOcean.Sizes as X
import Net.DigitalOcean.Images as X
import Net.DigitalOcean.SSHKeys as X
import Net.DigitalOcean.Droplets as X
| bluepeppers/DigitalOcean | src/Net/DigitalOcean.hs | agpl-3.0 | 298 | 0 | 4 | 34 | 68 | 50 | 18 | 8 | 0 |
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func =
( lakjsdlajsdljasdlkjasldjasldjasldjalsdjlaskjd
, lakjsdlajsdljasdlkjasldjasldjasldjalsdjlaskjd
)
| lspitzner/brittany | data/Test439.hs | agpl-3.0 | 225 | 0 | 5 | 24 | 13 | 8 | 5 | 3 | 1 |
--
-- Copyright (C) 2004-5 Don Stewart - http://www.cse.unsw.edu.au/~dons
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
-- USA
--
--
-- | Evaluate Haskell at runtime, using runtime compilation and dynamic
-- loading. Arguments are compiled to native code, and dynamically
-- loaded, returning a Haskell value representing the compiled argument.
-- The underlying implementation treats 'String' arguments as the source
-- for plugins to be compiled at runtime.
--
module System.Plugins.Eval (
eval,
eval_,
unsafeEval,
unsafeEval_,
typeOf,
mkHsValues,
{-
hs_eval_b, -- return a Bool
hs_eval_c, -- return a CChar
hs_eval_i, -- return a CInt
hs_eval_s, -- return a CString
-}
) where
import System.Plugins.Load
import System.Plugins.Make
import System.Plugins.Utils
import Control.Applicative
import Data.Char
import Data.Dynamic ( Dynamic )
import Data.Map as Map
import Data.Typeable ( Typeable )
import System.Directory
import System.IO ( hClose, hFlush, hPutStr )
import System.IO.Unsafe
import System.Random
type Import = String
symbol :: Symbol
symbol = "resource"
defaultArgs = ["-O0","-package","plugins"]
-- | 'eval' provides a typesafe (to a limit) form of runtime evaluation
-- for Haskell -- a limited form of /runtime metaprogramming/. The
-- 'String' argument to 'eval' is a Haskell source fragment to evaluate
-- at rutime. @imps@ are a list of module names to use in the context of
-- the compiled value.
--
-- The value returned by 'eval' is constrained to be 'Typeable' --
-- meaning we can perform a /limited/ runtime typecheck, using the
-- 'dynload' function. One consequence of this is that the code must
-- evaluate to a monomorphic value (which will be wrapped in a
-- 'Dynamic').
--
-- If the evaluated code typechecks under the 'Typeable' constraints,
-- 'Right v' is returned. 'Left errors' indicates typechecking failed.
-- Typechecking may fail at two places: when compiling the argument, or
-- when typechecking the splice point. 'eval' resembles a
-- metaprogramming 'run' operator for /closed/ source fragments.
--
-- To evaluate polymorphic values you need to wrap them in data
-- structures using rank-N types.
--
-- Examples:
--
-- > do i <- eval "1 + 6 :: Int" [] :: IO (Either String Int)
-- > print $ forceEither i
--
eval :: Typeable a => String -> [Import] -> IO (Either String a)
eval src imps = eval_ src imps defaultArgs [] []
--
-- | 'eval_' is a variety of 'eval' with all the internal hooks
-- available. You are able to set any extra arguments to the compiler
-- (for example, optimisation flags) or dynamic loader.
--
eval_ :: Typeable a =>
String -- ^ code to compile
-> [Import] -- ^ any imports
-> [String] -- ^ extra make flags
-> [FilePath] -- ^ (package.confs) for load
-> [FilePath] -- ^ include paths load is to search in
-> IO (Either String a) -- ^ either an error msg, or a well typed value
eval_ = rawEval dynwrap dynload
-- | Sometimes when constructing string fragments to evaluate, the
-- programmer is able to provide some other constraint on the evaluated
-- string, such that the evaluated expression will be typesafe, without
-- requiring a 'Typeable' constraint. In such cases, the monomorphic
-- restriction is annoying. 'unsafeEval' removes any splice-point
-- typecheck, with an accompanying obligation on the programmer to
-- ensure that the fragment evaluated will be typesafe at the point it
-- is spliced.
--
-- An example of how to do this would be to wrap the fragment in a call
-- to 'show'. The augmented fragment would then be checked when compiled
-- to return a 'String', and the programmer can rely on this, without
-- requiring a splice-point typecheck, and thus no 'Typeable'
-- restriction.
--
-- Note that if you get the proof wrong, your program will likely
-- segfault.
--
-- Example:
--
-- > do s <- unsafeEval "map toUpper \"haskell\"" ["Data.Char"]
-- > putStrLn $ forceEither s
--
unsafeEval :: String -> [Import] -> IO (Either String a)
unsafeEval src mods = unsafeEval_ src mods defaultArgs [] []
--
-- | 'unsafeEval_' is a form of 'unsafeEval' with all internal hooks
-- exposed. This is useful for application wishing to specify particular
-- libraries to link against and so on.
--
unsafeEval_ :: String -- ^ code to compile
-> [Import] -- ^ any imports
-> [String] -- ^ make flags
-> [FilePath] -- ^ (package.confs) for load
-> [FilePath] -- ^ include paths load is to search in
-> IO (Either String a)
unsafeEval_ = rawEval wrap load
rawEval wrapper loader src imps args ldflags incs = do
pwd <- getCurrentDirectory
(tmpf,tmph) <- mkTemp
hPutStr tmph $ wrapper src (takeBaseName' tmpf) imps
hFlush tmph >> hClose tmph
status <- make tmpf args
case status of
MakeFailure es -> return $ Left $ unlines es
MakeSuccess _ obj -> do
m_v <- loader obj (pwd:incs) ldflags symbol
case m_v of
LoadFailure es -> return $ Left $ unlines es
LoadSuccess _ rsrc -> return $ Right rsrc
<* makeCleaner tmpf
------------------------------------------------------------------------
--
-- | 'mkHsValues' is a helper function for converting 'Data.Map's
-- of names and values into Haskell code. It relies on the assumption that
-- the passed values' Show instances produce valid Haskell literals
-- (this is true for all Prelude types).
--
mkHsValues :: (Show a) => Map.Map String a -> String
mkHsValues values = concat $ elems $ Map.mapWithKey convertToHs values
where convertToHs :: (Show a) => String -> a -> String
convertToHs name value = name ++ " = " ++ show value ++ "\n"
------------------------------------------------------------------------
--
-- | Return a compiled value's type, by using Dynamic to get a
-- representation of the inferred type.
--
typeOf :: String -> [Import] -> IO (Either String String)
typeOf src imps = do
r <- eval src imps :: IO (Either String Dynamic)
return $ fmap (init . tail . show) r
-- ---------------------------------------------------------------------
-- wrappers
--
dynwrap :: String -> String -> [Import] -> String
dynwrap expr nm mods =
"module "++nm++ "( resource ) where\n" ++
concatMap (\m-> "import "++m++"\n") mods ++
"import Data.Dynamic\n" ++
"resource = let { "++x++" = \n" ++
"{-# LINE 1 \"<eval>\" #-}\n" ++ expr ++ ";} in toDyn "++x
where
x = randName ()
wrap :: String -> String -> [Import] -> String
wrap expr nm mods =
"module "++nm++ "( resource ) where\n" ++
concatMap (\m-> "import "++m++"\n") mods ++
"resource = let { "++x++" = \n" ++
"{-# LINE 1 \"<Plugins.Eval>\" #-}\n" ++ expr ++ ";} in "++x
where
x = randName ()
randName () = unsafePerformIO $
sequence $ replicate 3 $ getStdRandom (randomR (97,122)) >>= return . chr
-- what is this big variable name?
-- its a random value, so that it won't clash if the accidently mistype
-- an unbound 'x' or 'v' in their code.. it won't reveal the internal
-- structure of the wrapper, which is annoying in irc use by lambdabot
{-
------------------------------------------------------------------------
--
-- And for our friends in foreign parts
--
-- TODO needs to accept char** to import list
--
--
-- return NULL pointer if an error occured.
--
foreign export ccall hs_eval_b :: CString -> IO (Ptr CInt)
foreign export ccall hs_eval_c :: CString -> IO (Ptr CChar)
foreign export ccall hs_eval_i :: CString -> IO (Ptr CInt)
foreign export ccall hs_eval_s :: CString -> IO CString
------------------------------------------------------------------------
--
-- TODO implement a marshalling for Dynamics, so that we can pass that
-- over to the C side for checking.
--
hs_eval_b :: CString -> IO (Ptr CInt)
hs_eval_b s = do m_v <- eval_cstring s
case m_v of Nothing -> return nullPtr
Just v -> new (fromBool v)
hs_eval_c :: CString -> IO (Ptr CChar)
hs_eval_c s = do m_v <- eval_cstring s
case m_v of Nothing -> return nullPtr
Just v -> new (castCharToCChar v)
-- should be Integral
hs_eval_i :: CString -> IO (Ptr CInt)
hs_eval_i s = do m_v <- eval_cstring s :: IO (Maybe Int)
case m_v of Nothing -> return nullPtr
Just v -> new (fromIntegral v :: CInt)
hs_eval_s :: CString -> IO CString
hs_eval_s s = do m_v <- eval_cstring s
case m_v of Nothing -> return nullPtr
Just v -> newCString v
--
-- convenience
--
eval_cstring :: Typeable a => CString -> IO (Maybe a)
eval_cstring cs = do s <- peekCString cs
eval s [] -- TODO use eval()
-}
| Changaco/haskell-plugins | src/System/Plugins/Eval.hs | lgpl-2.1 | 9,771 | 0 | 18 | 2,374 | 1,141 | 645 | 496 | 81 | 3 |
{-#LANGUAGE DeriveDataTypeable#-}
module Data.P440.Domain.IZV where
import Data.P440.Domain.SimpleTypes
import Data.Typeable (Typeable)
import Data.Text (Text)
-- 3.1 Извещение
data Файл = Файл {
идЭС :: GUID
,версПрог :: Text
,телОтпр :: Text
,должнОтпр :: Text
,фамОтпр :: Text
,извещение :: Извещение
} deriving (Eq, Show, Typeable)
data Извещение = Извещение {
имяФайла :: Text
,кодРезПроверки :: Text
,датаВремяПроверки :: DateTime
,датаВремяПериода :: Maybe DateTime
} deriving (Eq, Show, Typeable)
| Macil-dev/440P-old | src/Data/P440/Domain/IZV.hs | unlicense | 719 | 27 | 7 | 138 | 387 | 211 | 176 | 19 | 0 |
module Main where
import Primes
import Digits
import Data.List
increase = 3330
primePermutations :: [Int]
primePermutations = filter isMatchingNum candidates
where
candidates = [1000..maxPossibleNum]
maxPossibleNum = 10000 - (increase*2)
isMatchingNum num = isPrimePermutationTrio (num,num+increase,num+2*increase)
isPrimePermutationTrio (a,b,c) = (isPrime a) && (isPrime b) && (isPrime c) && isPermutationInTrio (a,b,c)
isPermutationInTrio (a,b,c) = (sortedDigits a == sortedDigits b) && (sortedDigits a == sortedDigits c)
sortedDigits = sort.digits
main = print $ map (\x -> [x,x+increase,x+2*increase]) primePermutations
| kliuchnikau/project-euler | 049/Main.hs | apache-2.0 | 654 | 0 | 11 | 104 | 254 | 140 | 114 | 14 | 1 |
module TimeUtils
( lookupLocalTimeZone
, startOfDay
, justAfter, justBefore
, asLocalTime
, localTimeText
, originTime
)
where
import Prelude ()
import Prelude.MH
import qualified Data.Text as T
import Data.Time.Clock ( UTCTime(..) )
import Data.Time.Format ( formatTime, defaultTimeLocale )
import Data.Time.LocalTime ( LocalTime(..), TimeOfDay(..) )
import Data.Time.LocalTime.TimeZone.Olson ( getTimeZoneSeriesFromOlsonFile )
import Data.Time.LocalTime.TimeZone.Series ( localTimeToUTC'
, utcToLocalTime')
import Network.Mattermost.Types ( ServerTime(..) )
-- | Get the timezone series that should be used for converting UTC
-- times into local times with appropriate DST adjustments.
lookupLocalTimeZone :: IO TimeZoneSeries
lookupLocalTimeZone = getTimeZoneSeriesFromOlsonFile "/etc/localtime"
-- | Sometimes it is convenient to render a divider between messages;
-- the 'justAfter' function can be used to get a time that is after
-- the input time but by such a small increment that there is unlikely
-- to be anything between (or at) the result. Adding the divider
-- using this timestamp value allows the general sorting based on
-- timestamps to operate normally (whereas a type-match for a
-- non-timestamp-entry in the sort operation would be considerably
-- more complex).
justAfter :: ServerTime -> ServerTime
justAfter = ServerTime . justAfterUTC . withServerTime
where justAfterUTC time = let UTCTime d t = time in UTCTime d (succ t)
-- | Obtain a time value that is just moments before the input time;
-- see the comment for the 'justAfter' function for more details.
justBefore :: ServerTime -> ServerTime
justBefore = ServerTime . justBeforeUTC . withServerTime
where justBeforeUTC time = let UTCTime d t = time in UTCTime d (pred t)
-- | The timestamp for the start of the day associated with the input
-- timestamp. If timezone information is supplied, then the returned
-- value will correspond to when the day started in that timezone;
-- otherwise it is the start of the day in a timezone aligned with
-- UTC.
startOfDay :: Maybe TimeZoneSeries -> UTCTime -> UTCTime
startOfDay Nothing time = let UTCTime d _ = time in UTCTime d 0
startOfDay (Just tz) time = let lt = utcToLocalTime' tz time
ls = LocalTime (localDay lt) (TimeOfDay 0 0 0)
in localTimeToUTC' tz ls
-- | Convert a UTC time value to a local time.
asLocalTime :: TimeZoneSeries -> UTCTime -> LocalTime
asLocalTime = utcToLocalTime'
-- | Local time in displayable format
localTimeText :: Text -> LocalTime -> Text
localTimeText fmt time = T.pack $ formatTime defaultTimeLocale (T.unpack fmt) time
-- | Provides a time value that can be used when there are no other times available
originTime :: UTCTime
originTime = UTCTime (toEnum 0) 0
| aisamanra/matterhorn | src/TimeUtils.hs | bsd-3-clause | 2,972 | 0 | 11 | 673 | 491 | 276 | 215 | 36 | 1 |
-- |Module to parse the command line
module Commandline
( OutFormat(..)
, Options(..)
, commandLineOptions
)
where
import Control.Monad
import Data.Char
import Data.List
import Error
import System.Console.GetOpt
import System.FilePath
import Text.Read
-- |Supported output formats
data OutFormat
= PRG -- ^ A binary format directly loadable by an emulator
| HEX -- ^ A textual hexdump
deriving (Eq,Show,Read)
-- |Command line options of the assembler
data Options = Options
{ optDumpParsed :: Bool -- ^ Tracing: dump parsed input program
, optFormat :: OutFormat -- ^ Parsed output format
, optFormatRaw :: String -- ^ Raw output format as specified on command line
, optOutput :: FilePath -- ^ The output file
, optShowHelp :: Bool -- ^ Show help and terminate program
, optShowSymtab :: Bool -- ^ Tracing: print all symbols with their resolved addresses
, optShowVersion :: Bool -- ^ Show version information and terminate program
} deriving (Eq,Show)
-- |Default values for command line options
defaultOptions :: Options
defaultOptions = Options
{ optDumpParsed = False
, optFormat = PRG
, optFormatRaw = ""
, optOutput = ""
, optShowHelp = False
, optShowSymtab = False
, optShowVersion = False
}
-- |Option descriptions for GetOpt module
options :: [OptDescr (Options -> Options)]
options =
[ Option ['h','?']
["help"]
(NoArg (\opts -> opts { optShowHelp = True }))
"Print this help message."
, Option ['v']
["version"]
(NoArg (\opts -> opts { optShowVersion = True }))
"Print the version information."
, Option ['s']
["symtab"]
(NoArg (\opts -> opts { optShowSymtab = True }))
"Print the symbol table."
, Option ['d']
["dparse"]
(NoArg (\opts -> opts { optDumpParsed = True }))
"Print the parsed input program."
, Option ['o']
["output"]
(ReqArg (\s opts -> opts { optOutput = s }) "FILE")
("Set output file. Defaults to '<input>.prg' or '<input>.hex'.")
, Option ['f']
["format"]
(ReqArg (\s opts -> opts { optFormatRaw = s }) "FORMAT")
("Set output format to 'PRG' or 'HEX'. Defaults to '" ++ show (optFormat defaultOptions) ++ "'.")
]
-- |Command line handling
commandLineOptions :: [String] -> IO (Options, String)
commandLineOptions argv =
case getOpt Permute options argv of
(o,n,[]) -> do
when (optShowHelp o') showHelp
when (optShowVersion o') showVersion
file <- handleInputFile n
opts <- handleOutputFormat o' >>= handleOutputFile file
return (opts, file)
where
o' = foldl (flip id) defaultOptions o
(_,_,errs) -> exitWithError $ concat (map ("Error: "++) $ nub errs) ++ usageInfo header options
-- |Header message for usage info
header :: String
header = "Synopsis: asm6502 [options] <input file>"
-- |Show help and exit programm
showHelp :: IO ()
showHelp = exitWithInfo (usageInfo header options)
-- |Show version info and exit programm
showVersion :: IO ()
showVersion = exitWithInfo "Asm6502 version 1"
-- |Check for a single input file
handleInputFile :: [String] -> IO String
handleInputFile files = do
case files of
f:[] -> return $ makeValid f
_ -> exitWithError "Error: please specify exactly one input file"
-- |Check for a valid output format specification
handleOutputFormat :: Options -> IO Options
handleOutputFormat opts
| null format = return opts
| otherwise = case readMaybe format of
Just f -> return opts { optFormat = f }
Nothing -> exitWithError $ "Error: illegal output format '" ++ format ++ "'"
where
format = map toUpper $ optFormatRaw opts
-- |Check for name of output file, generate one from input file if missing
handleOutputFile :: FilePath -> Options -> IO Options
handleOutputFile file opts
| null output = return opts { optOutput = replaceExtension file $ map toLower $ show $ optFormat opts }
| otherwise = return opts
where
output = optOutput opts
| m-schmidt/Asm6502 | src/Commandline.hs | bsd-3-clause | 4,126 | 0 | 14 | 1,026 | 1,012 | 555 | 457 | 93 | 2 |
{- -O2 provides small, but noticable benefit for qsort. -}
module Data.Array.MArray.Sort.Introsort
( qsort
, introsort
-- internal
, introsort'
) where
import Control.Monad
import Data.Array.IO
import Data.Array.MArray.Sort.Heapsort
import Data.Array.MArray.Sort.Insertsort
insertsortLimit :: Int
insertsortLimit = 32
depthCoeficient :: Double
depthCoeficient = 2 / log 2
{-# INLINE qsort #-}
qsort :: (MArray a e m, Ord e) => a Int e -> m ()
qsort = introsort' (return ()) ( -1 )
{-# INLINE maxQSortDepth #-}
maxQSortDepth :: (MArray a e m) => a Int e -> m Int
maxQSortDepth arr = do
(mn, mx) <- getBounds arr
return $ ceiling (depthCoeficient * log (fromIntegral $ mx - mn + 1))
{-# INLINE introsort #-}
introsort :: (MArray a e m, Ord e) => a Int e -> m ()
introsort arr = maxQSortDepth arr >>= \d -> introsort' (return ()) d arr
{-# INLINE introsort' #-}
introsort' :: (MArray a e m, Ord e) => m () -> Int -> a Int e -> m ()
introsort' cmpaction maxdepth a = getBounds a >>= uncurry (srt maxdepth)
where
srt depthleft mn mx
| depthleft == 0 = heapsort' a mn mx
| mn + insertsortLimit > mx = insertsort' cmpaction a mn mx
| otherwise = do
-- Select a pivot - median of 3:
pL <- readArray a mn
pR <- readArray a mx
let d = (mn + mx) `div` 2
pD <- readArray a d
cmpaction
let (_, pidx) = median3 (pR, mx) (pD, d) (pL, mn)
p <- swap d mn
i <- split p (mn + 1) mx
swap i mn
let depthleft' = depthleft - 1
-- Sort the smaller part first. Hopefully, tail
-- recursion will catch on the larger part and so we'll
-- have guaranteed that even in the worst case, we'll
-- have at most (log n) calls on the stack.
if i < d then do
srt depthleft' mn (i - 1)
srt depthleft' (i + 1) mx
else do
srt depthleft' (i + 1) mx
srt depthleft' mn (i - 1)
where
{-# INLINE swap #-}
swap i j = do
u <- readArray a i
when (i /= j) $ do
v <- readArray a j
writeArray a i v
writeArray a j u
return u
{-# INLINE split #-}
split p = split'
where
split' i j = do
i' <- moveRight i
j' <- moveLeft j
if i' < j'
then swap i' j' >> split' (i' + 1) (j' - 1)
else return j'
where
moveRight i | i > j = return i
| otherwise = do
v <- readArray a i
cmpaction
if v >= p
then return i
else moveRight (i + 1)
moveLeft j | i > j = return j
| otherwise = do
v <- readArray a j
cmpaction
if v <= p
then return j
else moveLeft (j - 1)
{-# INLINE median3 #-}
median3 :: Ord a => a -> a -> a -> a
median3 a b c
| a > b = sel a b
| otherwise = sel b a
where
sel l s | c > l = l
| c < s = s
| otherwise = c
| ppetr/marray-sort | src/Data/Array/MArray/Sort/Introsort.hs | bsd-3-clause | 3,480 | 0 | 19 | 1,558 | 1,117 | 548 | 569 | 84 | 5 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoImplicitPrelude #-}
{- |
On little-endian machines, IO functions only support little-endian SND format with 1 channel and 64-bit float samples.
-}
module Sound.IoPtr
(
module Sound.Io
, module Sound.Ptr
, module Sound.Buffer
-- * Array-poking
, ePokeArray
-- * SND header
, SndHeader(..)
, sndMagic
, sndMinHeaderSize
, sndMaxGapSize
, pokeSndHeader
, peekSndHeader
, hGetSndHeader
-- * File
, hMustGetBuf
, bufReadFile
, bufWithFile
, ptrReadFile
, ptrWithReadFile
, ptrWithReadRawFile
)
where
import Sound.Abstract
import Sound.Buffer
import Sound.Class
import Sound.Io
import Sound.Ptr
sndMagic :: Word32
sndMagic = 0x2e736e64
sndMinHeaderSize :: (Num a) => a
sndMinHeaderSize = 24
sndMaxGapSize :: (Num a) => a
sndMaxGapSize = 1048576
data SndHeader
= MkSndHeader
{
_shDataOffset :: !Word32
, _shSampleCount :: !Word32
, _shEncoding :: !Word32
, _shRate :: !Word32
, _shChannelCount :: !Word32
}
deriving (Read, Show)
pokeSndHeader :: Ptr a -> SndHeader -> IO ()
pokeSndHeader p (MkSndHeader b c d e f) = do
expect (b == sndMinHeaderSize) $ "unsupported data offset " ++ show b
expect (d == 7) $ "unsupported encoding " ++ show d
expect (f == 1) $ "unsupported channel count " ++ show f
pokeByteOff p 0 sndMagic
pokeByteOff p 4 b
pokeByteOff p 8 c
pokeByteOff p 12 d
pokeByteOff p 16 e
pokeByteOff p 20 f
expect :: Bool -> String -> IO ()
expect cond msg = unless cond $ ioUserError msg
shGapSize :: SndHeader -> IO Int
shGapSize h = do
expect (gapSize >= 0) "negative gap size"
expect (gapSize <= sndMaxGapSize) "gap too large"
return gapSize
where
gapSize = fromIntegral (_shDataOffset h) - sndMinHeaderSize
peekSndHeader :: Ptr a -> IO SndHeader
peekSndHeader p = do
a <- peekByteOff p 0
unless (a == sndMagic) $ ioUserError "wrong magic"
MkSndHeader
<$> peekByteOff p 4
<*> peekByteOff p 8
<*> peekByteOff p 12
<*> peekByteOff p 16
<*> peekByteOff p 20
hMustGetBuf :: Handle -> Ptr a -> Int -> IO ()
hMustGetBuf handle ptr count = do
n <- hGetBuf handle ptr count
unless (n == count) $ ioUserError "premature end of handle"
hGetSndHeader :: Handle -> IO SndHeader
hGetSndHeader handle =
allocaBytes sndMinHeaderSize $ \ p -> do
hMustGetBuf handle p sndMinHeaderSize
header <- peekSndHeader p
gapSize <- shGapSize header
unless (gapSize == 0) $ allocaBytes discardBufSize $ \ discardPtr ->
let
loop !remaining = do
let !readCount = min discardBufSize remaining
when (readCount > 0) $ do
hMustGetBuf handle discardPtr readCount
loop (remaining - readCount)
in
loop gapSize
return $! header
where
discardBufSize = 4096
ePokeArray :: (Storable a) => Endo s -> (s -> a) -> Ptr a -> Int -> s -> IO ()
ePokeArray f extract ptr count =
loop 0
where
loop !i !s =
let
!t = f s
!x = extract s
in
if i >= count
then return ()
else pokeElemOff ptr i x >> loop (i + 1) t
bufReadFile :: FilePath -> IO (Buffer ForeignPtr Word8)
bufReadFile path = do
size <- getFileSize path
fptr <- mallocForeignPtrBytes size
byteCount <- withForeignPtr fptr $ \ ptr -> ptrReadFile path ptr size
return (MkBuffer fptr byteCount byteCount)
bufWithFile :: (Storable a) => FilePath -> (Buffer Ptr a -> IO r) -> IO r
bufWithFile path consume_ = do
buf <- bufReadFile path
withForeignBuffer buf (consume_ . bufCast)
{-# INLINE bufWithFile #-}
ptrReadFile :: FilePath -> Ptr a -> ByteCount -> IO ByteCount
ptrReadFile path ptr size =
withBinaryFile path ReadMode $ \ handle -> do
numBytesRead <- hGetBuf handle ptr size
-- FIXME not always userError
unless (numBytesRead == size) $ ioUserError $ path ++ " size " ++ show size ++ " read " ++ show numBytesRead
return numBytesRead
ptrWithReadFile :: FilePath -> (ByteCount -> Ptr a -> IO r) -> IO r
ptrWithReadFile path consume_ = do
size <- getFileSize path
allocaBytes size $ \ ptr -> do
numBytesRead <- ptrReadFile path ptr size
consume_ numBytesRead ptr
ptrWithReadRawFile :: FilePath -> (ElemCount Double -> Ptr Double -> IO r) -> IO r
ptrWithReadRawFile path consume_ =
ptrWithReadFile path (\ byteCount ptr -> consume_ (byteCount `div` 8) (castPtr ptr))
| edom/sound | src/Sound/IoPtr.hs | bsd-3-clause | 4,728 | 0 | 22 | 1,387 | 1,449 | 703 | 746 | 135 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE RankNTypes #-}
module GDAL.Plugin.CombinatorsAcc (
module GDAL.Plugin.CombinatorsAcc
, module A
) where
import GDAL.Plugin.Types
import GDAL.Plugin.Internal as I
import GDAL
import GDAL.Internal.HSDataset
import qualified Data.Text as T
import qualified Data.Vector.Storable as St
import Data.Maybe
import Data.Proxy
import Control.Monad
import Control.DeepSeq
import Control.Monad.IO.Class ( MonadIO(..) )
import GHC.Exts ( Constraint )
import Data.Array.Accelerate.Array.Sugar (EltRepr)
import Data.Array.Accelerate as A
import qualified Data.Array.Accelerate.LLVM.Native as CPU
#if HAVE_PTX
import qualified Data.Array.Accelerate.LLVM.PTX as PTX
#endif
import Data.Array.Accelerate.IO ( Vectors, fromVectors, toVectors)
import Prelude as P
import System.IO (hPutStrLn, stderr)
import Text.Read (readMaybe)
import GHC.Conc ( numCapabilities )
class LiftableFunc f where
type LiftConstr f :: Constraint
liftFunc :: f -> Lifted
mapExisting :: LiftableFunc f => f -> SomeFactory
mapExisting liftable = someFactory $ \query -> case liftFunc liftable of
Lift1 opener (fun :: Exp a -> Exp b) -> do
bandIn <- opener query
funAcc <- getRun1 (A.map fun)
bandNd <- bandNodataValue (bandAs bandIn (dataType (Proxy :: Proxy b)))
mkDataset bandIn [
HSRasterBand { blockSize = bsize
, nodata = bandNd
, readBlock = mkReadBlock1 funAcc bandIn
}
]
where
bsize = 256 :+: 256 :: Size
mkDataset :: Band s a t -> [HSRasterBand s] -> GDAL s (HSDataset s)
mkDataset protoBand rasterBands = do
srsIn <- bandProjection protoBand
gtIn <- fromMaybe (Geotransform 0 1 0 0 0 1) <$> bandGeotransform protoBand
return HSDataset
{ rasterSize = bandSize protoBand
, bands = rasterBands
, srs = srsIn
, geotransform = gtIn
}
mkReadBlock1
:: forall s m a b. (MonadIO m, Lift1Constr a b)
=> (Array DIM2 a -> Array DIM2 b)
-> ROBand s a
-> BlockIx
-> m (St.Vector b)
mkReadBlock1 fun band ix = do
vIn :: St.Vector a <- I.readBandBlockTranslated band bsize ix
let blockSh = let nx:+:ny = bsize in Z :. nx :. ny
return (toVectors . fun . fromVectors blockSh $ vIn)
type Lift1Constr a b = ( GDALType a, GDALType b, NFData b
, Elt a, Elt b
, Vectors (EltRepr a) ~ St.Vector a
, Vectors (EltRepr b) ~ St.Vector b
, Lift Exp b
)
type Opener a = forall s. QueryText -> GDAL s (ROBand s a)
data Lifted where
Lift1 :: Lift1Constr a b
=> Opener a
-> (Exp a -> Exp b)
-> Lifted
instance Lift1Constr a b => LiftableFunc (Exp a -> Exp b) where
type LiftConstr (Exp a -> Exp b) = Lift1Constr a b
liftFunc = Lift1 $ \query ->
let path = fromMaybe (error "Need to provide a path argument")
$ join (lookup "path" query)
bandStr = fromMaybe "1" (join (lookup "band" query))
band = fromMaybe (error "band must be an integer") (readMaybe (T.unpack bandStr))
in openReadOnly (T.unpack path) (dataType (Proxy :: Proxy a)) >>= getBand band
getRun1, getRun1CPU
:: (MonadIO m, Arrays a, Arrays b)
=> (Acc a -> Acc b) -> m (a -> b)
getRun1CPU acc = do
liftIO (hPutStrLn stderr ("CPU.run1 " P.++ show numCapabilities))
target <- liftIO $ case 1 of
1 -> CPU.createTarget [0] CPU.unbalancedParIO
n -> CPU.createTarget [0..n-1] CPU.unbalancedParIO
return (CPU.run1With target acc)
#if HAVE_PTX
getRun1PTX
:: (MonadIO m, Arrays a, Arrays b)
=> (Acc a -> Acc b) -> m (a -> b)
getRun1PTX acc = do
liftIO (hPutStrLn stderr "PTX.run1")
return (PTX.run1 acc)
getRun1 = getRun1PTX
#else
getRun1 = getRun1CPU
#endif
| meteogrid/gdal-plugin-hs | src/GDAL/Plugin/CombinatorsAcc.hs | bsd-3-clause | 4,229 | 0 | 19 | 1,118 | 1,330 | 708 | 622 | 97 | 2 |
{-# LANGUAGE CPP #-}
module BackendTest where
#ifndef WithoutBackendDependencies
import Test.HUnit
import Control.Monad ( forM_ )
import Database.Schema.Migrations.Backend.HDBC ()
import Database.Schema.Migrations.Migration ( Migration(..), newMigration )
import Database.Schema.Migrations.Backend ( Backend(..) )
import Database.HDBC ( IConnection(..), catchSql, withTransaction )
tests :: (IConnection a) => a -> IO ()
tests conn = do
let acts = [ isBootstrappedFalseTest
, bootstrapTest
, isBootstrappedTrueTest
, applyMigrationFailure
, applyMigrationSuccess
, revertMigrationFailure
, revertMigrationNothing
, revertMigrationJust
]
forM_ acts $ \act -> do
commit conn
act conn
bootstrapTest :: (IConnection a) => a -> IO ()
bootstrapTest conn = do
bs <- getBootstrapMigration conn
applyMigration conn bs
assertEqual "installed_migrations table exists" ["installed_migrations"] =<< getTables conn
assertEqual "successfully bootstrapped" [mId bs] =<< getMigrations conn
isBootstrappedTrueTest :: (IConnection a) => a -> IO ()
isBootstrappedTrueTest conn = do
result <- isBootstrapped conn
assertBool "Bootstrapped check" result
isBootstrappedFalseTest :: (IConnection a) => a -> IO ()
isBootstrappedFalseTest conn = do
result <- isBootstrapped conn
assertBool "Bootstrapped check" $ not result
ignoreSqlExceptions :: IO a -> IO (Maybe a)
ignoreSqlExceptions act = (act >>= return . Just) `catchSql`
(\_ -> return Nothing)
applyMigrationSuccess :: (IConnection a) => a -> IO ()
applyMigrationSuccess conn = do
m1 <- newMigration "validMigration"
let m1' = m1 { mApply = "CREATE TABLE valid1 (a int); CREATE TABLE valid2 (a int);" }
-- Apply the migrations, ignore exceptions
withTransaction conn $ \conn' -> applyMigration conn' m1'
-- Check that none of the migrations were installed
assertEqual "Installed migrations" ["root", "validMigration"] =<< getMigrations conn
assertEqual "Installed tables" ["installed_migrations", "valid1", "valid2"] =<< getTables conn
-- |Does a failure to apply a migration imply a transaction rollback?
applyMigrationFailure :: (IConnection a) => a -> IO ()
applyMigrationFailure conn = do
m1 <- newMigration "second"
m2 <- newMigration "third"
let m1' = m1 { mApply = "CREATE TABLE validButTemporary (a int)" }
let m2' = m2 { mApply = "INVALID SQL" }
-- Apply the migrations, ignore exceptions
ignoreSqlExceptions $ withTransaction conn $ \conn' -> do
applyMigration conn' m1'
applyMigration conn' m2'
-- Check that none of the migrations were installed
assertEqual "Installed migrations" ["root"] =<< getMigrations conn
assertEqual "Installed tables" ["installed_migrations"] =<< getTables conn
revertMigrationFailure :: (IConnection a) => a -> IO ()
revertMigrationFailure conn = do
m1 <- newMigration "second"
m2 <- newMigration "third"
let m1' = m1 { mApply = "CREATE TABLE validRMF (a int)"
, mRevert = Just "DROP TABLE validRMF"}
let m2' = m2 { mApply = "SELECT * FROM validRMF"
, mRevert = Just "INVALID REVERT SQL"}
applyMigration conn m1'
applyMigration conn m2'
installedBeforeRevert <- getMigrations conn
commit conn
-- Revert the migrations, ignore exceptions; the revert will fail,
-- but withTransaction will roll back.
ignoreSqlExceptions $ withTransaction conn $ \conn' -> do
revertMigration conn' m2'
revertMigration conn' m1'
-- Check that none of the migrations were reverted
assertEqual "successfully roll back failed revert" installedBeforeRevert
=<< getMigrations conn
revertMigrationNothing :: (IConnection a) => a -> IO ()
revertMigrationNothing conn = do
m1 <- newMigration "second"
let m1' = m1 { mApply = "SELECT 1"
, mRevert = Nothing }
applyMigration conn m1'
installedAfterApply <- getMigrations conn
assertBool "Check that the migration was applied" $ "second" `elem` installedAfterApply
-- Revert the migration, which should do nothing EXCEPT remove it
-- from the installed list
revertMigration conn m1'
installed <- getMigrations conn
assertBool "Check that the migration was reverted" $ not $ "second" `elem` installed
revertMigrationJust :: (IConnection a) => a -> IO ()
revertMigrationJust conn = do
let name = "revertable"
m1 <- newMigration name
let m1' = m1 { mApply = "CREATE TABLE the_test_table (a int)"
, mRevert = Just "DROP TABLE the_test_table" }
applyMigration conn m1'
installedAfterApply <- getMigrations conn
assertBool "Check that the migration was applied" $ name `elem` installedAfterApply
-- Revert the migration, which should do nothing EXCEPT remove it
-- from the installed list
revertMigration conn m1'
installed <- getMigrations conn
assertBool "Check that the migration was reverted" $ not $ name `elem` installed
#endif
| anton-dessiatov/dbmigrations | test/BackendTest.hs | bsd-3-clause | 5,182 | 0 | 12 | 1,220 | 1,187 | 590 | 597 | 96 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : dave.laing.80@gmail.com
Stability : experimental
Portability : non-portable
-}
module Fragment.SystemFw.Helpers (
tyLam
, tyLamAnn
, tyLamNoAnn
, tyApp
) where
import Control.Lens (review)
import Ast.Kind
import Ast.Type
import Fragment.SystemFw.Ast.Type
tyLam :: (Eq a, AsTySystemFw ki ty) => a -> Maybe (Kind ki a) -> Type ki ty a -> Type ki ty a
tyLam v ki ty = review _TyLam (ki, abstractTy v ty)
tyLamAnn :: (Eq a, AsTySystemFw ki ty) => a -> Kind ki a -> Type ki ty a -> Type ki ty a
tyLamAnn v ki ty = review _TyLamAnn (ki, abstractTy v ty)
tyLamNoAnn :: (Eq a, AsTySystemFw ki ty) => a -> Type ki ty a -> Type ki ty a
tyLamNoAnn v ty = review _TyLamNoAnn (abstractTy v ty)
tyApp :: AsTySystemFw ki ty => Type ki ty a -> Type ki ty a -> Type ki ty a
tyApp = curry $ review _TyApp
| dalaing/type-systems | src/Fragment/SystemFw/Helpers.hs | bsd-3-clause | 880 | 0 | 10 | 192 | 339 | 174 | 165 | 17 | 1 |
{-# LANGUAGE DeriveFunctor #-}
module Foundation.Layout where
import qualified Graphics.UI.Threepenny as UI
import Graphics.UI.Threepenny.Core hiding (row)
import Foundation.Common
import Data.Maybe (catMaybes, isJust)
-- Row {{{
data Row a = Row
{ rowCollapse :: Bool
, rowColumns :: [Column a]
} deriving (Functor)
instance ToElements a => ToElement (Row a) where
toElement (Row coll cs)
| maybe True (<= 12) (widthSmall cs) && maybe True (<= 12) (widthLarge cs) =
divClasses (if coll then ["row","collapse"] else ["row"]) #+
map toElement cs
| otherwise = fail $ "Column widths were greater than 12: (" ++ show (widthSmall cs) ++ ") (" ++ show (widthLarge cs) ++ ")"
widthSmall :: [Column a] -> Maybe Int
widthSmall cs = do
ms <- mapM smallLayout cs
let ns = map (\l -> [layoutWidth l,layoutOffset l]) ms
return $ sum $ concat ns
widthLarge :: [Column a] -> Maybe Int
widthLarge cs = do
ms <- mapM largeLayout cs
let ns = map (\l -> [layoutWidth l,layoutOffset l]) ms
return $ sum $ concat ns
collapseRow :: [Column a] -> Row a
collapseRow = Row True
row :: [Column a] -> Row a
row = Row False
pad :: ToElements a => a -> IO Element
pad a = toElement $ row
[ uniformLayout (centered 11) a
]
split :: ToElements a => [(Int,a)] -> IO Element
split cols = toElement $ row $ map mkCol cols
where
mkCol (width,cnt) = uniformLayout (colWidth width) cnt
-- }}}
-- Col {{{
data Column a = Column
{ smallLayout :: Maybe Layout
, largeLayout :: Maybe Layout
, colContent :: a
} deriving (Functor)
instance ToElements a => ToElement (Column a) where
toElement (Column smL lgL a) = do
smOpts <- formSmallOpts smL
lgOpts <- formLargeOpts lgL
let opts = catMaybes $ smOpts ++ lgOpts
cts <- toElements a
divClasses (opts ++ ["columns"]) #+ map element cts
where
formSmallOpts = formSizeOpts ("small-" ++)
formLargeOpts = formSizeOpts ("large-" ++)
formSizeOpts :: (String -> String) -> Maybe Layout -> IO [Maybe String]
formSizeOpts _ Nothing = return []
formSizeOpts size (Just l@(Layout cen off wid))
| wid > 0 && off < 12 && (wid + off) <= 12
= return
[ maybeWhen cen $ size "centered"
, maybeWhen (off > 0) $ size $ "offset-" ++ show off
, maybeWhen True $ size $ show wid
]
| otherwise = fail $ "Bad column layout: " ++ show l
col :: a -> Column a
col = uniformLayout (colWidth 12)
stackAlways :: a -> Column a
stackAlways = Column Nothing Nothing
uniformLayout :: Layout -> a -> Column a
uniformLayout smL = Column (Just smL) Nothing
stackOnSmall :: Layout -> a -> Column a
stackOnSmall lgL = Column Nothing (Just lgL)
overrideSmall :: Layout -> Layout -> a -> Column a
overrideSmall smL lgL = Column (Just smL) (Just lgL)
-- Layout
data Layout = Layout
{ layoutCentered :: Bool
, layoutOffset :: Int
, layoutWidth :: Int
} deriving Show
centered :: Int -> Layout
centered = Layout True 0
offset :: Int -> Int -> Layout
offset o = Layout False o
colWidth :: Int -> Layout
colWidth = Layout False 0
-- }}}
-- Grid {{{
data Grid a = Grid
{ smallRowSize :: Maybe Int
, largeRowSize :: Maybe Int
, gridContents :: [a]
} deriving (Functor)
instance ToElements a => ToElement (Grid a) where
toElement (Grid smSize lgSize cs) = do
opts <- mkOpts
css <- mapM toElements cs
UI.ul # set classes (catMaybes opts) # set UI.style [] #+ map ((UI.li #+) . map element) css
where
mkOpts
| isJust smSize || isJust lgSize = return
[ fmap (\i -> "small-block-grid-" ++ show i) smSize
, fmap (\i -> "large-block-grid-" ++ show i) lgSize
]
| otherwise = fail "Grid must have at least a small or a large layout"
uniformGridSize :: Int -> [a] -> Grid a
uniformGridSize smSize = Grid (Just smSize) Nothing
stackGridOnSmall :: Int -> [a] -> Grid a
stackGridOnSmall lgSize = Grid Nothing (Just lgSize)
overrideGridSize :: Int -> Int -> [a] -> Grid a
overrideGridSize smSize lgSize = Grid (Just smSize) (Just lgSize)
-- }}}
| kylcarte/threepenny-extras | src/Foundation/Layout.hs | bsd-3-clause | 4,110 | 0 | 16 | 1,007 | 1,594 | 809 | 785 | 101 | 1 |
{-|
Module : Algebra
Description : Relational algebra operators
Copyright : (c) Janthelme, 2016
License : BDS3
Maintainer : janthelme@gmail.com
Stability : experimental
Portability : POSIX
Implementation of relational algebra and other operators over 'Relvar's as defined in C.J. Date, \"/An Introduction to Database Systems/\" Eighth Edition, chapter 7 (\'Relational Algebra\') .
-}
{-# LANGUAGE FlexibleInstances #-}
module Algebra
( module Relvar,
-- module Attribute,
-- * Types
OpElem (..)
-- * Algebra operators
, union
, intersection
, minus
, times
, restrict
, project
, projectaway
, join
-- * Other operators
, semiJoin
, semiMinus
, extend
, summarize
, group
, ungroup
) where
-- TO DO : clean code. put module the right way. stack?
import Relvar
import qualified Relvar.LSet as LSet hiding (LSet)
import Relvar.LSet (LSet)
-- import Data.Typeable (TypeRep)
import qualified Data.Set as Set (Set, union, intersection, difference, filter, map, empty, member, foldl, elemAt, fromList, toList, partition, singleton)
import Data.List as L (sort, transpose)
-- import Control.Applicative ((<*>), ZipList)
-- | Summarize operators.
data OpElem = Sum
| Count -- ^ Count elements.
| Avg -- ^ Arithmetic Average.
| Max -- ^ Return the maximum element.
| Min -- ^ Return the minimum element.
| Sdev -- ^ Standard deviation.
| Var -- ^ Variance.
deriving (Eq, Show)
-- ======================
-- == Algebra (see C.J. Date)
-- ======================
-- | Union operator.
-- The two relations' attributes must be equal.
union :: Relvar -> Relvar -> Relvar
union r1 r2
| r1 `match` r2 = r1 {rdata = Set.union (rdata r1) (rdata r2)}
| otherwise = error $ errDiffAttr r1 r2
-- | Intersection operator
-- The two relations' attributes must be equal (see 'Relvar.match').
intersection :: Relvar -> Relvar -> Relvar
intersection r1 r2
| r1 `match` r2 = r1 {rdata = Set.intersection (rdata r1) (rdata r2)}
| otherwise = error $ errDiffAttr r1 r2
-- | Difference operator.
-- The two relations' attributes must be equal (see 'Relvar.match').
minus :: Relvar -> Relvar -> Relvar
minus r1 r2
| r1 `match` r2 = r1 {rdata = Set.difference (rdata r1) (rdata r2)}
| otherwise = error $ errDiffAttr r1 r2
-- | Product operator.
-- The two relations' attributes must be disjoint.
times :: Relvar -> Relvar -> Relvar
times r1 r2
| disjoint r1 r2 = Relvar {attributes = prodattr, rdata = proddata}
| otherwise = error $ errCommonAttr r1 r2
where prodattr = LSet.union (attributes r1) (attributes r2)
proddata = flattenSet $ Set.map (\rw -> Set.map (Set.union rw) $ rdata r2) $ rdata r1
-- | Filter a relation's rows given a (Row -> Bool) function
restrict' :: Relvar -> (Row -> Bool) -> Relvar
restrict' r f = r {rdata= Set.filter f (rdata r)}
-- | Filter a relation's rows given a ([Elem] -> Bool) function and a list of attribute names.
restrict :: Relvar -> ([Elem] -> Bool) -> [String] -> Relvar
restrict r f nms = restrict' r (f . (\ls -> LSet.extract True ls nms))
-- CHECK project on missing attributes = DUM?
-- | Projection on a given set of attributes.
-- Only attributes with labels in the provided list are included.
project :: Relvar -> [String] -> Relvar
project r lbls = r {attributes = projattr, rdata = projdata}
where projattr = LSet.project (attributes r) lbls
projdata = Set.map (flip LSet.project lbls) $ rdata r
-- | Projection on a given set of attributes.
-- Attributes with labels matching the list are excluded.
projectaway :: Relvar -> [String] -> Relvar
projectaway r lbls = project r $ LSet.labels $ LSet.projectaway (attributes r) lbls
-- | Natural join operator.
-- The two relations' attributes must not be disjoint.
-- The resulting
join :: Relvar -> Relvar -> Relvar
join r1 r2
| disjoint r1 r2 = times r1 r2
| r1 `match` r2 = intersection r1 r2
| otherwise = Relvar {attributes = joinattr, rdata = joindata}
where cmnlbls = LSet.labels $ common r1 r2 -- common labels (type-checked)
joinattr = LSet.union (attributes r1) (attributes r2)
joindata = flattenSet $ Set.map f $ rdata r1
f rwa = Set.map (Set.union rwa) $ rdata $ restrict2 r2 rwa cmnlbls
-- ======================
-- == Additional Operators (see C.J. Date)
-- ======================
-- | Similar to the join operator projected over the attributes of the first relation.
-- Loosely speaking the results of semiJoin r1 r2 are the rows of r1 which have a counterpart in r2.
--
-- prop> r1 `semiJoin` r2 == project (r1 `join` r2) (labels r1)
semiJoin :: Relvar -> Relvar -> Relvar
semiJoin r1 r2
| disjoint r1 r2 = r1 {rdata = Set.empty}
| r1 `match` r2 = intersection r1 r2
| otherwise = restrict' r1 f
where cmnlbls = LSet.labels $ common r1 r2 -- common labels (type-checked)
target = rdata $ project r2 cmnlbls
f rw = Set.member (LSet.project rw cmnlbls) target
-- | Similar to the minus operator projected over the attributes of the first relation.
-- Loosely speaking the results of semiMinus r1 r2 are the rows of r1 which do not have a counterpart in r2.
--
-- prop> r1 `semiMinus` r2 == project (r1 `minus` r2) (labels r1)
-- prop> r1 `semiMinus` r2 == r1 `minus` (r1 `semiJoin` r2)
semiMinus :: Relvar -> Relvar -> Relvar
semiMinus r1 r2 = minus r1 $ semiJoin r1 r2
-- | Add a derived column to an existing relation.
-- Each element in the new column is the result of a computation of some other columns.
extend :: Relvar -> ([Elem] -> Elem) -> [String] -> String -> Relvar -- CHECK: can extend to several columns?
extend r f inlbls outlbl = Relvar {attributes = LSet.insert outlbl outty $ attributes r, rdata = Set.map (extendRowWith inlbls outlbl f) $ rdata r}
where args0 = LSet.extract True (Set.elemAt 0 $ rdata r) inlbls -- arguments corresponding to the 1st row
outty = typeRep $ f args0 -- this only works for basic types and relations. CHECK: can we do better?
-- FIXME: bug when the lbls do not contain a valid col names. (in fact when project is on invalid column... FIX project)
-- | @summarize r per ops inlbls outlbls@ computes ops over inlbls columns into outlbls column.
summarize :: Relvar -> Relvar -> [OpElem] -> [String] -> [String] -> Relvar
summarize r per ops lbls lbls' = foldl1 union rs
where (rws, rels1) = catalog r per $ compute ops lbls lbls' -- structure : ([per's row], [computation for corresponding row])
rels2 = map (\rw -> per {rdata = Set.fromList [rw]}) rws
rs = zipWith times rels2 rels1
-- CHECK can per and lbls have common labels?
-- CHECK are all compatibility checks done in compute?
-- CHECK improve doc explanations... :(
-- | @group r grplbls reslbl@ returns a relation with all of r's attributes, excluding grplbls columns, plus reslbl column.
-- The elements in reslbl column are of type 'Relvar' and the result of grouping of grplbls columns over the non-grplbls of r.
--
-- prop> degree (group r grplbls reslbl) == degree r - (length grplbls) + 1
group :: Relvar -> [String] -> String -> Relvar
group r grplbls reslbl = Relvar {attributes = LSet.fromList ([reslbl] ++ labels per) ([tyR] ++ types per), rdata = Set.fromList ess}
where per = projectaway r grplbls
(rws, grprels) = catalog r per (flip project grplbls) -- structure : ([per's row], [projection of r on grplbls for corresponding row])
ess = zipWith (\r rw -> LSet.insert reslbl (R r) rw) grprels rws
-- | 'group' inverse operator.
ungroup :: Relvar -> String -> Relvar
ungroup r reslbl
| not $ elem tyR (types' r False [reslbl]) = error $ errNonRelField reslbl
| otherwise = foldl1 union $ zipWith times grprels nongrprels
where -- rws = Set.toList $ rdata r
(grprows, nongrprows) = unzip $ Set.toList $ Set.map (Set.partition ((==reslbl) . fst)) $ rdata r -- structure: [rows of reslbl] and [rows of nongrouplbls]
grprels = map (unboxRel . head . LSet.values) grprows -- structure: [Relvar]
nongrprels = map (\rw-> Relvar {attributes= LSet.delete reslbl $ attributes r, rdata = Set.singleton rw}) nongrprows
-- CHECK reslbl is part of r on implictly done?
-- ======================
-- == Local functions
-- ======================
flattenSet :: Ord a => Set.Set (Set.Set a) -> Set.Set a
flattenSet s = Set.foldl Set.union Set.empty s
-- | restrict rows which match a given target sub-row, over specified labels
restrict2 :: Relvar -> Row -> [String] -> Relvar
restrict2 r target lbls = restrict' r (\rw -> match (LSet.project rw lbls) (LSet.project target lbls))
-- extendRow :: (String, Elem) -> Row -> Row
-- extendRow e rw = Set.union rw $ Set.singleton e
extendRowWith :: [String] -> String -> ([Elem] -> Elem) -> Row -> Row
extendRowWith inlbls outlbl f rw = LSet.insert outlbl (f args) rw
where args = LSet.extract True rw inlbls
-- | compute ops over lbls into lbls'
compute :: [OpElem] -> [String] -> [String] -> Relvar -> Relvar
compute ops lbls lbls' r
| not $ LSet.compatibleLabels False (attributes r) lbls = undefined
| not $ LSet.checkLabels True lbls' = undefined
| (length lbls /= length ops) || (length lbls /= length lbls') = error errSizeMismatch
| otherwise = relvar lbls' tys' ess'
where tys = LSet.extract False (attributes r) lbls
tys' = summaryTy ops tys
ess = elems' r False lbls
ess' = transpose $ map (:[]) $ zipWith ($) (map summaryFn ops) $ transpose ess
-- | fst is the list of all (semiJoin r per) rows and snd is the result of f applied to each corresponding row
catalog :: Relvar -> Relvar -> (Relvar -> a) -> ([Row], [a])
catalog r per f
| False = undefined
| otherwise = (rws, map (f . flter) rws)
where rws = Set.toList (rdata $ semiJoin per r)
flter = \ rw -> restrict2 r rw $ labels per
-- | Types for the summary columns
summaryTy :: [OpElem] -> [TypeRep] -> [TypeRep]
summaryTy ops tys = map (\(t,o) -> if o==Count then tyI else t) $ zip tys ops
-- | Summary function given an OpElem
summaryFn :: OpElem -> ([Elem] -> Elem)
summaryFn ops = case ops of
Count -> countElem
Sum -> sumElem
Avg -> avgElem
Min -> minElem
Max -> maxElem
Sdev -> sdevElem
Var -> varElem
countElem :: [Elem] -> Elem
countElem es = I (length es)
sumElem' :: Elem -> Elem -> Elem
sumElem' (I x) (I y) = I (x+y)
sumElem' (J x) (J y) = J (x+y)
sumElem' (D x) (D y) = D (x+y)
sumElem' _ _ = Nil
sumElem :: [Elem] -> Elem
sumElem = foldl1 sumElem'
avgElem :: [Elem] -> Elem
avgElem es = let s = sumElem es in case s of
I x -> I (x `div` (length es))
J x -> J (x `div` (fromIntegral $ length es))
D x -> D (x / (fromIntegral $ length es))
_ -> Nil
maxElem :: [Elem] -> Elem
maxElem = maximum
minElem :: [Elem] -> Elem
minElem = minimum
varElem :: [Elem] -> Elem
varElem = nilElem -- CHECK - TBI
sdevElem :: [Elem] -> Elem
sdevElem = nilElem -- CHECK - TBI
nilElem :: [Elem] -> Elem
nilElem = const Nil
-- unbox Relvar elements (ugly?)
unboxRel :: Elem -> Relvar
unboxRel (R x) = x
unboxRel _ = dum
-- ======================
-- == Error messages
-- ======================
errDiffAttr :: Relvar -> Relvar -> String
errDiffAttr r1 r2 = "Relations do not have the same attributes : " ++ show (L.sort $ LSet.toList $ attributes r1) ++ " vs " ++ show (L.sort $ LSet.toList $ attributes r2)
errCommonAttr :: Relvar -> Relvar -> String
errCommonAttr r1 r2 = "Relations share common attributes : " ++ show (common r1 r2)
errSizeMismatch :: String
errSizeMismatch = "Size mismatch"
errNonRelField :: String -> String
errNonRelField lbl = "The type associated with the label " ++ lbl ++ " is not Relation"
| JAnthelme/relation-tool | src/Algebra.hs | bsd-3-clause | 12,139 | 0 | 16 | 2,933 | 3,187 | 1,698 | 1,489 | 169 | 7 |
module TPar.Utils where
import Control.Distributed.Process
debugEnabled :: Bool
debugEnabled = False
tparDebug :: String -> Process ()
tparDebug _ | not debugEnabled = return ()
tparDebug s = say s'
where
s' = "tpar: "++s
| bgamari/tpar | TPar/Utils.hs | bsd-3-clause | 232 | 0 | 8 | 45 | 80 | 41 | 39 | 8 | 1 |
-- | Standard pitch representation.
module Music.Pitch (
module Data.Semigroup,
module Data.VectorSpace,
module Data.AffineSpace,
module Data.AffineSpace.Point,
module Music.Pitch.Augmentable,
module Music.Pitch.Alterable,
module Music.Pitch.Absolute,
module Music.Pitch.Common,
module Music.Pitch.Equal,
module Music.Pitch.Clef,
module Music.Pitch.Intonation,
module Music.Pitch.Literal,
module Music.Pitch.Ambitus,
module Music.Pitch.Scale,
) where
import Data.Semigroup
import Data.VectorSpace hiding (Sum, getSum)
import Data.AffineSpace
import Data.AffineSpace.Point
import Music.Pitch.Absolute
import Music.Pitch.Augmentable
import Music.Pitch.Alterable
import Music.Pitch.Ambitus
import Music.Pitch.Equal
import Music.Pitch.Common hiding (Mode)
import Music.Pitch.Common.Names
import Music.Pitch.Literal
import Music.Pitch.Clef
import Music.Pitch.Intonation
import Music.Pitch.Scale
| music-suite/music-pitch | src/Music/Pitch.hs | bsd-3-clause | 1,012 | 0 | 5 | 193 | 208 | 142 | 66 | 30 | 0 |
-- 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.
module Duckling.Time.NL.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Testing.Asserts
import Duckling.Testing.Types
import Duckling.Time.NL.Corpus
import qualified Duckling.Time.NL.BE.Corpus as BE
tests :: TestTree
tests = testGroup "NL Tests"
[ makeCorpusTest [Seal Time] corpus
, makeCorpusTest [Seal Time] latentCorpus
, makeNegativeCorpusTest [Seal Time] negativeCorpus
, localeTests
]
localeTests :: TestTree
localeTests = testGroup "Locale Tests"
[ testGroup "NL_BE Tests"
[ makeCorpusTest [Seal Time] $ withLocale corpus localeBE BE.allExamples
, makeNegativeCorpusTest [Seal Time] $ withLocale negativeCorpus localeBE []
]
]
where
localeBE = makeLocale NL $ Just BE
| facebookincubator/duckling | tests/Duckling/Time/NL/Tests.hs | bsd-3-clause | 1,021 | 0 | 12 | 170 | 222 | 126 | 96 | 23 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
#if __GLASGOW_HASKELL__ <= 800 && __GLASGOW_HASKELL__ >= 706
-- Work around a compiler bug
{-# OPTIONS_GHC -fsimpl-tick-factor=300 #-}
#endif
-- |
-- Module: Data.Aeson.Parser.Internal
-- Copyright: (c) 2011-2016 Bryan O'Sullivan
-- (c) 2011 MailRank, Inc.
-- License: BSD3
-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
-- Stability: experimental
-- Portability: portable
--
-- Efficiently and correctly parse a JSON string. The string must be
-- encoded as UTF-8.
module Data.Aeson.Parser.Internal
(
-- * Lazy parsers
json, jsonEOF
, jsonWith
, jsonLast
, jsonAccum
, jsonNoDup
, value
, jstring
, jstring_
, scientific
-- * Strict parsers
, json', jsonEOF'
, jsonWith'
, jsonLast'
, jsonAccum'
, jsonNoDup'
, value'
-- * Helpers
, decodeWith
, decodeStrictWith
, eitherDecodeWith
, eitherDecodeStrictWith
-- ** Handling objects with duplicate keys
, fromListAccum
, parseListNoDup
) where
import Prelude.Compat
import Control.Applicative ((<|>))
import Control.Monad (void, when)
import Data.Aeson.Types.Internal (IResult(..), JSONPath, Object, Result(..), Value(..), Key)
import qualified Data.Aeson.KeyMap as KM
import qualified Data.Aeson.Key as Key
import Data.Attoparsec.ByteString.Char8 (Parser, char, decimal, endOfInput, isDigit_w8, signed, string)
import Data.Function (fix)
import Data.Functor.Compat (($>))
import Data.Scientific (Scientific)
import Data.Text (Text)
import Data.Vector (Vector)
import qualified Data.Vector as Vector (empty, fromList, fromListN, reverse)
import qualified Data.Attoparsec.ByteString as A
import qualified Data.Attoparsec.Lazy as L
import qualified Data.ByteString as B
import qualified Data.ByteString.Unsafe as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.ByteString.Builder as B
import qualified Data.Scientific as Sci
import Data.Aeson.Parser.Unescape (unescapeText)
import Data.Aeson.Internal.Text
-- $setup
-- >>> :set -XOverloadedStrings
-- >>> import Data.Aeson.Types
#define BACKSLASH 92
#define CLOSE_CURLY 125
#define CLOSE_SQUARE 93
#define COMMA 44
#define DOUBLE_QUOTE 34
#define OPEN_CURLY 123
#define OPEN_SQUARE 91
#define C_0 48
#define C_9 57
#define C_A 65
#define C_F 70
#define C_a 97
#define C_f 102
#define C_n 110
#define C_t 116
-- | Parse any JSON value.
--
-- The conversion of a parsed value to a Haskell value is deferred
-- until the Haskell value is needed. This may improve performance if
-- only a subset of the results of conversions are needed, but at a
-- cost in thunk allocation.
--
-- This function is an alias for 'value'. In aeson 0.8 and earlier, it
-- parsed only object or array types, in conformance with the
-- now-obsolete RFC 4627.
--
-- ==== Warning
--
-- If an object contains duplicate keys, only the first one will be kept.
-- For a more flexible alternative, see 'jsonWith'.
json :: Parser Value
json = value
-- | Parse any JSON value.
--
-- This is a strict version of 'json' which avoids building up thunks
-- during parsing; it performs all conversions immediately. Prefer
-- this version if most of the JSON data needs to be accessed.
--
-- This function is an alias for 'value''. In aeson 0.8 and earlier, it
-- parsed only object or array types, in conformance with the
-- now-obsolete RFC 4627.
--
-- ==== Warning
--
-- If an object contains duplicate keys, only the first one will be kept.
-- For a more flexible alternative, see 'jsonWith''.
json' :: Parser Value
json' = value'
-- Open recursion: object_, object_', array_, array_' are parameterized by the
-- toplevel Value parser to be called recursively, to keep the parameter
-- mkObject outside of the recursive loop for proper inlining.
object_ :: ([(Key, Value)] -> Either String Object) -> Parser Value -> Parser Value
object_ mkObject val = {-# SCC "object_" #-} Object <$> objectValues mkObject key val
{-# INLINE object_ #-}
object_' :: ([(Key, Value)] -> Either String Object) -> Parser Value -> Parser Value
object_' mkObject val' = {-# SCC "object_'" #-} do
!vals <- objectValues mkObject key' val'
return (Object vals)
where
key' = do
!s <- key
return s
{-# INLINE object_' #-}
objectValues :: ([(Key, Value)] -> Either String Object)
-> Parser Key -> Parser Value -> Parser (KM.KeyMap Value)
objectValues mkObject str val = do
skipSpace
w <- A.peekWord8'
if w == CLOSE_CURLY
then A.anyWord8 >> return KM.empty
else loop []
where
-- Why use acc pattern here, you may ask? because then the underlying 'KM.fromList'
-- implementation can make use of mutation when constructing a map. For example,
-- 'HashMap` uses 'unsafeInsert' and it's much faster because it's doing in place
-- update to the 'HashMap'!
loop acc = do
k <- (str A.<?> "object key") <* skipSpace <* (char ':' A.<?> "':'")
v <- (val A.<?> "object value") <* skipSpace
ch <- A.satisfy (\w -> w == COMMA || w == CLOSE_CURLY) A.<?> "',' or '}'"
let acc' = (k, v) : acc
if ch == COMMA
then skipSpace >> loop acc'
else case mkObject acc' of
Left err -> fail err
Right obj -> pure obj
{-# INLINE objectValues #-}
array_ :: Parser Value -> Parser Value
array_ val = {-# SCC "array_" #-} Array <$> arrayValues val
{-# INLINE array_ #-}
array_' :: Parser Value -> Parser Value
array_' val = {-# SCC "array_'" #-} do
!vals <- arrayValues val
return (Array vals)
{-# INLINE array_' #-}
arrayValues :: Parser Value -> Parser (Vector Value)
arrayValues val = do
skipSpace
w <- A.peekWord8'
if w == CLOSE_SQUARE
then A.anyWord8 >> return Vector.empty
else loop [] 1
where
loop acc !len = do
v <- (val A.<?> "json list value") <* skipSpace
ch <- A.satisfy (\w -> w == COMMA || w == CLOSE_SQUARE) A.<?> "',' or ']'"
if ch == COMMA
then skipSpace >> loop (v:acc) (len+1)
else return (Vector.reverse (Vector.fromListN len (v:acc)))
{-# INLINE arrayValues #-}
-- | Parse any JSON value. Synonym of 'json'.
value :: Parser Value
value = jsonWith (pure . KM.fromList)
-- | Parse any JSON value.
--
-- This parser is parameterized by a function to construct an 'Object'
-- from a raw list of key-value pairs, where duplicates are preserved.
-- The pairs appear in __reverse order__ from the source.
--
-- ==== __Examples__
--
-- 'json' keeps only the first occurence of each key, using 'Data.Aeson.KeyMap.fromList'.
--
-- @
-- 'json' = 'jsonWith' ('Right' '.' 'H.fromList')
-- @
--
-- 'jsonLast' keeps the last occurence of each key, using
-- @'HashMap.Lazy.fromListWith' ('const' 'id')@.
--
-- @
-- 'jsonLast' = 'jsonWith' ('Right' '.' 'HashMap.Lazy.fromListWith' ('const' 'id'))
-- @
--
-- 'jsonAccum' keeps wraps all values in arrays to keep duplicates, using
-- 'fromListAccum'.
--
-- @
-- 'jsonAccum' = 'jsonWith' ('Right' . 'fromListAccum')
-- @
--
-- 'jsonNoDup' fails if any object contains duplicate keys, using 'parseListNoDup'.
--
-- @
-- 'jsonNoDup' = 'jsonWith' 'parseListNoDup'
-- @
jsonWith :: ([(Key, Value)] -> Either String Object) -> Parser Value
jsonWith mkObject = fix $ \value_ -> do
skipSpace
w <- A.peekWord8'
case w of
DOUBLE_QUOTE -> A.anyWord8 *> (String <$> jstring_)
OPEN_CURLY -> A.anyWord8 *> object_ mkObject value_
OPEN_SQUARE -> A.anyWord8 *> array_ value_
C_f -> string "false" $> Bool False
C_t -> string "true" $> Bool True
C_n -> string "null" $> Null
_ | w >= 48 && w <= 57 || w == 45
-> Number <$> scientific
| otherwise -> fail "not a valid json value"
{-# INLINE jsonWith #-}
-- | Variant of 'json' which keeps only the last occurence of every key.
jsonLast :: Parser Value
jsonLast = jsonWith (Right . KM.fromListWith (const id))
-- | Variant of 'json' wrapping all object mappings in 'Array' to preserve
-- key-value pairs with the same keys.
jsonAccum :: Parser Value
jsonAccum = jsonWith (Right . fromListAccum)
-- | Variant of 'json' which fails if any object contains duplicate keys.
jsonNoDup :: Parser Value
jsonNoDup = jsonWith parseListNoDup
-- | @'fromListAccum' kvs@ is an object mapping keys to arrays containing all
-- associated values from the original list @kvs@.
--
-- >>> fromListAccum [("apple", Bool True), ("apple", Bool False), ("orange", Bool False)]
-- fromList [("apple",Array [Bool False,Bool True]),("orange",Array [Bool False])]
fromListAccum :: [(Key, Value)] -> Object
fromListAccum =
fmap (Array . Vector.fromList . ($ [])) . KM.fromListWith (.) . (fmap . fmap) (:)
-- | @'fromListNoDup' kvs@ fails if @kvs@ contains duplicate keys.
parseListNoDup :: [(Key, Value)] -> Either String Object
parseListNoDup =
KM.traverseWithKey unwrap . KM.fromListWith (\_ _ -> Nothing) . (fmap . fmap) Just
where
unwrap k Nothing = Left $ "found duplicate key: " ++ show k
unwrap _ (Just v) = Right v
-- | Strict version of 'value'. Synonym of 'json''.
value' :: Parser Value
value' = jsonWith' (pure . KM.fromList)
-- | Strict version of 'jsonWith'.
jsonWith' :: ([(Key, Value)] -> Either String Object) -> Parser Value
jsonWith' mkObject = fix $ \value_ -> do
skipSpace
w <- A.peekWord8'
case w of
DOUBLE_QUOTE -> do
!s <- A.anyWord8 *> jstring_
return (String s)
OPEN_CURLY -> A.anyWord8 *> object_' mkObject value_
OPEN_SQUARE -> A.anyWord8 *> array_' value_
C_f -> string "false" $> Bool False
C_t -> string "true" $> Bool True
C_n -> string "null" $> Null
_ | w >= 48 && w <= 57 || w == 45
-> do
!n <- scientific
return (Number n)
| otherwise -> fail "not a valid json value"
{-# INLINE jsonWith' #-}
-- | Variant of 'json'' which keeps only the last occurence of every key.
jsonLast' :: Parser Value
jsonLast' = jsonWith' (pure . KM.fromListWith (const id))
-- | Variant of 'json'' wrapping all object mappings in 'Array' to preserve
-- key-value pairs with the same keys.
jsonAccum' :: Parser Value
jsonAccum' = jsonWith' (pure . fromListAccum)
-- | Variant of 'json'' which fails if any object contains duplicate keys.
jsonNoDup' :: Parser Value
jsonNoDup' = jsonWith' parseListNoDup
-- | Parse a quoted JSON string.
jstring :: Parser Text
jstring = A.word8 DOUBLE_QUOTE *> jstring_
-- | Parse a JSON Key
key :: Parser Key
key = Key.fromText <$> jstring
-- | Parse a string without a leading quote.
jstring_ :: Parser Text
{-# INLINE jstring_ #-}
jstring_ = do
-- not sure whether >= or bit hackery is faster
-- perfectly, we shouldn't care, it's compiler job.
s <- A.takeWhile (\w -> w /= DOUBLE_QUOTE && w /= BACKSLASH && w >= 0x20 && w < 0x80)
let txt = unsafeDecodeASCII s
mw <- A.peekWord8
case mw of
Nothing -> fail "string without end"
Just DOUBLE_QUOTE -> A.anyWord8 $> txt
Just w | w < 0x20 -> fail "unescaped control character"
_ -> jstringSlow s
jstringSlow :: B.ByteString -> Parser Text
{-# INLINE jstringSlow #-}
jstringSlow s' = {-# SCC "jstringSlow" #-} do
s <- A.scan startState go <* A.anyWord8
case unescapeText (B.append s' s) of
Right r -> return r
Left err -> fail $ show err
where
startState = False
go a c
| a = Just False
| c == DOUBLE_QUOTE = Nothing
| otherwise = let a' = c == backslash
in Just a'
where backslash = BACKSLASH
decodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Maybe a
decodeWith p to s =
case L.parse p s of
L.Done _ v -> case to v of
Success a -> Just a
_ -> Nothing
_ -> Nothing
{-# INLINE decodeWith #-}
decodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString
-> Maybe a
decodeStrictWith p to s =
case either Error to (A.parseOnly p s) of
Success a -> Just a
_ -> Nothing
{-# INLINE decodeStrictWith #-}
eitherDecodeWith :: Parser Value -> (Value -> IResult a) -> L.ByteString
-> Either (JSONPath, String) a
eitherDecodeWith p to s =
case L.parse p s of
L.Done _ v -> case to v of
ISuccess a -> Right a
IError path msg -> Left (path, msg)
L.Fail notparsed ctx msg -> Left ([], buildMsg notparsed ctx msg)
where
buildMsg :: L.ByteString -> [String] -> String -> String
buildMsg notYetParsed [] msg = msg ++ formatErrorLine notYetParsed
buildMsg notYetParsed (expectation:_) msg =
msg ++ ". Expecting " ++ expectation ++ formatErrorLine notYetParsed
{-# INLINE eitherDecodeWith #-}
-- | Grab the first 100 bytes from the non parsed portion and
-- format to get nicer error messages
formatErrorLine :: L.ByteString -> String
formatErrorLine bs =
C.unpack .
-- if formatting results in empty ByteString just return that
-- otherwise construct the error message with the bytestring builder
(\bs' ->
if BSL.null bs'
then BSL.empty
else
B.toLazyByteString $
B.stringUtf8 " at '" <> B.lazyByteString bs' <> B.stringUtf8 "'"
) .
-- if newline is present cut at that position
BSL.takeWhile (10 /=) .
-- remove spaces, CR's, tabs, backslashes and quotes characters
BSL.filter (`notElem` [9, 13, 32, 34, 47, 92]) .
-- take 100 bytes
BSL.take 100 $ bs
eitherDecodeStrictWith :: Parser Value -> (Value -> IResult a) -> B.ByteString
-> Either (JSONPath, String) a
eitherDecodeStrictWith p to s =
case either (IError []) to (A.parseOnly p s) of
ISuccess a -> Right a
IError path msg -> Left (path, msg)
{-# INLINE eitherDecodeStrictWith #-}
-- $lazy
--
-- The 'json' and 'value' parsers decouple identification from
-- conversion. Identification occurs immediately (so that an invalid
-- JSON document can be rejected as early as possible), but conversion
-- to a Haskell value is deferred until that value is needed.
--
-- This decoupling can be time-efficient if only a smallish subset of
-- elements in a JSON value need to be inspected, since the cost of
-- conversion is zero for uninspected elements. The trade off is an
-- increase in memory usage, due to allocation of thunks for values
-- that have not yet been converted.
-- $strict
--
-- The 'json'' and 'value'' parsers combine identification with
-- conversion. They consume more CPU cycles up front, but have a
-- smaller memory footprint.
-- | Parse a top-level JSON value followed by optional whitespace and
-- end-of-input. See also: 'json'.
jsonEOF :: Parser Value
jsonEOF = json <* skipSpace <* endOfInput
-- | Parse a top-level JSON value followed by optional whitespace and
-- end-of-input. See also: 'json''.
jsonEOF' :: Parser Value
jsonEOF' = json' <* skipSpace <* endOfInput
-- | The only valid whitespace in a JSON document is space, newline,
-- carriage return, and tab.
skipSpace :: Parser ()
skipSpace = A.skipWhile $ \w -> w == 0x20 || w == 0x0a || w == 0x0d || w == 0x09
{-# INLINE skipSpace #-}
------------------ Copy-pasted and adapted from attoparsec ------------------
-- A strict pair
data SP = SP !Integer {-# UNPACK #-}!Int
decimal0 :: Parser Integer
decimal0 = do
let zero = 48
digits <- A.takeWhile1 isDigit_w8
if B.length digits > 1 && B.unsafeHead digits == zero
then fail "leading zero"
else return (bsToInteger digits)
-- | Parse a JSON number.
scientific :: Parser Scientific
scientific = do
let minus = 45
plus = 43
sign <- A.peekWord8'
let !positive = sign == plus || sign /= minus
when (sign == plus || sign == minus) $
void A.anyWord8
n <- decimal0
let f fracDigits = SP (B.foldl' step n fracDigits)
(negate $ B.length fracDigits)
step a w = a * 10 + fromIntegral (w - 48)
dotty <- A.peekWord8
-- '.' -> ascii 46
SP c e <- case dotty of
Just 46 -> A.anyWord8 *> (f <$> A.takeWhile1 isDigit_w8)
_ -> pure (SP n 0)
let !signedCoeff | positive = c
| otherwise = -c
let littleE = 101
bigE = 69
(A.satisfy (\ex -> ex == littleE || ex == bigE) *>
fmap (Sci.scientific signedCoeff . (e +)) (signed decimal)) <|>
return (Sci.scientific signedCoeff e)
{-# INLINE scientific #-}
------------------ Copy-pasted and adapted from base ------------------------
bsToInteger :: B.ByteString -> Integer
bsToInteger bs
| l > 40 = valInteger 10 l [ fromIntegral (w - 48) | w <- B.unpack bs ]
| otherwise = bsToIntegerSimple bs
where
l = B.length bs
bsToIntegerSimple :: B.ByteString -> Integer
bsToIntegerSimple = B.foldl' step 0 where
step a b = a * 10 + fromIntegral (b - 48) -- 48 = '0'
-- A sub-quadratic algorithm for Integer. Pairs of adjacent radix b
-- digits are combined into a single radix b^2 digit. This process is
-- repeated until we are left with a single digit. This algorithm
-- performs well only on large inputs, so we use the simple algorithm
-- for smaller inputs.
valInteger :: Integer -> Int -> [Integer] -> Integer
valInteger = go
where
go :: Integer -> Int -> [Integer] -> Integer
go _ _ [] = 0
go _ _ [d] = d
go b l ds
| l > 40 = b' `seq` go b' l' (combine b ds')
| otherwise = valSimple b ds
where
-- ensure that we have an even number of digits
-- before we call combine:
ds' = if even l then ds else 0 : ds
b' = b * b
l' = (l + 1) `quot` 2
combine b (d1 : d2 : ds) = d `seq` (d : combine b ds)
where
d = d1 * b + d2
combine _ [] = []
combine _ [_] = errorWithoutStackTrace "this should not happen"
-- The following algorithm is only linear for types whose Num operations
-- are in constant time.
valSimple :: Integer -> [Integer] -> Integer
valSimple base = go 0
where
go r [] = r
go r (d : ds) = r' `seq` go r' ds
where
r' = r * base + fromIntegral d
| dmjio/aeson | src/Data/Aeson/Parser/Internal.hs | bsd-3-clause | 18,321 | 0 | 19 | 4,351 | 4,211 | 2,243 | 1,968 | 310 | 7 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE CPP #-}
module Facebook.Object.Marketing.AdsPixel where
import Facebook.Records hiding (get)
import qualified Facebook.Records as Rec
import Facebook.Types hiding (Id)
import Facebook.Pager
import Facebook.Monad
import Facebook.Graph
import Facebook.Base (FacebookException(..))
import qualified Data.Aeson as A
import Data.Time.Format
import Data.Aeson hiding (Value)
import Control.Applicative
import Data.Text (Text)
import Data.Text.Read (decimal)
import Data.Scientific (toBoundedInteger)
import qualified Data.Text.Encoding as TE
import GHC.Generics (Generic)
import qualified Data.Map.Strict as Map
import Data.Vector (Vector)
import qualified Data.Vector as V
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Builder as BSB
import qualified Data.ByteString.Lazy as BSL
import qualified Control.Monad.Trans.Resource as R
import Control.Monad.Trans.Control (MonadBaseControl)
#if MIN_VERSION_time(1,5,0)
import System.Locale hiding (defaultTimeLocale, rfc822DateFormat)
import Data.Time.Clock
#else
import System.Locale
import Data.Time.Clock hiding (defaultTimeLocale, rfc822DateFormat)
#endif
import Facebook.Object.Marketing.Types
data Code = Code
newtype Code_ = Code_ Text deriving (Show, Generic)
instance Field Code where
type FieldValue Code = Code_
fieldName _ = "code"
fieldLabel = Code
unCode_ :: Code_ -> Text
unCode_ (Code_ x) = x
instance A.FromJSON Code_
instance A.ToJSON Code_
instance ToBS Code_ where
toBS (Code_ a) = toBS a
code r = r `Rec.get` Code
-- Entity:AdsPixel, mode:Reading
class IsAdsPixelGetField r
instance (IsAdsPixelGetField h, IsAdsPixelGetField t) => IsAdsPixelGetField (h :*: t)
instance IsAdsPixelGetField Nil
instance IsAdsPixelGetField Name
instance IsAdsPixelGetField Code
instance IsAdsPixelGetField Id
type AdsPixelGet fl r = (A.FromJSON r, IsAdsPixelGetField r, FieldListToRec fl r)
type AdsPixelGetRet r = r -- Default fields
getAdsPixel :: (R.MonadResource m, MonadBaseControl IO m, AdsPixelGet fl r) =>
Id_ -- ^ Ad Account Id
-> fl -- ^ Arguments to be passed to Facebook.
-> Maybe UserAccessToken -- ^ Optional user access token.
-> FacebookT anyAuth m (Pager (AdsPixelGetRet r))
getAdsPixel (Id_ id) fl mtoken = getObject ("/v2.7/" <> id <> "/adspixels") [("fields", textListToBS $ fieldNameList $ fl)] mtoken
| BeautifulDestinations/fb | src/Facebook/Object/Marketing/AdsPixel.hs | bsd-3-clause | 2,544 | 0 | 13 | 339 | 630 | 375 | 255 | -1 | -1 |
{-# LANGUAGE GADTs, GeneralizedNewtypeDeriving, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, FlexibleContexts, RankNTypes, MultiParamTypeClasses, FlexibleInstances, ViewPatterns, ImplicitParams, TypeOperators, PackageImports #-}
module HobbitLib (
InList (..),
Nil,Cons,List0,List1,List2,List3,List4,List5,First,Second,Third,Tail,(:++:),
Ctx (CtxNil, CtxCons), ctxAppend, IsAppend (IsAppendBase,IsAppendStep),
Name(), -- hides Name implementation
Binding(), -- hides Binding implementation
Mb(), -- hides MultiBind implementation
nu,
cmpName, (:=:)(TEq), cmpNameBool, mbCmpName, InCtx, cmpInCtx, cmpInCtxBool,
inCtxSameLength,
emptyMb, combineMb, separateMb,
mbInt, mbBool, mbString,
mbToplevel, ToplevelFun, ToplevelRes, topFun,
-- things for using mbMatch
Tag(Tag),FTag(FTag),TFunApply,Repr(Repr),Args(ArgsNil,ArgsCons),ArgsMbMap,
MbMatchable,toRepr,mbCtor,CtorsFun,MatchTpFun,
mbMatch,
-- things for CtxFLists
MapCtx(..), emptyMC, ctxSingle, (|>), (:|>), ctxLookup, ctxMap, (|++>)
) where
import Unsafe.Coerce
import Data.List
import Data.IORef
import System.IO.Unsafe(unsafePerformIO)
import Control.Applicative
--import Test.StrictBench
import "mtl" Control.Monad.Identity(Identity,runIdentity)
import Control.Monad
import Control.DeepSeq
------------------------------------------------------------
-- fresh names
------------------------------------------------------------
type Nametype = Int
counter :: IORef Int
{-# NOINLINE counter #-}
counter = unsafePerformIO (newIORef 0)
fresh_name :: () -> Int
{-# NOINLINE fresh_name #-}
fresh_name () = unsafePerformIO $ do
x <- readIORef counter
writeIORef counter (x+1)
return x
------------------------------------------------------------
-- manipulating lists of types
-- note: we do right on the outside for efficiency of
-- adding a single binder inside another one
------------------------------------------------------------
data Nil
data Cons a l
-- proofs that a type is in a tuple-list of types
data InList ctx a where
InListBase :: InList (Cons a ctx) a
InListStep :: InList ctx a -> InList (Cons b ctx) a
instance Eq (InList ctx a) where
InListBase == InListBase = True
(InListStep p1) == (InListStep p2) = p1 == p2
_ == _ = False
-- phantom type for type lists
data Ctx ctx where
CtxNil :: Ctx Nil
CtxCons :: Tag a -> Ctx l -> Ctx (Cons a l)
-- proofs that a tuple-list of types is the append of two others
data IsAppend ctx1 ctx2 ctx where
IsAppendBase :: IsAppend ctx Nil ctx
IsAppendStep :: IsAppend ctx1 ctx2 ctx -> IsAppend ctx1 (Cons x ctx2) (Cons x ctx)
-- useful helper functions
type List0 = Nil
type List1 a = (Cons a Nil)
type List2 a b = (Cons a (Cons b Nil))
type List3 a b c = (Cons a (Cons b (Cons c Nil)))
type List4 a b c d = (Cons a (Cons b (Cons c (Cons d Nil))))
type List5 a b c d e = (Cons a (Cons b (Cons c (Cons d (Cons e Nil)))))
type family First a
type instance First (Cons a l) = a
type family Second a
type instance Second (Cons a1 (Cons a2 l)) = a2
type family Third a
type instance Third (Cons a1 (Cons a2 (Cons a3 l))) = a3
type family Tail a
type instance Tail (Cons a l) = l
type family (ctx1 :++: ctx2)
type instance ctx1 :++: Nil = ctx1
type instance ctx1 :++: (Cons a ctx2) = (Cons a (ctx1 :++: ctx2))
-- appending two context representations
ctxAppend :: Ctx ctx1 -> Ctx ctx2 -> Ctx (ctx1 :++: ctx2)
ctxAppend ctx1 CtxNil = ctx1
ctxAppend ctx1 (CtxCons tag ctx2) = CtxCons tag (ctxAppend ctx1 ctx2)
-- this is for when we know the ith element of ctx must be type a
unsafeLookupList :: Int -> InList ctx a
unsafeLookupList 0 = unsafeCoerce InListBase
unsafeLookupList n = unsafeCoerce (InListStep (unsafeLookupList (n-1)))
------------------------------------------------------------
-- now we define our data-types
-- under the hood, names are just integers
------------------------------------------------------------
data Name a = MkName (Nametype) deriving Eq
data Mb ctx b = MkMb [Nametype] b deriving Eq
type Binding a = Mb (List1 a)
-- for benchmarking
instance NFData (IORef a) where
rnf ref = ref `seq` ()
instance NFData (Name a) where
rnf (MkName i) = rnf i
-- for benchmarking
instance NFData a => NFData (Mb ctx a) where
rnf (MkMb l x) = rnf l `seq` rnf x
------------------------------------------------------------
-- printing methods
------------------------------------------------------------
-- for printing things (debug only)
{-
instance Show (Name a) where
show (MkName n) = "#" ++ show n ++ "#"
instance Show b => Show (Mb a b) where
show (MkMb l b) = "#" ++ show l ++ "." ++ show b
-}
instance Show b => Show (InList ctx b) where
show InListBase = "InListBase"
show (InListStep pf) = "InListStep (" ++ show pf ++ ")"
------------------------------------------------------------
-- simple operations for creating and manipulating bindings
------------------------------------------------------------
-- nu creates bindings
nu :: (Name a -> b) -> (Binding a b)
nu f = let n = fresh_name () in n `seq` MkMb [n] (f (MkName n))
-- combine binding of a binding into a single binding
-- README: inner-most bindings come FIRST
combineMb :: Mb ctx1 (Mb ctx2 b) -> Mb (ctx1 :++: ctx2) b
combineMb (MkMb l1 (MkMb l2 b)) = MkMb (l2++l1) b
-- separates inner-most binding
-- README: inner-most bindings come FIRST
separateMb :: Ctx ctxOut -> Ctx ctxIn ->
Mb (ctxOut :++: ctxIn) a -> Mb ctxOut (Mb ctxIn a)
separateMb ctxOut ctxIn (MkMb l a) = MkMb lOut (MkMb lIn a)
where (lIn, lOut) = splitAt (ctxLength ctxIn) l
ctxLength :: Ctx ctx -> Int
ctxLength CtxNil = 0
ctxLength (CtxCons a ctx) = 1 + (ctxLength ctx)
{-
separateMb :: IsAppend ctx1 ctx2 ctx -> Mb ctx a -> Mb ctx1 (Mb ctx2 a)
separateMb isapp (MkMb l a) = MkMb l1 (MkMb l2 a)
where (l1, l2) = splitAt (isAppLength isapp) l
isAppLength :: IsAppend ctx1 ctx2 ctx -> Int
isAppLength IsAppendBase = 0
isAppLength (IsAppendStep isapp) = 1 + (isAppLength isapp)
-}
-- make an empty binding
emptyMb :: a -> Mb Nil a
emptyMb t = MkMb [] t
------------------------------------------------------------
-- name-matching operations
------------------------------------------------------------
data a :=: b where
TEq :: (a ~ b) => a :=: b
cmpName :: Name a -> Name b -> Maybe (a :=: b)
cmpName (MkName n1) (MkName n2) =
if n1 == n2 then
Just $ unsafeCoerce TEq
else
Nothing
cmpNameBool :: Name a -> Name b -> Bool
cmpNameBool (MkName n1) (MkName n2) = n1 == n2
-- in normal HobbitLib, InCtx = InList proofs
type InCtx ctx a = InList ctx a
-- comparing bound names using the ordering in the binding context
-- README: InCtxLT means a1 is bound inside of a2
data TpOrd a1 a2 where
TpLT :: TpOrd a1 a2
TpGT :: TpOrd a1 a2
TpEQ :: TpOrd a a
cmpInCtx :: InCtx ctx a1 -> InCtx ctx a2 -> TpOrd a1 a2
cmpInCtx InListBase InListBase = TpEQ
cmpInCtx InListBase (InListStep _) = TpLT
cmpInCtx (InListStep _) InListBase = TpGT
cmpInCtx (InListStep in1) (InListStep in2) = cmpInCtx in1 in2
cmpInCtxBool :: InCtx ctx a1 -> InCtx ctx a2 -> Bool
cmpInCtxBool in1 in2 =
case cmpInCtx in1 in2 of
TpEQ -> True
_ -> False
inCtxSameLength :: InCtx ctx1 a1 -> InCtx ctx2 a2 -> Bool
inCtxSameLength InListBase InListBase = True
inCtxSameLength (InListStep in1) (InListStep in2) = inCtxSameLength in1 in2
inCtxSameLength _ _ = False
-- name_multi_bind_cmp checks if a name is bound in a multi-binding
mbCmpName :: Mb ctx (Name a) -> Either (InCtx ctx a) (Name a)
mbCmpName (MkMb names (MkName n)) =
helper (elemIndex n names)
where helper Nothing = Right (MkName n)
helper (Just i) = Left (unsafeLookupList i)
------------------------------------------------------------
-- applying top-level functions under binders
------------------------------------------------------------
class ToplevelFun tag a where
type ToplevelRes tag a
topFun :: Tag tag -> a -> ToplevelRes tag a
mbToplevel :: ToplevelFun tag a => Tag tag -> Mb ctx a -> Mb ctx (ToplevelRes tag a)
mbToplevel tag (MkMb names i) = MkMb names (topFun tag i)
------------------------------------------------------------
-- special-purpose matching under binders
------------------------------------------------------------
mbInt :: Mb ctx Int -> Int
mbInt (MkMb _ i) = i
mbBool :: Mb ctx Bool -> Bool
mbBool (MkMb _ b) = b
mbString :: Mb ctx String -> String
mbString (MkMb _ str) = str
------------------------------------------------------------
-- generic matching under binders
------------------------------------------------------------
-- for supplying type arguments
data Tag a = Tag
data FTag (f :: * -> *) = FTag
-- user-extensible function for applying the type function ftag to args
type family TFunApply f targs
-- abstract representation of a (G)ADT
data Repr f a where
Repr :: Tag z -> InList (TFunApply f z) (args, a) -> Args args -> Repr f a
-- this is essentially a value representation of a nested tuple type
data Args args where
ArgsNil :: Args List0
ArgsCons :: a -> Args args -> Args (Cons a args)
-- mapping (Mb ctx) over nested arrow types and replacing the ret value with ret
type family ArgsMbMap ctx args ret
type instance ArgsMbMap ctx List0 ret = ret
type instance ArgsMbMap ctx (Cons a args) ret = Mb ctx a -> ArgsMbMap ctx args ret
-- type class stating that FIXME
{-
class MbMatchable (f :: * -> *) where
type CtorsFun f -- type function to get ctors list
type MatchTpFun f :: * -> * -> * -- type function to get match result type
toRepr :: f x -> Repr (CtorsFun f) (f x)
mbCtor :: Tag z -> Tag ctx -> InList (TFunApply (CtorsFun f) z) (args, f x) ->
ArgsMbMap ctx args (MatchTpFun f ctx x)
-}
class MbMatchable a where
type CtorsFun a -- type function to get ctors list
type MatchTpFun a -- type function to get match result type
toRepr :: a -> Repr (CtorsFun a) a
mbCtor :: Tag z -> Tag ctx -> InList (TFunApply (CtorsFun a) z) (args, a) ->
ArgsMbMap ctx args (TFunApply (MatchTpFun a) ctx)
-- matching under bindings
mbMatch :: MbMatchable a => Tag ctx -> Mb ctx a -> TFunApply (MatchTpFun a) ctx
mbMatch ctxT (MkMb names x) =
case toRepr x of
Repr zT in_ctors args ->
argsMapApply ctxT Tag (MkMb names) (mbCtor zT ctxT in_ctors) args
-- helper function for applying a function to arguments
argsMapApply :: Tag ctx -> Tag ret -> (forall x. x -> Mb ctx x) ->
ArgsMbMap ctx args ret -> Args args -> ret
argsMapApply ctxT rT addMb f ArgsNil = f
argsMapApply ctxT rT addMb f (ArgsCons x args) = argsMapApply ctxT rT addMb (f (addMb x)) args
------------------------------------------------------------
-- lists of things that match the context
------------------------------------------------------------
data MapCtx f ctx where
Empty :: MapCtx f Nil
(:>) :: MapCtx f ctx -> f a -> MapCtx f (Cons a ctx)
emptyMC = Empty
(|>) = (:>)
ctxSingle :: f a -> MapCtx f (List1 a)
ctxSingle x = Empty :> x
type ctx :|> a = (Cons a ctx)
ctxLookup :: InCtx ctx a -> MapCtx f ctx -> f a
ctxLookup InListBase (_ :> x) = x
ctxLookup (InListStep p) (xs :> _) = ctxLookup p xs
ctxMap :: (forall x. f x -> g x) -> MapCtx f ctx -> MapCtx g ctx
ctxMap f Empty = Empty
ctxMap f (xs :> x) = (ctxMap f xs) :> (f x)
(|++>) :: MapCtx f ctx1 -> MapCtx f ctx2 -> MapCtx f (ctx1 :++: ctx2)
mc |++> Empty = mc
mc |++> (mc2 :> x) = (mc |++> mc2) :> x
| eddywestbrook/hobbits | archival/HobbitLib.hs | bsd-3-clause | 11,564 | 4 | 14 | 2,332 | 3,299 | 1,785 | 1,514 | -1 | -1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Utils
-- Copyright : (c) The University of Glasgow 2001-2002,
-- Simon Marlow 2003-2006,
-- David Waern 2006-2009
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
module Haddock.Utils (
-- * Misc utilities
restrictTo, emptyHsQTvs,
toDescription, toInstalledDescription,
-- * Filename utilities
moduleHtmlFile, moduleHtmlFile',
contentsHtmlFile, indexHtmlFile,
frameIndexHtmlFile,
moduleIndexFrameName, mainFrameName, synopsisFrameName,
subIndexHtmlFile,
jsFile, framesFile,
-- * Anchor and URL utilities
moduleNameUrl, moduleNameUrl', moduleUrl,
nameAnchorId,
makeAnchorId,
-- * Miscellaneous utilities
getProgramName, bye, die, dieMsg, noDieMsg, mapSnd, mapMaybeM, escapeStr,
-- * HTML cross reference mapping
html_xrefs_ref, html_xrefs_ref',
-- * Doc markup
markup,
idMarkup,
-- * List utilities
replace,
spanWith,
-- * MTL stuff
MonadIO(..),
-- * Logging
parseVerbosity,
out,
-- * System tools
getProcessID
) where
import Haddock.Types
import Haddock.GhcUtils
import GHC
import Name
import Control.Monad ( liftM )
import Data.Char ( isAlpha, isAlphaNum, isAscii, ord, chr )
import Numeric ( showIntAtBase )
import Data.Map ( Map )
import qualified Data.Map as Map hiding ( Map )
import Data.IORef ( IORef, newIORef, readIORef )
import Data.List ( isSuffixOf )
import Data.Maybe ( mapMaybe )
import System.Environment ( getProgName )
import System.Exit
import System.IO ( hPutStr, stderr )
import System.IO.Unsafe ( unsafePerformIO )
import qualified System.FilePath.Posix as HtmlPath
import Distribution.Verbosity
import Distribution.ReadE
#ifndef mingw32_HOST_OS
import qualified System.Posix.Internals
#endif
import MonadUtils ( MonadIO(..) )
--------------------------------------------------------------------------------
-- * Logging
--------------------------------------------------------------------------------
parseVerbosity :: String -> Either String Verbosity
parseVerbosity = runReadE flagToVerbosity
-- | Print a message to stdout, if it is not too verbose
out :: MonadIO m
=> Verbosity -- ^ program verbosity
-> Verbosity -- ^ message verbosity
-> String -> m ()
out progVerbosity msgVerbosity msg
| msgVerbosity <= progVerbosity = liftIO $ putStrLn msg
| otherwise = return ()
--------------------------------------------------------------------------------
-- * Some Utilities
--------------------------------------------------------------------------------
-- | Extract a module's short description.
toDescription :: Interface -> Maybe (Doc Name)
toDescription = hmi_description . ifaceInfo
-- | Extract a module's short description.
toInstalledDescription :: InstalledInterface -> Maybe (Doc Name)
toInstalledDescription = hmi_description . instInfo
--------------------------------------------------------------------------------
-- * Making abstract declarations
--------------------------------------------------------------------------------
restrictTo :: [Name] -> LHsDecl Name -> LHsDecl Name
restrictTo names (L loc decl) = L loc $ case decl of
TyClD d | isDataDecl d ->
TyClD (d { tcdDataDefn = restrictDataDefn names (tcdDataDefn d) })
TyClD d | isClassDecl d ->
TyClD (d { tcdSigs = restrictDecls names (tcdSigs d),
tcdATs = restrictATs names (tcdATs d) })
_ -> decl
restrictDataDefn :: [Name] -> HsDataDefn Name -> HsDataDefn Name
restrictDataDefn names defn@(HsDataDefn { dd_ND = new_or_data, dd_cons = cons })
| DataType <- new_or_data
= defn { dd_cons = restrictCons names cons }
| otherwise -- Newtype
= case restrictCons names cons of
[] -> defn { dd_ND = DataType, dd_cons = [] }
[con] -> defn { dd_cons = [con] }
_ -> error "Should not happen"
restrictCons :: [Name] -> [LConDecl Name] -> [LConDecl Name]
restrictCons names decls = [ L p d | L p (Just d) <- map (fmap keep) decls ]
where
keep d | unLoc (con_name d) `elem` names =
case con_details d of
PrefixCon _ -> Just d
RecCon fields
| all field_avail fields -> Just d
| otherwise -> Just (d { con_details = PrefixCon (field_types fields) })
-- if we have *all* the field names available, then
-- keep the record declaration. Otherwise degrade to
-- a constructor declaration. This isn't quite right, but
-- it's the best we can do.
InfixCon _ _ -> Just d
where
field_avail (ConDeclField n _ _) = unLoc n `elem` names
field_types flds = [ t | ConDeclField _ t _ <- flds ]
keep _ = Nothing
restrictDecls :: [Name] -> [LSig Name] -> [LSig Name]
restrictDecls names = mapMaybe (filterLSigNames (`elem` names))
restrictATs :: [Name] -> [LFamilyDecl Name] -> [LFamilyDecl Name]
restrictATs names ats = [ at | at <- ats , unL (fdLName (unL at)) `elem` names ]
emptyHsQTvs :: LHsTyVarBndrs Name
-- This function is here, rather than in HsTypes, because it *renamed*, but
-- does not necessarily have all the rigt kind variables. It is used
-- in Haddock just for printing, so it doesn't matter
emptyHsQTvs = HsQTvs { hsq_kvs = error "haddock:emptyHsQTvs", hsq_tvs = [] }
--------------------------------------------------------------------------------
-- * Filename mangling functions stolen from s main/DriverUtil.lhs.
--------------------------------------------------------------------------------
baseName :: ModuleName -> FilePath
baseName = map (\c -> if c == '.' then '-' else c) . moduleNameString
moduleHtmlFile :: Module -> FilePath
moduleHtmlFile mdl =
case Map.lookup mdl html_xrefs of
Nothing -> baseName mdl' ++ ".html"
Just fp0 -> HtmlPath.joinPath [fp0, baseName mdl' ++ ".html"]
where
mdl' = moduleName mdl
moduleHtmlFile' :: ModuleName -> FilePath
moduleHtmlFile' mdl =
case Map.lookup mdl html_xrefs' of
Nothing -> baseName mdl ++ ".html"
Just fp0 -> HtmlPath.joinPath [fp0, baseName mdl ++ ".html"]
contentsHtmlFile, indexHtmlFile :: String
contentsHtmlFile = "index.html"
indexHtmlFile = "doc-index.html"
-- | The name of the module index file to be displayed inside a frame.
-- Modules are display in full, but without indentation. Clicking opens in
-- the main window.
frameIndexHtmlFile :: String
frameIndexHtmlFile = "index-frames.html"
moduleIndexFrameName, mainFrameName, synopsisFrameName :: String
moduleIndexFrameName = "modules"
mainFrameName = "main"
synopsisFrameName = "synopsis"
subIndexHtmlFile :: String -> String
subIndexHtmlFile ls = "doc-index-" ++ b ++ ".html"
where b | all isAlpha ls = ls
| otherwise = concatMap (show . ord) ls
-------------------------------------------------------------------------------
-- * Anchor and URL utilities
--
-- NB: Anchor IDs, used as the destination of a link within a document must
-- conform to XML's NAME production. That, taken with XHTML and HTML 4.01's
-- various needs and compatibility constraints, means these IDs have to match:
-- [A-Za-z][A-Za-z0-9:_.-]*
-- Such IDs do not need to be escaped in any way when used as the fragment part
-- of a URL. Indeed, %-escaping them can lead to compatibility issues as it
-- isn't clear if such fragment identifiers should, or should not be unescaped
-- before being matched with IDs in the target document.
-------------------------------------------------------------------------------
moduleUrl :: Module -> String
moduleUrl = moduleHtmlFile
moduleNameUrl :: Module -> OccName -> String
moduleNameUrl mdl n = moduleUrl mdl ++ '#' : nameAnchorId n
moduleNameUrl' :: ModuleName -> OccName -> String
moduleNameUrl' mdl n = moduleHtmlFile' mdl ++ '#' : nameAnchorId n
nameAnchorId :: OccName -> String
nameAnchorId name = makeAnchorId (prefix : ':' : occNameString name)
where prefix | isValOcc name = 'v'
| otherwise = 't'
-- | Takes an arbitrary string and makes it a valid anchor ID. The mapping is
-- identity preserving.
makeAnchorId :: String -> String
makeAnchorId [] = []
makeAnchorId (f:r) = escape isAlpha f ++ concatMap (escape isLegal) r
where
escape p c | p c = [c]
| otherwise = '-' : show (ord c) ++ "-"
isLegal ':' = True
isLegal '_' = True
isLegal '.' = True
isLegal c = isAscii c && isAlphaNum c
-- NB: '-' is legal in IDs, but we use it as the escape char
-------------------------------------------------------------------------------
-- * Files we need to copy from our $libdir
-------------------------------------------------------------------------------
jsFile, framesFile :: String
jsFile = "haddock-util.js"
framesFile = "frames.html"
-------------------------------------------------------------------------------
-- * Misc.
-------------------------------------------------------------------------------
getProgramName :: IO String
getProgramName = liftM (`withoutSuffix` ".bin") getProgName
where str `withoutSuffix` suff
| suff `isSuffixOf` str = take (length str - length suff) str
| otherwise = str
bye :: String -> IO a
bye s = putStr s >> exitSuccess
die :: String -> IO a
die s = hPutStr stderr s >> exitWith (ExitFailure 1)
dieMsg :: String -> IO a
dieMsg s = getProgramName >>= \prog -> die (prog ++ ": " ++ s)
noDieMsg :: String -> IO ()
noDieMsg s = getProgramName >>= \prog -> hPutStr stderr (prog ++ ": " ++ s)
mapSnd :: (b -> c) -> [(a,b)] -> [(a,c)]
mapSnd _ [] = []
mapSnd f ((x,y):xs) = (x,f y) : mapSnd f xs
mapMaybeM :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b)
mapMaybeM _ Nothing = return Nothing
mapMaybeM f (Just a) = liftM Just (f a)
escapeStr :: String -> String
escapeStr = escapeURIString isUnreserved
-- Following few functions are copy'n'pasted from Network.URI module
-- to avoid depending on the network lib, since doing so gives a
-- circular build dependency between haddock and network
-- (at least if you want to build network with haddock docs)
escapeURIChar :: (Char -> Bool) -> Char -> String
escapeURIChar p c
| p c = [c]
| otherwise = '%' : myShowHex (ord c) ""
where
myShowHex :: Int -> ShowS
myShowHex n r = case showIntAtBase 16 toChrHex n r of
[] -> "00"
[a] -> ['0',a]
cs -> cs
toChrHex d
| d < 10 = chr (ord '0' + fromIntegral d)
| otherwise = chr (ord 'A' + fromIntegral (d - 10))
escapeURIString :: (Char -> Bool) -> String -> String
escapeURIString = concatMap . escapeURIChar
isUnreserved :: Char -> Bool
isUnreserved c = isAlphaNumChar c || (c `elem` "-_.~")
isAlphaChar, isDigitChar, isAlphaNumChar :: Char -> Bool
isAlphaChar c = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
isDigitChar c = c >= '0' && c <= '9'
isAlphaNumChar c = isAlphaChar c || isDigitChar c
-----------------------------------------------------------------------------
-- * HTML cross references
--
-- For each module, we need to know where its HTML documentation lives
-- so that we can point hyperlinks to it. It is extremely
-- inconvenient to plumb this information to all the places that need
-- it (basically every function in HaddockHtml), and furthermore the
-- mapping is constant for any single run of Haddock. So for the time
-- being I'm going to use a write-once global variable.
-----------------------------------------------------------------------------
{-# NOINLINE html_xrefs_ref #-}
html_xrefs_ref :: IORef (Map Module FilePath)
html_xrefs_ref = unsafePerformIO (newIORef (error "module_map"))
{-# NOINLINE html_xrefs_ref' #-}
html_xrefs_ref' :: IORef (Map ModuleName FilePath)
html_xrefs_ref' = unsafePerformIO (newIORef (error "module_map"))
{-# NOINLINE html_xrefs #-}
html_xrefs :: Map Module FilePath
html_xrefs = unsafePerformIO (readIORef html_xrefs_ref)
{-# NOINLINE html_xrefs' #-}
html_xrefs' :: Map ModuleName FilePath
html_xrefs' = unsafePerformIO (readIORef html_xrefs_ref')
-----------------------------------------------------------------------------
-- * List utils
-----------------------------------------------------------------------------
replace :: Eq a => a -> a -> [a] -> [a]
replace a b = map (\x -> if x == a then b else x)
spanWith :: (a -> Maybe b) -> [a] -> ([b],[a])
spanWith _ [] = ([],[])
spanWith p xs@(a:as)
| Just b <- p a = let (bs,cs) = spanWith p as in (b:bs,cs)
| otherwise = ([],xs)
-----------------------------------------------------------------------------
-- * Put here temporarily
-----------------------------------------------------------------------------
markup :: DocMarkup id a -> Doc id -> a
markup m DocEmpty = markupEmpty m
markup m (DocAppend d1 d2) = markupAppend m (markup m d1) (markup m d2)
markup m (DocString s) = markupString m s
markup m (DocParagraph d) = markupParagraph m (markup m d)
markup m (DocIdentifier x) = markupIdentifier m x
markup m (DocIdentifierUnchecked x) = markupIdentifierUnchecked m x
markup m (DocModule mod0) = markupModule m mod0
markup m (DocWarning d) = markupWarning m (markup m d)
markup m (DocEmphasis d) = markupEmphasis m (markup m d)
markup m (DocBold d) = markupBold m (markup m d)
markup m (DocMonospaced d) = markupMonospaced m (markup m d)
markup m (DocUnorderedList ds) = markupUnorderedList m (map (markup m) ds)
markup m (DocOrderedList ds) = markupOrderedList m (map (markup m) ds)
markup m (DocDefList ds) = markupDefList m (map (markupPair m) ds)
markup m (DocCodeBlock d) = markupCodeBlock m (markup m d)
markup m (DocHyperlink l) = markupHyperlink m l
markup m (DocAName ref) = markupAName m ref
markup m (DocPic img) = markupPic m img
markup m (DocProperty p) = markupProperty m p
markup m (DocExamples e) = markupExample m e
markup m (DocHeader (Header l t)) = markupHeader m (Header l (markup m t))
markupPair :: DocMarkup id a -> (Doc id, Doc id) -> (a, a)
markupPair m (a,b) = (markup m a, markup m b)
-- | The identity markup
idMarkup :: DocMarkup a (Doc a)
idMarkup = Markup {
markupEmpty = DocEmpty,
markupString = DocString,
markupParagraph = DocParagraph,
markupAppend = DocAppend,
markupIdentifier = DocIdentifier,
markupIdentifierUnchecked = DocIdentifierUnchecked,
markupModule = DocModule,
markupWarning = DocWarning,
markupEmphasis = DocEmphasis,
markupBold = DocBold,
markupMonospaced = DocMonospaced,
markupUnorderedList = DocUnorderedList,
markupOrderedList = DocOrderedList,
markupDefList = DocDefList,
markupCodeBlock = DocCodeBlock,
markupHyperlink = DocHyperlink,
markupAName = DocAName,
markupPic = DocPic,
markupProperty = DocProperty,
markupExample = DocExamples,
markupHeader = DocHeader
}
-----------------------------------------------------------------------------
-- * System tools
-----------------------------------------------------------------------------
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
#else
getProcessID :: IO Int
getProcessID = fmap fromIntegral System.Posix.Internals.c_getpid
#endif
| jwiegley/ghc-release | utils/haddock/src/Haddock/Utils.hs | gpl-3.0 | 15,848 | 0 | 18 | 3,355 | 3,835 | 2,051 | 1,784 | 249 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ECS.Types.Product
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.ECS.Types.Product where
import Network.AWS.ECS.Types.Sum
import Network.AWS.Prelude
-- | A regional grouping of one or more container instances on which you can
-- run task requests. Each account receives a default cluster the first
-- time you use the Amazon ECS service, but you may also create other
-- clusters. Clusters may contain more than one instance type
-- simultaneously.
--
-- /See:/ 'cluster' smart constructor.
data Cluster = Cluster'
{ _cStatus :: !(Maybe Text)
, _cClusterARN :: !(Maybe Text)
, _cRunningTasksCount :: !(Maybe Int)
, _cRegisteredContainerInstancesCount :: !(Maybe Int)
, _cPendingTasksCount :: !(Maybe Int)
, _cClusterName :: !(Maybe Text)
, _cActiveServicesCount :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Cluster' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cStatus'
--
-- * 'cClusterARN'
--
-- * 'cRunningTasksCount'
--
-- * 'cRegisteredContainerInstancesCount'
--
-- * 'cPendingTasksCount'
--
-- * 'cClusterName'
--
-- * 'cActiveServicesCount'
cluster
:: Cluster
cluster =
Cluster'
{ _cStatus = Nothing
, _cClusterARN = Nothing
, _cRunningTasksCount = Nothing
, _cRegisteredContainerInstancesCount = Nothing
, _cPendingTasksCount = Nothing
, _cClusterName = Nothing
, _cActiveServicesCount = Nothing
}
-- | The status of the cluster. The valid values are 'ACTIVE' or 'INACTIVE'.
-- 'ACTIVE' indicates that you can register container instances with the
-- cluster and the associated instances can accept tasks.
cStatus :: Lens' Cluster (Maybe Text)
cStatus = lens _cStatus (\ s a -> s{_cStatus = a});
-- | The Amazon Resource Name (ARN) that identifies the cluster. The ARN
-- contains the 'arn:aws:ecs' namespace, followed by the region of the
-- cluster, the AWS account ID of the cluster owner, the 'cluster'
-- namespace, and then the cluster name. For example,
-- arn:aws:ecs:/region/:/012345678910/:cluster\//test/.
cClusterARN :: Lens' Cluster (Maybe Text)
cClusterARN = lens _cClusterARN (\ s a -> s{_cClusterARN = a});
-- | The number of tasks in the cluster that are in the 'RUNNING' state.
cRunningTasksCount :: Lens' Cluster (Maybe Int)
cRunningTasksCount = lens _cRunningTasksCount (\ s a -> s{_cRunningTasksCount = a});
-- | The number of container instances registered into the cluster.
cRegisteredContainerInstancesCount :: Lens' Cluster (Maybe Int)
cRegisteredContainerInstancesCount = lens _cRegisteredContainerInstancesCount (\ s a -> s{_cRegisteredContainerInstancesCount = a});
-- | The number of tasks in the cluster that are in the 'PENDING' state.
cPendingTasksCount :: Lens' Cluster (Maybe Int)
cPendingTasksCount = lens _cPendingTasksCount (\ s a -> s{_cPendingTasksCount = a});
-- | A user-generated string that you can use to identify your cluster.
cClusterName :: Lens' Cluster (Maybe Text)
cClusterName = lens _cClusterName (\ s a -> s{_cClusterName = a});
-- | The number of services that are running on the cluster in an 'ACTIVE'
-- state. You can view these services with ListServices.
cActiveServicesCount :: Lens' Cluster (Maybe Int)
cActiveServicesCount = lens _cActiveServicesCount (\ s a -> s{_cActiveServicesCount = a});
instance FromJSON Cluster where
parseJSON
= withObject "Cluster"
(\ x ->
Cluster' <$>
(x .:? "status") <*> (x .:? "clusterArn") <*>
(x .:? "runningTasksCount")
<*> (x .:? "registeredContainerInstancesCount")
<*> (x .:? "pendingTasksCount")
<*> (x .:? "clusterName")
<*> (x .:? "activeServicesCount"))
-- | A docker container that is part of a task.
--
-- /See:/ 'container' smart constructor.
data Container = Container'
{ _cNetworkBindings :: !(Maybe [NetworkBinding])
, _cContainerARN :: !(Maybe Text)
, _cTaskARN :: !(Maybe Text)
, _cLastStatus :: !(Maybe Text)
, _cReason :: !(Maybe Text)
, _cName :: !(Maybe Text)
, _cExitCode :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Container' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cNetworkBindings'
--
-- * 'cContainerARN'
--
-- * 'cTaskARN'
--
-- * 'cLastStatus'
--
-- * 'cReason'
--
-- * 'cName'
--
-- * 'cExitCode'
container
:: Container
container =
Container'
{ _cNetworkBindings = Nothing
, _cContainerARN = Nothing
, _cTaskARN = Nothing
, _cLastStatus = Nothing
, _cReason = Nothing
, _cName = Nothing
, _cExitCode = Nothing
}
-- | The network bindings associated with the container.
cNetworkBindings :: Lens' Container [NetworkBinding]
cNetworkBindings = lens _cNetworkBindings (\ s a -> s{_cNetworkBindings = a}) . _Default . _Coerce;
-- | The Amazon Resource Name (ARN) of the container.
cContainerARN :: Lens' Container (Maybe Text)
cContainerARN = lens _cContainerARN (\ s a -> s{_cContainerARN = a});
-- | The Amazon Resource Name (ARN) of the task.
cTaskARN :: Lens' Container (Maybe Text)
cTaskARN = lens _cTaskARN (\ s a -> s{_cTaskARN = a});
-- | The last known status of the container.
cLastStatus :: Lens' Container (Maybe Text)
cLastStatus = lens _cLastStatus (\ s a -> s{_cLastStatus = a});
-- | A short (255 max characters) human-readable string to provide additional
-- detail about a running or stopped container.
cReason :: Lens' Container (Maybe Text)
cReason = lens _cReason (\ s a -> s{_cReason = a});
-- | The name of the container.
cName :: Lens' Container (Maybe Text)
cName = lens _cName (\ s a -> s{_cName = a});
-- | The exit code returned from the container.
cExitCode :: Lens' Container (Maybe Int)
cExitCode = lens _cExitCode (\ s a -> s{_cExitCode = a});
instance FromJSON Container where
parseJSON
= withObject "Container"
(\ x ->
Container' <$>
(x .:? "networkBindings" .!= mempty) <*>
(x .:? "containerArn")
<*> (x .:? "taskArn")
<*> (x .:? "lastStatus")
<*> (x .:? "reason")
<*> (x .:? "name")
<*> (x .:? "exitCode"))
-- | Container definitions are used in task definitions to describe the
-- different containers that are launched as part of a task.
--
-- /See:/ 'containerDefinition' smart constructor.
data ContainerDefinition = ContainerDefinition'
{ _cdImage :: !(Maybe Text)
, _cdCommand :: !(Maybe [Text])
, _cdVolumesFrom :: !(Maybe [VolumeFrom])
, _cdEnvironment :: !(Maybe [KeyValuePair])
, _cdEntryPoint :: !(Maybe [Text])
, _cdPortMappings :: !(Maybe [PortMapping])
, _cdMemory :: !(Maybe Int)
, _cdName :: !(Maybe Text)
, _cdMountPoints :: !(Maybe [MountPoint])
, _cdLinks :: !(Maybe [Text])
, _cdEssential :: !(Maybe Bool)
, _cdCpu :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ContainerDefinition' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdImage'
--
-- * 'cdCommand'
--
-- * 'cdVolumesFrom'
--
-- * 'cdEnvironment'
--
-- * 'cdEntryPoint'
--
-- * 'cdPortMappings'
--
-- * 'cdMemory'
--
-- * 'cdName'
--
-- * 'cdMountPoints'
--
-- * 'cdLinks'
--
-- * 'cdEssential'
--
-- * 'cdCpu'
containerDefinition
:: ContainerDefinition
containerDefinition =
ContainerDefinition'
{ _cdImage = Nothing
, _cdCommand = Nothing
, _cdVolumesFrom = Nothing
, _cdEnvironment = Nothing
, _cdEntryPoint = Nothing
, _cdPortMappings = Nothing
, _cdMemory = Nothing
, _cdName = Nothing
, _cdMountPoints = Nothing
, _cdLinks = Nothing
, _cdEssential = Nothing
, _cdCpu = Nothing
}
-- | The image used to start a container. This string is passed directly to
-- the Docker daemon. Images in the Docker Hub registry are available by
-- default. Other repositories are specified with
-- 'repository-url\/image:tag'.
cdImage :: Lens' ContainerDefinition (Maybe Text)
cdImage = lens _cdImage (\ s a -> s{_cdImage = a});
-- | The 'CMD' that is passed to the container. For more information on the
-- Docker 'CMD' parameter, see
-- <https://docs.docker.com/reference/builder/#cmd>.
cdCommand :: Lens' ContainerDefinition [Text]
cdCommand = lens _cdCommand (\ s a -> s{_cdCommand = a}) . _Default . _Coerce;
-- | Data volumes to mount from another container.
cdVolumesFrom :: Lens' ContainerDefinition [VolumeFrom]
cdVolumesFrom = lens _cdVolumesFrom (\ s a -> s{_cdVolumesFrom = a}) . _Default . _Coerce;
-- | The environment variables to pass to a container.
cdEnvironment :: Lens' ContainerDefinition [KeyValuePair]
cdEnvironment = lens _cdEnvironment (\ s a -> s{_cdEnvironment = a}) . _Default . _Coerce;
-- | Early versions of the Amazon ECS container agent do not properly handle
-- 'entryPoint' parameters. If you have problems using 'entryPoint', update
-- your container agent or enter your commands and arguments as 'command'
-- array items instead.
--
-- The 'ENTRYPOINT' that is passed to the container. For more information
-- on the Docker 'ENTRYPOINT' parameter, see
-- <https://docs.docker.com/reference/builder/#entrypoint>.
cdEntryPoint :: Lens' ContainerDefinition [Text]
cdEntryPoint = lens _cdEntryPoint (\ s a -> s{_cdEntryPoint = a}) . _Default . _Coerce;
-- | The list of port mappings for the container.
cdPortMappings :: Lens' ContainerDefinition [PortMapping]
cdPortMappings = lens _cdPortMappings (\ s a -> s{_cdPortMappings = a}) . _Default . _Coerce;
-- | The number of MiB of memory reserved for the container. If your
-- container attempts to exceed the memory allocated here, the container is
-- killed.
cdMemory :: Lens' ContainerDefinition (Maybe Int)
cdMemory = lens _cdMemory (\ s a -> s{_cdMemory = a});
-- | The name of a container. If you are linking multiple containers together
-- in a task definition, the 'name' of one container can be entered in the
-- 'links' of another container to connect the containers.
cdName :: Lens' ContainerDefinition (Maybe Text)
cdName = lens _cdName (\ s a -> s{_cdName = a});
-- | The mount points for data volumes in your container.
cdMountPoints :: Lens' ContainerDefinition [MountPoint]
cdMountPoints = lens _cdMountPoints (\ s a -> s{_cdMountPoints = a}) . _Default . _Coerce;
-- | The 'link' parameter allows containers to communicate with each other
-- without the need for port mappings, using the 'name' parameter. The
-- 'name:internalName' construct is analogous to 'name:alias' in Docker
-- links. For more information on linking Docker containers, see
-- <https://docs.docker.com/userguide/dockerlinks/>.
--
-- Containers that are collocated on a single container instance may be
-- able to communicate with each other without requiring links or host port
-- mappings. Network isolation is achieved on the container instance using
-- security groups and VPC settings.
cdLinks :: Lens' ContainerDefinition [Text]
cdLinks = lens _cdLinks (\ s a -> s{_cdLinks = a}) . _Default . _Coerce;
-- | If the 'essential' parameter of a container is marked as 'true', the
-- failure of that container will stop the task. If the 'essential'
-- parameter of a container is marked as 'false', then its failure will not
-- affect the rest of the containers in a task. If this parameter is
-- omitted, a container is assumed to be essential.
--
-- All tasks must have at least one essential container.
cdEssential :: Lens' ContainerDefinition (Maybe Bool)
cdEssential = lens _cdEssential (\ s a -> s{_cdEssential = a});
-- | The number of 'cpu' units reserved for the container. A container
-- instance has 1,024 'cpu' units for every CPU core. This parameter
-- specifies the minimum amount of CPU to reserve for a container, and
-- containers share unallocated CPU units with other containers on the
-- instance with the same ratio as their allocated amount.
--
-- For example, if you run a single-container task on a single-core
-- instance type with 512 CPU units specified for that container, and that
-- is the only task running on the container instance, that container could
-- use the full 1,024 CPU unit share at any given time. However, if you
-- launched another copy of the same task on that container instance, each
-- task would be guaranteed a minimum of 512 CPU units when needed, and
-- each container could float to higher CPU usage if the other container
-- was not using it, but if both tasks were 100% active all of the time,
-- they would be limited to 512 CPU units.
--
-- The Docker daemon on the container instance uses the CPU value to
-- calculate the relative CPU share ratios for running containers. For more
-- information, see
-- <https://docs.docker.com/reference/run/#cpu-share-constraint CPU share constraint>
-- in the Docker documentation. The minimum valid CPU share value that the
-- Linux kernel will allow is 2; however, the CPU parameter is not
-- required, and you can use CPU values below 2 in your container
-- definitions. For CPU values below 2 (including null), the behavior
-- varies based on your Amazon ECS container agent version:
--
-- - __Agent versions less than or equal to 1.1.0:__ Null and zero CPU
-- values are passed to Docker as 0, which Docker then converts to
-- 1,024 CPU shares. CPU values of 1 are passed to Docker as 1, which
-- the Linux kernel converts to 2 CPU shares.
-- - __Agent versions greater than or equal to 1.2.0:__ Null, zero, and
-- CPU values of 1 are passed to Docker as 2.
cdCpu :: Lens' ContainerDefinition (Maybe Int)
cdCpu = lens _cdCpu (\ s a -> s{_cdCpu = a});
instance FromJSON ContainerDefinition where
parseJSON
= withObject "ContainerDefinition"
(\ x ->
ContainerDefinition' <$>
(x .:? "image") <*> (x .:? "command" .!= mempty) <*>
(x .:? "volumesFrom" .!= mempty)
<*> (x .:? "environment" .!= mempty)
<*> (x .:? "entryPoint" .!= mempty)
<*> (x .:? "portMappings" .!= mempty)
<*> (x .:? "memory")
<*> (x .:? "name")
<*> (x .:? "mountPoints" .!= mempty)
<*> (x .:? "links" .!= mempty)
<*> (x .:? "essential")
<*> (x .:? "cpu"))
instance ToJSON ContainerDefinition where
toJSON ContainerDefinition'{..}
= object
(catMaybes
[("image" .=) <$> _cdImage,
("command" .=) <$> _cdCommand,
("volumesFrom" .=) <$> _cdVolumesFrom,
("environment" .=) <$> _cdEnvironment,
("entryPoint" .=) <$> _cdEntryPoint,
("portMappings" .=) <$> _cdPortMappings,
("memory" .=) <$> _cdMemory, ("name" .=) <$> _cdName,
("mountPoints" .=) <$> _cdMountPoints,
("links" .=) <$> _cdLinks,
("essential" .=) <$> _cdEssential,
("cpu" .=) <$> _cdCpu])
-- | An Amazon EC2 instance that is running the Amazon ECS agent and has been
-- registered with a cluster.
--
-- /See:/ 'containerInstance' smart constructor.
data ContainerInstance = ContainerInstance'
{ _ciStatus :: !(Maybe Text)
, _ciRunningTasksCount :: !(Maybe Int)
, _ciRemainingResources :: !(Maybe [Resource])
, _ciEc2InstanceId :: !(Maybe Text)
, _ciContainerInstanceARN :: !(Maybe Text)
, _ciAgentConnected :: !(Maybe Bool)
, _ciVersionInfo :: !(Maybe VersionInfo)
, _ciAgentUpdateStatus :: !(Maybe AgentUpdateStatus)
, _ciPendingTasksCount :: !(Maybe Int)
, _ciRegisteredResources :: !(Maybe [Resource])
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ContainerInstance' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ciStatus'
--
-- * 'ciRunningTasksCount'
--
-- * 'ciRemainingResources'
--
-- * 'ciEc2InstanceId'
--
-- * 'ciContainerInstanceARN'
--
-- * 'ciAgentConnected'
--
-- * 'ciVersionInfo'
--
-- * 'ciAgentUpdateStatus'
--
-- * 'ciPendingTasksCount'
--
-- * 'ciRegisteredResources'
containerInstance
:: ContainerInstance
containerInstance =
ContainerInstance'
{ _ciStatus = Nothing
, _ciRunningTasksCount = Nothing
, _ciRemainingResources = Nothing
, _ciEc2InstanceId = Nothing
, _ciContainerInstanceARN = Nothing
, _ciAgentConnected = Nothing
, _ciVersionInfo = Nothing
, _ciAgentUpdateStatus = Nothing
, _ciPendingTasksCount = Nothing
, _ciRegisteredResources = Nothing
}
-- | The status of the container instance. The valid values are 'ACTIVE' or
-- 'INACTIVE'. 'ACTIVE' indicates that the container instance can accept
-- tasks.
ciStatus :: Lens' ContainerInstance (Maybe Text)
ciStatus = lens _ciStatus (\ s a -> s{_ciStatus = a});
-- | The number of tasks on the container instance that are in the 'RUNNING'
-- status.
ciRunningTasksCount :: Lens' ContainerInstance (Maybe Int)
ciRunningTasksCount = lens _ciRunningTasksCount (\ s a -> s{_ciRunningTasksCount = a});
-- | The remaining resources of the container instance that are available for
-- new tasks.
ciRemainingResources :: Lens' ContainerInstance [Resource]
ciRemainingResources = lens _ciRemainingResources (\ s a -> s{_ciRemainingResources = a}) . _Default . _Coerce;
-- | The Amazon EC2 instance ID of the container instance.
ciEc2InstanceId :: Lens' ContainerInstance (Maybe Text)
ciEc2InstanceId = lens _ciEc2InstanceId (\ s a -> s{_ciEc2InstanceId = a});
-- | The Amazon Resource Name (ARN) of the container instance. The ARN
-- contains the 'arn:aws:ecs' namespace, followed by the region of the
-- container instance, the AWS account ID of the container instance owner,
-- the 'container-instance' namespace, and then the container instance
-- UUID. For example,
-- arn:aws:ecs:/region/:/aws_account_id/:container-instance\//container_instance_UUID/.
ciContainerInstanceARN :: Lens' ContainerInstance (Maybe Text)
ciContainerInstanceARN = lens _ciContainerInstanceARN (\ s a -> s{_ciContainerInstanceARN = a});
-- | This parameter returns 'true' if the agent is actually connected to
-- Amazon ECS. Registered instances with an agent that may be unhealthy or
-- stopped will return 'false', and instances without a connected agent
-- cannot accept placement request.
ciAgentConnected :: Lens' ContainerInstance (Maybe Bool)
ciAgentConnected = lens _ciAgentConnected (\ s a -> s{_ciAgentConnected = a});
-- | The version information for the Amazon ECS container agent and Docker
-- daemon running on the container instance.
ciVersionInfo :: Lens' ContainerInstance (Maybe VersionInfo)
ciVersionInfo = lens _ciVersionInfo (\ s a -> s{_ciVersionInfo = a});
-- | The status of the most recent agent update. If an update has never been
-- requested, this value is 'NULL'.
ciAgentUpdateStatus :: Lens' ContainerInstance (Maybe AgentUpdateStatus)
ciAgentUpdateStatus = lens _ciAgentUpdateStatus (\ s a -> s{_ciAgentUpdateStatus = a});
-- | The number of tasks on the container instance that are in the 'PENDING'
-- status.
ciPendingTasksCount :: Lens' ContainerInstance (Maybe Int)
ciPendingTasksCount = lens _ciPendingTasksCount (\ s a -> s{_ciPendingTasksCount = a});
-- | The registered resources on the container instance that are in use by
-- current tasks.
ciRegisteredResources :: Lens' ContainerInstance [Resource]
ciRegisteredResources = lens _ciRegisteredResources (\ s a -> s{_ciRegisteredResources = a}) . _Default . _Coerce;
instance FromJSON ContainerInstance where
parseJSON
= withObject "ContainerInstance"
(\ x ->
ContainerInstance' <$>
(x .:? "status") <*> (x .:? "runningTasksCount") <*>
(x .:? "remainingResources" .!= mempty)
<*> (x .:? "ec2InstanceId")
<*> (x .:? "containerInstanceArn")
<*> (x .:? "agentConnected")
<*> (x .:? "versionInfo")
<*> (x .:? "agentUpdateStatus")
<*> (x .:? "pendingTasksCount")
<*> (x .:? "registeredResources" .!= mempty))
-- | The overrides that should be sent to a container.
--
-- /See:/ 'containerOverride' smart constructor.
data ContainerOverride = ContainerOverride'
{ _coCommand :: !(Maybe [Text])
, _coEnvironment :: !(Maybe [KeyValuePair])
, _coName :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ContainerOverride' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'coCommand'
--
-- * 'coEnvironment'
--
-- * 'coName'
containerOverride
:: ContainerOverride
containerOverride =
ContainerOverride'
{ _coCommand = Nothing
, _coEnvironment = Nothing
, _coName = Nothing
}
-- | The command to send to the container that overrides the default command
-- from the Docker image or the task definition.
coCommand :: Lens' ContainerOverride [Text]
coCommand = lens _coCommand (\ s a -> s{_coCommand = a}) . _Default . _Coerce;
-- | The environment variables to send to the container. You can add new
-- environment variables, which are added to the container at launch, or
-- you can override the existing environment variables from the Docker
-- image or the task definition.
coEnvironment :: Lens' ContainerOverride [KeyValuePair]
coEnvironment = lens _coEnvironment (\ s a -> s{_coEnvironment = a}) . _Default . _Coerce;
-- | The name of the container that receives the override.
coName :: Lens' ContainerOverride (Maybe Text)
coName = lens _coName (\ s a -> s{_coName = a});
instance FromJSON ContainerOverride where
parseJSON
= withObject "ContainerOverride"
(\ x ->
ContainerOverride' <$>
(x .:? "command" .!= mempty) <*>
(x .:? "environment" .!= mempty)
<*> (x .:? "name"))
instance ToJSON ContainerOverride where
toJSON ContainerOverride'{..}
= object
(catMaybes
[("command" .=) <$> _coCommand,
("environment" .=) <$> _coEnvironment,
("name" .=) <$> _coName])
-- | Details on a service within a cluster
--
-- /See:/ 'containerService' smart constructor.
data ContainerService = ContainerService'
{ _csRunningCount :: !(Maybe Int)
, _csStatus :: !(Maybe Text)
, _csClusterARN :: !(Maybe Text)
, _csDesiredCount :: !(Maybe Int)
, _csLoadBalancers :: !(Maybe [LoadBalancer])
, _csPendingCount :: !(Maybe Int)
, _csEvents :: !(Maybe [ServiceEvent])
, _csDeployments :: !(Maybe [Deployment])
, _csServiceName :: !(Maybe Text)
, _csServiceARN :: !(Maybe Text)
, _csTaskDefinition :: !(Maybe Text)
, _csRoleARN :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ContainerService' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csRunningCount'
--
-- * 'csStatus'
--
-- * 'csClusterARN'
--
-- * 'csDesiredCount'
--
-- * 'csLoadBalancers'
--
-- * 'csPendingCount'
--
-- * 'csEvents'
--
-- * 'csDeployments'
--
-- * 'csServiceName'
--
-- * 'csServiceARN'
--
-- * 'csTaskDefinition'
--
-- * 'csRoleARN'
containerService
:: ContainerService
containerService =
ContainerService'
{ _csRunningCount = Nothing
, _csStatus = Nothing
, _csClusterARN = Nothing
, _csDesiredCount = Nothing
, _csLoadBalancers = Nothing
, _csPendingCount = Nothing
, _csEvents = Nothing
, _csDeployments = Nothing
, _csServiceName = Nothing
, _csServiceARN = Nothing
, _csTaskDefinition = Nothing
, _csRoleARN = Nothing
}
-- | The number of tasks in the cluster that are in the 'RUNNING' state.
csRunningCount :: Lens' ContainerService (Maybe Int)
csRunningCount = lens _csRunningCount (\ s a -> s{_csRunningCount = a});
-- | The status of the service. The valid values are 'ACTIVE', 'DRAINING', or
-- 'INACTIVE'.
csStatus :: Lens' ContainerService (Maybe Text)
csStatus = lens _csStatus (\ s a -> s{_csStatus = a});
-- | The Amazon Resource Name (ARN) of the of the cluster that hosts the
-- service.
csClusterARN :: Lens' ContainerService (Maybe Text)
csClusterARN = lens _csClusterARN (\ s a -> s{_csClusterARN = a});
-- | The desired number of instantiations of the task definition to keep
-- running on the service. This value is specified when the service is
-- created with CreateService, and it can be modified with UpdateService.
csDesiredCount :: Lens' ContainerService (Maybe Int)
csDesiredCount = lens _csDesiredCount (\ s a -> s{_csDesiredCount = a});
-- | A list of load balancer objects, containing the load balancer name, the
-- container name (as it appears in a container definition), and the
-- container port to access from the load balancer.
csLoadBalancers :: Lens' ContainerService [LoadBalancer]
csLoadBalancers = lens _csLoadBalancers (\ s a -> s{_csLoadBalancers = a}) . _Default . _Coerce;
-- | The number of tasks in the cluster that are in the 'PENDING' state.
csPendingCount :: Lens' ContainerService (Maybe Int)
csPendingCount = lens _csPendingCount (\ s a -> s{_csPendingCount = a});
-- | The event stream for your service. A maximum of 100 of the latest events
-- are displayed.
csEvents :: Lens' ContainerService [ServiceEvent]
csEvents = lens _csEvents (\ s a -> s{_csEvents = a}) . _Default . _Coerce;
-- | The current state of deployments for the service.
csDeployments :: Lens' ContainerService [Deployment]
csDeployments = lens _csDeployments (\ s a -> s{_csDeployments = a}) . _Default . _Coerce;
-- | A user-generated string that you can use to identify your service.
csServiceName :: Lens' ContainerService (Maybe Text)
csServiceName = lens _csServiceName (\ s a -> s{_csServiceName = a});
-- | The Amazon Resource Name (ARN) that identifies the service. The ARN
-- contains the 'arn:aws:ecs' namespace, followed by the region of the
-- service, the AWS account ID of the service owner, the 'service'
-- namespace, and then the service name. For example,
-- arn:aws:ecs:/region/:/012345678910/:service\//my-service/.
csServiceARN :: Lens' ContainerService (Maybe Text)
csServiceARN = lens _csServiceARN (\ s a -> s{_csServiceARN = a});
-- | The task definition to use for tasks in the service. This value is
-- specified when the service is created with CreateService, and it can be
-- modified with UpdateService.
csTaskDefinition :: Lens' ContainerService (Maybe Text)
csTaskDefinition = lens _csTaskDefinition (\ s a -> s{_csTaskDefinition = a});
-- | The Amazon Resource Name (ARN) of the IAM role associated with the
-- service that allows the Amazon ECS container agent to register container
-- instances with a load balancer.
csRoleARN :: Lens' ContainerService (Maybe Text)
csRoleARN = lens _csRoleARN (\ s a -> s{_csRoleARN = a});
instance FromJSON ContainerService where
parseJSON
= withObject "ContainerService"
(\ x ->
ContainerService' <$>
(x .:? "runningCount") <*> (x .:? "status") <*>
(x .:? "clusterArn")
<*> (x .:? "desiredCount")
<*> (x .:? "loadBalancers" .!= mempty)
<*> (x .:? "pendingCount")
<*> (x .:? "events" .!= mempty)
<*> (x .:? "deployments" .!= mempty)
<*> (x .:? "serviceName")
<*> (x .:? "serviceArn")
<*> (x .:? "taskDefinition")
<*> (x .:? "roleArn"))
-- | The details of an Amazon ECS service deployment.
--
-- /See:/ 'deployment' smart constructor.
data Deployment = Deployment'
{ _dRunningCount :: !(Maybe Int)
, _dStatus :: !(Maybe Text)
, _dCreatedAt :: !(Maybe POSIX)
, _dDesiredCount :: !(Maybe Int)
, _dPendingCount :: !(Maybe Int)
, _dId :: !(Maybe Text)
, _dUpdatedAt :: !(Maybe POSIX)
, _dTaskDefinition :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Deployment' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dRunningCount'
--
-- * 'dStatus'
--
-- * 'dCreatedAt'
--
-- * 'dDesiredCount'
--
-- * 'dPendingCount'
--
-- * 'dId'
--
-- * 'dUpdatedAt'
--
-- * 'dTaskDefinition'
deployment
:: Deployment
deployment =
Deployment'
{ _dRunningCount = Nothing
, _dStatus = Nothing
, _dCreatedAt = Nothing
, _dDesiredCount = Nothing
, _dPendingCount = Nothing
, _dId = Nothing
, _dUpdatedAt = Nothing
, _dTaskDefinition = Nothing
}
-- | The number of tasks in the deployment that are in the 'RUNNING' status.
dRunningCount :: Lens' Deployment (Maybe Int)
dRunningCount = lens _dRunningCount (\ s a -> s{_dRunningCount = a});
-- | The status of the deployment. Valid values are 'PRIMARY' (for the most
-- recent deployment), 'ACTIVE' (for previous deployments that still have
-- tasks running, but are being replaced with the 'PRIMARY' deployment),
-- and 'INACTIVE' (for deployments that have been completely replaced).
dStatus :: Lens' Deployment (Maybe Text)
dStatus = lens _dStatus (\ s a -> s{_dStatus = a});
-- | The Unix time in seconds and milliseconds when the service was created.
dCreatedAt :: Lens' Deployment (Maybe UTCTime)
dCreatedAt = lens _dCreatedAt (\ s a -> s{_dCreatedAt = a}) . mapping _Time;
-- | The most recent desired count of tasks that was specified for the
-- service to deploy and\/or maintain.
dDesiredCount :: Lens' Deployment (Maybe Int)
dDesiredCount = lens _dDesiredCount (\ s a -> s{_dDesiredCount = a});
-- | The number of tasks in the deployment that are in the 'PENDING' status.
dPendingCount :: Lens' Deployment (Maybe Int)
dPendingCount = lens _dPendingCount (\ s a -> s{_dPendingCount = a});
-- | The ID of the deployment.
dId :: Lens' Deployment (Maybe Text)
dId = lens _dId (\ s a -> s{_dId = a});
-- | The Unix time in seconds and milliseconds when the service was last
-- updated.
dUpdatedAt :: Lens' Deployment (Maybe UTCTime)
dUpdatedAt = lens _dUpdatedAt (\ s a -> s{_dUpdatedAt = a}) . mapping _Time;
-- | The most recent task definition that was specified for the service to
-- use.
dTaskDefinition :: Lens' Deployment (Maybe Text)
dTaskDefinition = lens _dTaskDefinition (\ s a -> s{_dTaskDefinition = a});
instance FromJSON Deployment where
parseJSON
= withObject "Deployment"
(\ x ->
Deployment' <$>
(x .:? "runningCount") <*> (x .:? "status") <*>
(x .:? "createdAt")
<*> (x .:? "desiredCount")
<*> (x .:? "pendingCount")
<*> (x .:? "id")
<*> (x .:? "updatedAt")
<*> (x .:? "taskDefinition"))
-- | A failed resource.
--
-- /See:/ 'failure' smart constructor.
data Failure = Failure'
{ _fArn :: !(Maybe Text)
, _fReason :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Failure' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fArn'
--
-- * 'fReason'
failure
:: Failure
failure =
Failure'
{ _fArn = Nothing
, _fReason = Nothing
}
-- | The Amazon Resource Name (ARN) of the failed resource.
fArn :: Lens' Failure (Maybe Text)
fArn = lens _fArn (\ s a -> s{_fArn = a});
-- | The reason for the failure.
fReason :: Lens' Failure (Maybe Text)
fReason = lens _fReason (\ s a -> s{_fReason = a});
instance FromJSON Failure where
parseJSON
= withObject "Failure"
(\ x ->
Failure' <$> (x .:? "arn") <*> (x .:? "reason"))
-- | Details on a container instance host volume.
--
-- /See:/ 'hostVolumeProperties' smart constructor.
newtype HostVolumeProperties = HostVolumeProperties'
{ _hvpSourcePath :: Maybe Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'HostVolumeProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hvpSourcePath'
hostVolumeProperties
:: HostVolumeProperties
hostVolumeProperties =
HostVolumeProperties'
{ _hvpSourcePath = Nothing
}
-- | The path on the host container instance that is presented to the
-- container. If this parameter is empty, then the Docker daemon has
-- assigned a host path for you.
hvpSourcePath :: Lens' HostVolumeProperties (Maybe Text)
hvpSourcePath = lens _hvpSourcePath (\ s a -> s{_hvpSourcePath = a});
instance FromJSON HostVolumeProperties where
parseJSON
= withObject "HostVolumeProperties"
(\ x ->
HostVolumeProperties' <$> (x .:? "sourcePath"))
instance ToJSON HostVolumeProperties where
toJSON HostVolumeProperties'{..}
= object
(catMaybes [("sourcePath" .=) <$> _hvpSourcePath])
-- | A key and value pair object.
--
-- /See:/ 'keyValuePair' smart constructor.
data KeyValuePair = KeyValuePair'
{ _kvpValue :: !(Maybe Text)
, _kvpName :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'KeyValuePair' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'kvpValue'
--
-- * 'kvpName'
keyValuePair
:: KeyValuePair
keyValuePair =
KeyValuePair'
{ _kvpValue = Nothing
, _kvpName = Nothing
}
-- | The value of the key value pair. For environment variables, this is the
-- value of the environment variable.
kvpValue :: Lens' KeyValuePair (Maybe Text)
kvpValue = lens _kvpValue (\ s a -> s{_kvpValue = a});
-- | The name of the key value pair. For environment variables, this is the
-- name of the environment variable.
kvpName :: Lens' KeyValuePair (Maybe Text)
kvpName = lens _kvpName (\ s a -> s{_kvpName = a});
instance FromJSON KeyValuePair where
parseJSON
= withObject "KeyValuePair"
(\ x ->
KeyValuePair' <$> (x .:? "value") <*> (x .:? "name"))
instance ToJSON KeyValuePair where
toJSON KeyValuePair'{..}
= object
(catMaybes
[("value" .=) <$> _kvpValue,
("name" .=) <$> _kvpName])
-- | Details on a load balancer that is used with a service.
--
-- /See:/ 'loadBalancer' smart constructor.
data LoadBalancer = LoadBalancer'
{ _lbLoadBalancerName :: !(Maybe Text)
, _lbContainerName :: !(Maybe Text)
, _lbContainerPort :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'LoadBalancer' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbLoadBalancerName'
--
-- * 'lbContainerName'
--
-- * 'lbContainerPort'
loadBalancer
:: LoadBalancer
loadBalancer =
LoadBalancer'
{ _lbLoadBalancerName = Nothing
, _lbContainerName = Nothing
, _lbContainerPort = Nothing
}
-- | The name of the load balancer.
lbLoadBalancerName :: Lens' LoadBalancer (Maybe Text)
lbLoadBalancerName = lens _lbLoadBalancerName (\ s a -> s{_lbLoadBalancerName = a});
-- | The name of the container to associate with the load balancer.
lbContainerName :: Lens' LoadBalancer (Maybe Text)
lbContainerName = lens _lbContainerName (\ s a -> s{_lbContainerName = a});
-- | The port on the container to associate with the load balancer. This port
-- must correspond to a 'containerPort' in the service\'s task definition.
-- Your container instances must allow ingress traffic on the 'hostPort' of
-- the port mapping.
lbContainerPort :: Lens' LoadBalancer (Maybe Int)
lbContainerPort = lens _lbContainerPort (\ s a -> s{_lbContainerPort = a});
instance FromJSON LoadBalancer where
parseJSON
= withObject "LoadBalancer"
(\ x ->
LoadBalancer' <$>
(x .:? "loadBalancerName") <*>
(x .:? "containerName")
<*> (x .:? "containerPort"))
instance ToJSON LoadBalancer where
toJSON LoadBalancer'{..}
= object
(catMaybes
[("loadBalancerName" .=) <$> _lbLoadBalancerName,
("containerName" .=) <$> _lbContainerName,
("containerPort" .=) <$> _lbContainerPort])
-- | Details on a volume mount point that is used in a container definition.
--
-- /See:/ 'mountPoint' smart constructor.
data MountPoint = MountPoint'
{ _mpContainerPath :: !(Maybe Text)
, _mpSourceVolume :: !(Maybe Text)
, _mpReadOnly :: !(Maybe Bool)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'MountPoint' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mpContainerPath'
--
-- * 'mpSourceVolume'
--
-- * 'mpReadOnly'
mountPoint
:: MountPoint
mountPoint =
MountPoint'
{ _mpContainerPath = Nothing
, _mpSourceVolume = Nothing
, _mpReadOnly = Nothing
}
-- | The path on the container to mount the host volume at.
mpContainerPath :: Lens' MountPoint (Maybe Text)
mpContainerPath = lens _mpContainerPath (\ s a -> s{_mpContainerPath = a});
-- | The name of the volume to mount.
mpSourceVolume :: Lens' MountPoint (Maybe Text)
mpSourceVolume = lens _mpSourceVolume (\ s a -> s{_mpSourceVolume = a});
-- | If this value is 'true', the container has read-only access to the
-- volume. If this value is 'false', then the container can write to the
-- volume. The default value is 'false'.
mpReadOnly :: Lens' MountPoint (Maybe Bool)
mpReadOnly = lens _mpReadOnly (\ s a -> s{_mpReadOnly = a});
instance FromJSON MountPoint where
parseJSON
= withObject "MountPoint"
(\ x ->
MountPoint' <$>
(x .:? "containerPath") <*> (x .:? "sourceVolume")
<*> (x .:? "readOnly"))
instance ToJSON MountPoint where
toJSON MountPoint'{..}
= object
(catMaybes
[("containerPath" .=) <$> _mpContainerPath,
("sourceVolume" .=) <$> _mpSourceVolume,
("readOnly" .=) <$> _mpReadOnly])
-- | Details on the network bindings between a container and its host
-- container instance.
--
-- /See:/ 'networkBinding' smart constructor.
data NetworkBinding = NetworkBinding'
{ _nbBindIP :: !(Maybe Text)
, _nbProtocol :: !(Maybe TransportProtocol)
, _nbHostPort :: !(Maybe Int)
, _nbContainerPort :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'NetworkBinding' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'nbBindIP'
--
-- * 'nbProtocol'
--
-- * 'nbHostPort'
--
-- * 'nbContainerPort'
networkBinding
:: NetworkBinding
networkBinding =
NetworkBinding'
{ _nbBindIP = Nothing
, _nbProtocol = Nothing
, _nbHostPort = Nothing
, _nbContainerPort = Nothing
}
-- | The IP address that the container is bound to on the container instance.
nbBindIP :: Lens' NetworkBinding (Maybe Text)
nbBindIP = lens _nbBindIP (\ s a -> s{_nbBindIP = a});
-- | The protocol used for the network binding.
nbProtocol :: Lens' NetworkBinding (Maybe TransportProtocol)
nbProtocol = lens _nbProtocol (\ s a -> s{_nbProtocol = a});
-- | The port number on the host that is used with the network binding.
nbHostPort :: Lens' NetworkBinding (Maybe Int)
nbHostPort = lens _nbHostPort (\ s a -> s{_nbHostPort = a});
-- | The port number on the container that is be used with the network
-- binding.
nbContainerPort :: Lens' NetworkBinding (Maybe Int)
nbContainerPort = lens _nbContainerPort (\ s a -> s{_nbContainerPort = a});
instance FromJSON NetworkBinding where
parseJSON
= withObject "NetworkBinding"
(\ x ->
NetworkBinding' <$>
(x .:? "bindIP") <*> (x .:? "protocol") <*>
(x .:? "hostPort")
<*> (x .:? "containerPort"))
instance ToJSON NetworkBinding where
toJSON NetworkBinding'{..}
= object
(catMaybes
[("bindIP" .=) <$> _nbBindIP,
("protocol" .=) <$> _nbProtocol,
("hostPort" .=) <$> _nbHostPort,
("containerPort" .=) <$> _nbContainerPort])
-- | Port mappings allow containers to access ports on the host container
-- instance to send or receive traffic. Port mappings are specified as part
-- of the container definition.
--
-- /See:/ 'portMapping' smart constructor.
data PortMapping = PortMapping'
{ _pmProtocol :: !(Maybe TransportProtocol)
, _pmHostPort :: !(Maybe Int)
, _pmContainerPort :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PortMapping' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pmProtocol'
--
-- * 'pmHostPort'
--
-- * 'pmContainerPort'
portMapping
:: PortMapping
portMapping =
PortMapping'
{ _pmProtocol = Nothing
, _pmHostPort = Nothing
, _pmContainerPort = Nothing
}
-- | The protocol used for the port mapping. Valid values are 'tcp' and
-- 'udp'. The default is 'tcp'.
pmProtocol :: Lens' PortMapping (Maybe TransportProtocol)
pmProtocol = lens _pmProtocol (\ s a -> s{_pmProtocol = a});
-- | The port number on the container instance to reserve for your container.
-- You can specify a non-reserved host port for your container port
-- mapping, or you can omit the 'hostPort' (or set it to '0') while
-- specifying a 'containerPort' and your container will automatically
-- receive a port in the ephemeral port range for your container instance
-- operating system and Docker version.
--
-- The default ephemeral port range is 49153 to 65535, and this range is
-- used for Docker versions prior to 1.6.0. For Docker version 1.6.0 and
-- later, the Docker daemon tries to read the ephemeral port range from
-- '\/proc\/sys\/net\/ipv4\/ip_local_port_range'; if this kernel parameter
-- is unavailable, the default ephemeral port range is used. You should not
-- attempt to specify a host port in the ephemeral port range, since these
-- are reserved for automatic assignment. In general, ports below 32768 are
-- outside of the ephemeral port range.
--
-- The default reserved ports are 22 for SSH, the Docker ports 2375 and
-- 2376, and the Amazon ECS Container Agent port 51678. Any host port that
-- was previously specified in a running task is also reserved while the
-- task is running (once a task stops, the host port is released).The
-- current reserved ports are displayed in the 'remainingResources' of
-- DescribeContainerInstances output, and a container instance may have up
-- to 50 reserved ports at a time, including the default reserved ports
-- (automatically assigned ports do not count toward this limit).
pmHostPort :: Lens' PortMapping (Maybe Int)
pmHostPort = lens _pmHostPort (\ s a -> s{_pmHostPort = a});
-- | The port number on the container that is bound to the user-specified or
-- automatically assigned host port. If you specify a container port and
-- not a host port, your container will automatically receive a host port
-- in the ephemeral port range (for more information, see 'hostPort').
pmContainerPort :: Lens' PortMapping (Maybe Int)
pmContainerPort = lens _pmContainerPort (\ s a -> s{_pmContainerPort = a});
instance FromJSON PortMapping where
parseJSON
= withObject "PortMapping"
(\ x ->
PortMapping' <$>
(x .:? "protocol") <*> (x .:? "hostPort") <*>
(x .:? "containerPort"))
instance ToJSON PortMapping where
toJSON PortMapping'{..}
= object
(catMaybes
[("protocol" .=) <$> _pmProtocol,
("hostPort" .=) <$> _pmHostPort,
("containerPort" .=) <$> _pmContainerPort])
-- | Describes the resources available for a container instance.
--
-- /See:/ 'resource' smart constructor.
data Resource = Resource'
{ _rStringSetValue :: !(Maybe [Text])
, _rIntegerValue :: !(Maybe Int)
, _rDoubleValue :: !(Maybe Double)
, _rLongValue :: !(Maybe Integer)
, _rName :: !(Maybe Text)
, _rType :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Resource' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rStringSetValue'
--
-- * 'rIntegerValue'
--
-- * 'rDoubleValue'
--
-- * 'rLongValue'
--
-- * 'rName'
--
-- * 'rType'
resource
:: Resource
resource =
Resource'
{ _rStringSetValue = Nothing
, _rIntegerValue = Nothing
, _rDoubleValue = Nothing
, _rLongValue = Nothing
, _rName = Nothing
, _rType = Nothing
}
-- | When the 'stringSetValue' type is set, the value of the resource must be
-- a string type.
rStringSetValue :: Lens' Resource [Text]
rStringSetValue = lens _rStringSetValue (\ s a -> s{_rStringSetValue = a}) . _Default . _Coerce;
-- | When the 'integerValue' type is set, the value of the resource must be
-- an integer.
rIntegerValue :: Lens' Resource (Maybe Int)
rIntegerValue = lens _rIntegerValue (\ s a -> s{_rIntegerValue = a});
-- | When the 'doubleValue' type is set, the value of the resource must be a
-- double precision floating-point type.
rDoubleValue :: Lens' Resource (Maybe Double)
rDoubleValue = lens _rDoubleValue (\ s a -> s{_rDoubleValue = a});
-- | When the 'longValue' type is set, the value of the resource must be an
-- extended precision floating-point type.
rLongValue :: Lens' Resource (Maybe Integer)
rLongValue = lens _rLongValue (\ s a -> s{_rLongValue = a});
-- | The name of the resource, such as 'CPU', 'MEMORY', 'PORTS', or a
-- user-defined resource.
rName :: Lens' Resource (Maybe Text)
rName = lens _rName (\ s a -> s{_rName = a});
-- | The type of the resource, such as 'INTEGER', 'DOUBLE', 'LONG', or
-- 'STRINGSET'.
rType :: Lens' Resource (Maybe Text)
rType = lens _rType (\ s a -> s{_rType = a});
instance FromJSON Resource where
parseJSON
= withObject "Resource"
(\ x ->
Resource' <$>
(x .:? "stringSetValue" .!= mempty) <*>
(x .:? "integerValue")
<*> (x .:? "doubleValue")
<*> (x .:? "longValue")
<*> (x .:? "name")
<*> (x .:? "type"))
instance ToJSON Resource where
toJSON Resource'{..}
= object
(catMaybes
[("stringSetValue" .=) <$> _rStringSetValue,
("integerValue" .=) <$> _rIntegerValue,
("doubleValue" .=) <$> _rDoubleValue,
("longValue" .=) <$> _rLongValue,
("name" .=) <$> _rName, ("type" .=) <$> _rType])
-- | Details on an event associated with a service.
--
-- /See:/ 'serviceEvent' smart constructor.
data ServiceEvent = ServiceEvent'
{ _seCreatedAt :: !(Maybe POSIX)
, _seId :: !(Maybe Text)
, _seMessage :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ServiceEvent' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'seCreatedAt'
--
-- * 'seId'
--
-- * 'seMessage'
serviceEvent
:: ServiceEvent
serviceEvent =
ServiceEvent'
{ _seCreatedAt = Nothing
, _seId = Nothing
, _seMessage = Nothing
}
-- | The Unix time in seconds and milliseconds when the event was triggered.
seCreatedAt :: Lens' ServiceEvent (Maybe UTCTime)
seCreatedAt = lens _seCreatedAt (\ s a -> s{_seCreatedAt = a}) . mapping _Time;
-- | The ID string of the event.
seId :: Lens' ServiceEvent (Maybe Text)
seId = lens _seId (\ s a -> s{_seId = a});
-- | The event message.
seMessage :: Lens' ServiceEvent (Maybe Text)
seMessage = lens _seMessage (\ s a -> s{_seMessage = a});
instance FromJSON ServiceEvent where
parseJSON
= withObject "ServiceEvent"
(\ x ->
ServiceEvent' <$>
(x .:? "createdAt") <*> (x .:? "id") <*>
(x .:? "message"))
-- | Details on a task in a cluster.
--
-- /See:/ 'task' smart constructor.
data Task = Task'
{ _tDesiredStatus :: !(Maybe Text)
, _tOverrides :: !(Maybe TaskOverride)
, _tClusterARN :: !(Maybe Text)
, _tTaskARN :: !(Maybe Text)
, _tContainerInstanceARN :: !(Maybe Text)
, _tLastStatus :: !(Maybe Text)
, _tContainers :: !(Maybe [Container])
, _tStartedBy :: !(Maybe Text)
, _tTaskDefinitionARN :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Task' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tDesiredStatus'
--
-- * 'tOverrides'
--
-- * 'tClusterARN'
--
-- * 'tTaskARN'
--
-- * 'tContainerInstanceARN'
--
-- * 'tLastStatus'
--
-- * 'tContainers'
--
-- * 'tStartedBy'
--
-- * 'tTaskDefinitionARN'
task
:: Task
task =
Task'
{ _tDesiredStatus = Nothing
, _tOverrides = Nothing
, _tClusterARN = Nothing
, _tTaskARN = Nothing
, _tContainerInstanceARN = Nothing
, _tLastStatus = Nothing
, _tContainers = Nothing
, _tStartedBy = Nothing
, _tTaskDefinitionARN = Nothing
}
-- | The desired status of the task.
tDesiredStatus :: Lens' Task (Maybe Text)
tDesiredStatus = lens _tDesiredStatus (\ s a -> s{_tDesiredStatus = a});
-- | One or more container overrides.
tOverrides :: Lens' Task (Maybe TaskOverride)
tOverrides = lens _tOverrides (\ s a -> s{_tOverrides = a});
-- | The Amazon Resource Name (ARN) of the of the cluster that hosts the
-- task.
tClusterARN :: Lens' Task (Maybe Text)
tClusterARN = lens _tClusterARN (\ s a -> s{_tClusterARN = a});
-- | The Amazon Resource Name (ARN) of the task.
tTaskARN :: Lens' Task (Maybe Text)
tTaskARN = lens _tTaskARN (\ s a -> s{_tTaskARN = a});
-- | The Amazon Resource Name (ARN) of the container instances that host the
-- task.
tContainerInstanceARN :: Lens' Task (Maybe Text)
tContainerInstanceARN = lens _tContainerInstanceARN (\ s a -> s{_tContainerInstanceARN = a});
-- | The last known status of the task.
tLastStatus :: Lens' Task (Maybe Text)
tLastStatus = lens _tLastStatus (\ s a -> s{_tLastStatus = a});
-- | The containers associated with the task.
tContainers :: Lens' Task [Container]
tContainers = lens _tContainers (\ s a -> s{_tContainers = a}) . _Default . _Coerce;
-- | The tag specified when a task is started. If the task is started by an
-- Amazon ECS service, then the 'startedBy' parameter contains the
-- deployment ID of the service that starts it.
tStartedBy :: Lens' Task (Maybe Text)
tStartedBy = lens _tStartedBy (\ s a -> s{_tStartedBy = a});
-- | The Amazon Resource Name (ARN) of the of the task definition that
-- creates the task.
tTaskDefinitionARN :: Lens' Task (Maybe Text)
tTaskDefinitionARN = lens _tTaskDefinitionARN (\ s a -> s{_tTaskDefinitionARN = a});
instance FromJSON Task where
parseJSON
= withObject "Task"
(\ x ->
Task' <$>
(x .:? "desiredStatus") <*> (x .:? "overrides") <*>
(x .:? "clusterArn")
<*> (x .:? "taskArn")
<*> (x .:? "containerInstanceArn")
<*> (x .:? "lastStatus")
<*> (x .:? "containers" .!= mempty)
<*> (x .:? "startedBy")
<*> (x .:? "taskDefinitionArn"))
-- | Details of a task definition.
--
-- /See:/ 'taskDefinition' smart constructor.
data TaskDefinition = TaskDefinition'
{ _tdStatus :: !(Maybe TaskDefinitionStatus)
, _tdFamily :: !(Maybe Text)
, _tdContainerDefinitions :: !(Maybe [ContainerDefinition])
, _tdTaskDefinitionARN :: !(Maybe Text)
, _tdRevision :: !(Maybe Int)
, _tdVolumes :: !(Maybe [Volume])
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TaskDefinition' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tdStatus'
--
-- * 'tdFamily'
--
-- * 'tdContainerDefinitions'
--
-- * 'tdTaskDefinitionARN'
--
-- * 'tdRevision'
--
-- * 'tdVolumes'
taskDefinition
:: TaskDefinition
taskDefinition =
TaskDefinition'
{ _tdStatus = Nothing
, _tdFamily = Nothing
, _tdContainerDefinitions = Nothing
, _tdTaskDefinitionARN = Nothing
, _tdRevision = Nothing
, _tdVolumes = Nothing
}
-- | The status of the task definition.
tdStatus :: Lens' TaskDefinition (Maybe TaskDefinitionStatus)
tdStatus = lens _tdStatus (\ s a -> s{_tdStatus = a});
-- | The family of your task definition. You can think of the 'family' as the
-- name of your task definition.
tdFamily :: Lens' TaskDefinition (Maybe Text)
tdFamily = lens _tdFamily (\ s a -> s{_tdFamily = a});
-- | A list of container definitions in JSON format that describe the
-- different containers that make up your task. For more information on
-- container definition parameters and defaults, see
-- <http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html Amazon ECS Task Definitions>
-- in the /Amazon EC2 Container Service Developer Guide/.
tdContainerDefinitions :: Lens' TaskDefinition [ContainerDefinition]
tdContainerDefinitions = lens _tdContainerDefinitions (\ s a -> s{_tdContainerDefinitions = a}) . _Default . _Coerce;
-- | The full Amazon Resource Name (ARN) of the of the task definition.
tdTaskDefinitionARN :: Lens' TaskDefinition (Maybe Text)
tdTaskDefinitionARN = lens _tdTaskDefinitionARN (\ s a -> s{_tdTaskDefinitionARN = a});
-- | The revision of the task in a particular family. You can think of the
-- revision as a version number of a task definition in a family. When you
-- register a task definition for the first time, the revision is '1', and
-- each time you register a new revision of a task definition in the same
-- family, the revision value always increases by one (even if you have
-- deregistered previous revisions in this family).
tdRevision :: Lens' TaskDefinition (Maybe Int)
tdRevision = lens _tdRevision (\ s a -> s{_tdRevision = a});
-- | The list of volumes in a task. For more information on volume definition
-- parameters and defaults, see
-- <http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html Amazon ECS Task Definitions>
-- in the /Amazon EC2 Container Service Developer Guide/.
tdVolumes :: Lens' TaskDefinition [Volume]
tdVolumes = lens _tdVolumes (\ s a -> s{_tdVolumes = a}) . _Default . _Coerce;
instance FromJSON TaskDefinition where
parseJSON
= withObject "TaskDefinition"
(\ x ->
TaskDefinition' <$>
(x .:? "status") <*> (x .:? "family") <*>
(x .:? "containerDefinitions" .!= mempty)
<*> (x .:? "taskDefinitionArn")
<*> (x .:? "revision")
<*> (x .:? "volumes" .!= mempty))
-- | The overrides associated with a task.
--
-- /See:/ 'taskOverride' smart constructor.
newtype TaskOverride = TaskOverride'
{ _toContainerOverrides :: Maybe [ContainerOverride]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TaskOverride' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'toContainerOverrides'
taskOverride
:: TaskOverride
taskOverride =
TaskOverride'
{ _toContainerOverrides = Nothing
}
-- | One or more container overrides sent to a task.
toContainerOverrides :: Lens' TaskOverride [ContainerOverride]
toContainerOverrides = lens _toContainerOverrides (\ s a -> s{_toContainerOverrides = a}) . _Default . _Coerce;
instance FromJSON TaskOverride where
parseJSON
= withObject "TaskOverride"
(\ x ->
TaskOverride' <$>
(x .:? "containerOverrides" .!= mempty))
instance ToJSON TaskOverride where
toJSON TaskOverride'{..}
= object
(catMaybes
[("containerOverrides" .=) <$>
_toContainerOverrides])
-- | The Docker and Amazon ECS container agent version information on a
-- container instance.
--
-- /See:/ 'versionInfo' smart constructor.
data VersionInfo = VersionInfo'
{ _viAgentHash :: !(Maybe Text)
, _viAgentVersion :: !(Maybe Text)
, _viDockerVersion :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'VersionInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'viAgentHash'
--
-- * 'viAgentVersion'
--
-- * 'viDockerVersion'
versionInfo
:: VersionInfo
versionInfo =
VersionInfo'
{ _viAgentHash = Nothing
, _viAgentVersion = Nothing
, _viDockerVersion = Nothing
}
-- | The Git commit hash for the Amazon ECS container agent build on the
-- <https://github.com/aws/amazon-ecs-agent/commits/master amazon-ecs-agent>
-- GitHub repository.
viAgentHash :: Lens' VersionInfo (Maybe Text)
viAgentHash = lens _viAgentHash (\ s a -> s{_viAgentHash = a});
-- | The version number of the Amazon ECS container agent.
viAgentVersion :: Lens' VersionInfo (Maybe Text)
viAgentVersion = lens _viAgentVersion (\ s a -> s{_viAgentVersion = a});
-- | The Docker version running on the container instance.
viDockerVersion :: Lens' VersionInfo (Maybe Text)
viDockerVersion = lens _viDockerVersion (\ s a -> s{_viDockerVersion = a});
instance FromJSON VersionInfo where
parseJSON
= withObject "VersionInfo"
(\ x ->
VersionInfo' <$>
(x .:? "agentHash") <*> (x .:? "agentVersion") <*>
(x .:? "dockerVersion"))
instance ToJSON VersionInfo where
toJSON VersionInfo'{..}
= object
(catMaybes
[("agentHash" .=) <$> _viAgentHash,
("agentVersion" .=) <$> _viAgentVersion,
("dockerVersion" .=) <$> _viDockerVersion])
-- | A data volume used in a task definition.
--
-- /See:/ 'volume' smart constructor.
data Volume = Volume'
{ _vName :: !(Maybe Text)
, _vHost :: !(Maybe HostVolumeProperties)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Volume' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vName'
--
-- * 'vHost'
volume
:: Volume
volume =
Volume'
{ _vName = Nothing
, _vHost = Nothing
}
-- | The name of the volume. This name is referenced in the 'sourceVolume'
-- parameter of container definition 'mountPoints'.
vName :: Lens' Volume (Maybe Text)
vName = lens _vName (\ s a -> s{_vName = a});
-- | The path on the host container instance that is presented to the
-- containers which access the volume. If this parameter is empty, then the
-- Docker daemon assigns a host path for you.
vHost :: Lens' Volume (Maybe HostVolumeProperties)
vHost = lens _vHost (\ s a -> s{_vHost = a});
instance FromJSON Volume where
parseJSON
= withObject "Volume"
(\ x ->
Volume' <$> (x .:? "name") <*> (x .:? "host"))
instance ToJSON Volume where
toJSON Volume'{..}
= object
(catMaybes
[("name" .=) <$> _vName, ("host" .=) <$> _vHost])
-- | Details on a data volume from another container.
--
-- /See:/ 'volumeFrom' smart constructor.
data VolumeFrom = VolumeFrom'
{ _vfSourceContainer :: !(Maybe Text)
, _vfReadOnly :: !(Maybe Bool)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'VolumeFrom' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vfSourceContainer'
--
-- * 'vfReadOnly'
volumeFrom
:: VolumeFrom
volumeFrom =
VolumeFrom'
{ _vfSourceContainer = Nothing
, _vfReadOnly = Nothing
}
-- | The name of the container to mount volumes from.
vfSourceContainer :: Lens' VolumeFrom (Maybe Text)
vfSourceContainer = lens _vfSourceContainer (\ s a -> s{_vfSourceContainer = a});
-- | If this value is 'true', the container has read-only access to the
-- volume. If this value is 'false', then the container can write to the
-- volume. The default value is 'false'.
vfReadOnly :: Lens' VolumeFrom (Maybe Bool)
vfReadOnly = lens _vfReadOnly (\ s a -> s{_vfReadOnly = a});
instance FromJSON VolumeFrom where
parseJSON
= withObject "VolumeFrom"
(\ x ->
VolumeFrom' <$>
(x .:? "sourceContainer") <*> (x .:? "readOnly"))
instance ToJSON VolumeFrom where
toJSON VolumeFrom'{..}
= object
(catMaybes
[("sourceContainer" .=) <$> _vfSourceContainer,
("readOnly" .=) <$> _vfReadOnly])
| fmapfmapfmap/amazonka | amazonka-ecs/gen/Network/AWS/ECS/Types/Product.hs | mpl-2.0 | 63,266 | 0 | 22 | 14,942 | 11,635 | 6,792 | 4,843 | 1,083 | 1 |
module RefErl.BufferServer.Data where
import RefErl.BufferServer.Data.Rope
import Data.IntMap
import Data.Map
import System.IO
data Buffer = Buffer
{ fileName :: String
, content :: !Rope
, undos :: !URList
}
deriving (Show)
data State = State
{ refactorings :: Refactorings
, buffers :: Buffers
, autoIncrement :: !Int
, refacType :: !String
, renamings :: !(IntMap (String, String))
--, configData :: ConfigData
}
deriving (Show)
data Buffers = Buffers
{ openedBufs :: ![Buffer]
, closedBufs :: !(Map String Buffer)
}
deriving (Show)
data ClosedBuffer = ClosedBuffer
{ baseFileName :: String
, changes :: !URList
}
deriving (Show)
data BufferState = Opened | Closed
deriving (Eq, Show)
data Refactorings = Refactorings
{ openedRefacs :: !(IntMap [String])
}
deriving (Show)
data Change = AtomicChange
{ changeId :: Int
--, changeType :: String
, updates :: ![Update]
, changeType :: String
}
deriving (Show)
data URList = URList
{ getUndos :: ![Change]
, getRedos :: ![Change]
}
deriving (Show)
data Update = Insert {updatePoint :: !Point, insertUpdateString :: !Rope}
| Delete {updatePoint :: !Point, deleteUpdateString :: !Rope}
deriving (Show)
data UpdateType = InsertUpdate | DeleteUpdate
deriving (Eq)
data UndoType = UndoOp | RedoOp
{-data ConfigData = ConfigData
{ encoding :: TextEncoding
}
deriving (Show)
--}
--encoding :: TextEncoding
--encoding = utf8
| RefactorErl/refactorerl | refactorerl-0.9.15.04/lib/referl_ui/bufsrv/RefErl/BufferServer/Data.hs | lgpl-3.0 | 1,478 | 52 | 12 | 318 | 456 | 265 | 191 | 77 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-----------------------------------------------------------------
-- Autogenerated by Thrift
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-- @generated
-----------------------------------------------------------------
module My.Namespacing.Extend.Test.ExtendTestService_Client(check) where
import qualified My.Namespacing.Test.HsTestService_Client
import Data.IORef
import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..),
Eq, Show, Ord,
concat, error, fromIntegral, fromEnum, length, map,
maybe, not, null, otherwise, return, show, toEnum,
enumFromTo, Bounded, minBound, maxBound, seq,
(.), (&&), (||), (==), (++), ($), (-), (>>=), (>>))
import qualified Control.Applicative as Applicative (ZipList(..))
import Control.Applicative ( (<*>) )
import qualified Control.DeepSeq as DeepSeq
import qualified Control.Exception as Exception
import qualified Control.Monad as Monad ( liftM, ap, when )
import qualified Data.ByteString.Lazy as BS
import Data.Functor ( (<$>) )
import qualified Data.Hashable as Hashable
import qualified Data.Int as Int
import qualified Data.Maybe as Maybe (catMaybes)
import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 )
import qualified Data.Text.Lazy as LT
import qualified Data.Typeable as Typeable ( Typeable )
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) )
import qualified Test.QuickCheck as QuickCheck ( elements )
import qualified Thrift
import qualified Thrift.Types as Types
import qualified Thrift.Serializable as Serializable
import qualified Thrift.Arbitraries as Arbitraries
import qualified My.Namespacing.Test.Hsmodule_Types as Hsmodule_Types
import qualified My.Namespacing.Extend.Test.Extend_Types
import qualified My.Namespacing.Extend.Test.ExtendTestService
seqid = newIORef 0
check (ip,op) arg_struct1 = do
send_check op arg_struct1
recv_check ip
send_check op arg_struct1 = do
seq <- seqid
seqn <- readIORef seq
Thrift.writeMessage op ("check", Types.M_CALL, seqn) $
ExtendTestService.write_Check_args op (ExtendTestService.Check_args{ExtendTestService.check_args_struct1=arg_struct1})
Thrift.tFlush (Thrift.getTransport op)
recv_check ip =
Thrift.readMessage ip $ \(fname,mtype,rseqid) -> do
Monad.when (mtype == Types.M_EXCEPTION) $ Thrift.readAppExn ip >>= Exception.throw
res <- ExtendTestService.read_Check_result ip
return $ ExtendTestService.check_result_success res
| sinjar666/fbthrift | thrift/compiler/test/fixtures/namespace/gen-hs/My/Namespacing/Extend/Test/ExtendTestService_Client.hs | apache-2.0 | 3,021 | 0 | 14 | 487 | 663 | 431 | 232 | 56 | 1 |
module Network.BitTorrent.DHT.ContactInfo
( PeerStore
, Network.BitTorrent.DHT.ContactInfo.lookup
, Network.BitTorrent.DHT.ContactInfo.insert
) where
import Data.Default
import Data.List as L
import Data.Maybe
import Data.Monoid
import Data.HashMap.Strict as HM
import Data.Serialize
import Data.Torrent
import Network.BitTorrent.Address
{-
import Data.HashMap.Strict as HM
import Data.Torrent.InfoHash
import Network.BitTorrent.Address
-- increase prefix when table is too large
-- decrease prefix when table is too small
-- filter outdated peers
{-----------------------------------------------------------------------
-- PeerSet
-----------------------------------------------------------------------}
type PeerSet a = [(PeerAddr a, NodeInfo a, Timestamp)]
-- compare PSQueue vs Ordered list
takeNewest :: PeerSet a -> [PeerAddr a]
takeNewest = undefined
dropOld :: Timestamp -> PeerSet a -> PeerSet a
dropOld = undefined
insert :: PeerAddr a -> Timestamp -> PeerSet a -> PeerSet a
insert = undefined
type Mask = Int
type Size = Int
type Timestamp = Int
{-----------------------------------------------------------------------
-- InfoHashMap
-----------------------------------------------------------------------}
-- compare handwritten prefix tree versus IntMap
data Tree a
= Nil
| Tip !InfoHash !(PeerSet a)
| Bin !InfoHash !Mask !Size !Timestamp (Tree a) (Tree a)
insertTree :: InfoHash -> a -> Tree a -> Tree a
insertTree = undefined
type Prio = Int
--shrink :: ContactInfo ip -> Int
shrink Nil = Nil
shrink (Tip _ _) = undefined
shrink (Bin _ _) = undefined
{-----------------------------------------------------------------------
-- InfoHashMap
-----------------------------------------------------------------------}
-- compare new design versus HashMap
data IntMap k p a
type ContactInfo = Map InfoHash Timestamp (Set (PeerAddr IP) Timestamp)
data ContactInfo ip = PeerStore
{ maxSize :: Int
, prefixSize :: Int
, thisNodeId :: NodeId
, count :: Int -- ^ Cached size of the 'peerSet'
, peerSet :: HashMap InfoHash [PeerAddr ip]
}
size :: ContactInfo ip -> Int
size = undefined
prefixSize :: ContactInfo ip -> Int
prefixSize = undefined
lookup :: InfoHash -> ContactInfo ip -> [PeerAddr ip]
lookup = undefined
insert :: InfoHash -> PeerAddr ip -> ContactInfo ip -> ContactInfo ip
insert = undefined
-- | Limit in size.
prune :: NodeId -> Int -> ContactInfo ip -> ContactInfo ip
prune pref targetSize Nil = Nil
prune pref targetSize (Tip _ _) = undefined
-- | Remove expired entries.
splitGT :: Timestamp -> ContactInfo ip -> ContactInfo ip
splitGT = undefined
-}
-- | Storage used to keep track a set of known peers in client,
-- tracker or DHT sessions.
newtype PeerStore ip = PeerStore (HashMap InfoHash [PeerAddr ip])
-- | Empty store.
instance Default (PeerStore a) where
def = PeerStore HM.empty
{-# INLINE def #-}
-- | Monoid under union operation.
instance Eq a => Monoid (PeerStore a) where
mempty = def
{-# INLINE mempty #-}
mappend (PeerStore a) (PeerStore b) =
PeerStore (HM.unionWith L.union a b)
{-# INLINE mappend #-}
-- | Can be used to store peers between invocations of the client
-- software.
instance Serialize (PeerStore a) where
get = undefined
put = undefined
-- | Used in 'get_peers' DHT queries.
lookup :: InfoHash -> PeerStore a -> [PeerAddr a]
lookup ih (PeerStore m) = fromMaybe [] $ HM.lookup ih m
-- | Used in 'announce_peer' DHT queries.
insert :: Eq a => InfoHash -> PeerAddr a -> PeerStore a -> PeerStore a
insert ih a (PeerStore m) = PeerStore (HM.insertWith L.union ih [a] m)
| DavidAlphaFox/bittorrent | src/Network/BitTorrent/DHT/ContactInfo.hs | bsd-3-clause | 3,650 | 0 | 9 | 649 | 350 | 194 | 156 | 29 | 1 |
{-# LANGUAGE DeriveGeneric #-}
-- | The appearance of in-game items, as communicated to the player.
module Game.LambdaHack.Common.Flavour
( -- * The @Flavour@ type
Flavour
, -- * Constructors
zipPlain, zipFancy, stdFlav, zipLiquid
, -- * Accessors
flavourToColor, flavourToName
-- * Assorted
, colorToTeamName, colorToPlainName, colorToFancyName
) where
import Data.Binary
import Data.Hashable (Hashable)
import Data.Text (Text)
import GHC.Generics (Generic)
import Game.LambdaHack.Common.Color
data FancyName = Plain | Fancy | Liquid
deriving (Show, Eq, Ord, Generic)
instance Hashable FancyName
instance Binary FancyName
-- TODO: add more variety, as the number of items increases
-- | The type of item flavours.
data Flavour = Flavour
{ fancyName :: !FancyName -- ^ how fancy should the colour description be
, baseColor :: !Color -- ^ the colour of the flavour
}
deriving (Show, Eq, Ord, Generic)
instance Hashable Flavour
instance Binary Flavour
-- | Turn a colour set into a flavour set.
zipPlain, zipFancy, zipLiquid :: [Color] -> [Flavour]
zipPlain = map (Flavour Plain)
zipFancy = map (Flavour Fancy)
zipLiquid = map (Flavour Liquid)
-- | The standard full set of flavours.
stdFlav :: [Flavour]
stdFlav = zipPlain stdCol ++ zipFancy stdCol ++ zipLiquid stdCol
-- | Get the underlying base colour of a flavour.
flavourToColor :: Flavour -> Color
flavourToColor Flavour{baseColor} = baseColor
-- | Construct the full name of a flavour.
flavourToName :: Flavour -> Text
flavourToName Flavour{fancyName=Plain, ..} = colorToPlainName baseColor
flavourToName Flavour{fancyName=Fancy, ..} = colorToFancyName baseColor
flavourToName Flavour{fancyName=Liquid, ..} = colorToLiquidName baseColor
-- | Human-readable names for item colors. The plain set.
colorToPlainName :: Color -> Text
colorToPlainName Black = "black"
colorToPlainName Red = "red"
colorToPlainName Green = "green"
colorToPlainName Brown = "brown"
colorToPlainName Blue = "blue"
colorToPlainName Magenta = "purple"
colorToPlainName Cyan = "cyan"
colorToPlainName White = "ivory"
colorToPlainName BrBlack = "gray"
colorToPlainName BrRed = "coral"
colorToPlainName BrGreen = "lime"
colorToPlainName BrYellow = "yellow"
colorToPlainName BrBlue = "azure"
colorToPlainName BrMagenta = "pink"
colorToPlainName BrCyan = "aquamarine"
colorToPlainName BrWhite = "white"
-- | Human-readable names for item colors. The fancy set.
colorToFancyName :: Color -> Text
colorToFancyName Black = "smoky-black"
colorToFancyName Red = "apple-red"
colorToFancyName Green = "forest-green"
colorToFancyName Brown = "mahogany"
colorToFancyName Blue = "royal-blue"
colorToFancyName Magenta = "indigo"
colorToFancyName Cyan = "teal"
colorToFancyName White = "silver-gray"
colorToFancyName BrBlack = "charcoal"
colorToFancyName BrRed = "salmon"
colorToFancyName BrGreen = "emerald"
colorToFancyName BrYellow = "amber"
colorToFancyName BrBlue = "sky-blue"
colorToFancyName BrMagenta = "magenta"
colorToFancyName BrCyan = "turquoise"
colorToFancyName BrWhite = "ghost-white"
-- | Human-readable names for item colors. The liquid set.
colorToLiquidName :: Color -> Text
colorToLiquidName Black = "tarry"
colorToLiquidName Red = "bloody"
colorToLiquidName Green = "moldy"
colorToLiquidName Brown = "muddy"
colorToLiquidName Blue = "oily"
colorToLiquidName Magenta = "swirling"
colorToLiquidName Cyan = "bubbling"
colorToLiquidName White = "cloudy"
colorToLiquidName BrBlack = "pitchy"
colorToLiquidName BrRed = "red-speckled"
colorToLiquidName BrGreen = "sappy"
colorToLiquidName BrYellow = "gold"
colorToLiquidName BrBlue = "blue-speckled"
colorToLiquidName BrMagenta = "hazy"
colorToLiquidName BrCyan = "misty"
colorToLiquidName BrWhite = "shining"
-- | Simple names for team colors (bright colours preferred).
colorToTeamName :: Color -> Text
colorToTeamName BrRed = "red"
colorToTeamName BrGreen = "green"
colorToTeamName BrYellow = "yellow"
colorToTeamName BrBlue = "blue"
colorToTeamName BrMagenta = "pink"
colorToTeamName BrCyan = "cyan"
colorToTeamName BrWhite = "white"
colorToTeamName c = colorToFancyName c
| Concomitant/LambdaHack | Game/LambdaHack/Common/Flavour.hs | bsd-3-clause | 4,279 | 0 | 9 | 753 | 881 | 471 | 410 | -1 | -1 |
-- This program is intended for performance analysis. It simply
-- builds a Bloom filter from a list of words, one per line, and
-- queries it exhaustively.
module Main () where
import Control.Monad (forM_, mapM_)
import Data.BloomFilter (Bloom, fromListB, elemB, lengthB)
import Data.BloomFilter.Hash (cheapHashes)
import Data.BloomFilter.Easy (easyList, suggestSizing)
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Time.Clock (diffUTCTime, getCurrentTime)
import System.Environment (getArgs)
conservative, aggressive :: Double -> [B.ByteString] -> Bloom B.ByteString
conservative = easyList
aggressive fpr xs
= let (size, numHashes) = suggestSizing (length xs) fpr
k = 3
in fromListB (cheapHashes (numHashes - k)) (size * k) xs
testFunction = conservative
main = do
args <- getArgs
let files | null args = ["/usr/share/dict/words"]
| otherwise = args
forM_ files $ \file -> do
a <- getCurrentTime
words <- B.lines `fmap` B.readFile file
putStrLn $ {-# SCC "words/length" #-} show (length words) ++ " words"
b <- getCurrentTime
putStrLn $ show (diffUTCTime b a) ++ "s to count words"
let filt = {-# SCC "construct" #-} testFunction 0.01 words
print filt
c <- getCurrentTime
putStrLn $ show (diffUTCTime c b) ++ "s to construct filter"
{-# SCC "query" #-} mapM_ print $ filter (not . (`elemB` filt)) words
d <- getCurrentTime
putStrLn $ show (diffUTCTime d c) ++ "s to query every element"
| jsa/hs-bloomfilter | examples/Words.hs | bsd-3-clause | 1,498 | 0 | 15 | 306 | 449 | 236 | 213 | 32 | 1 |
import Graphics.UI.Gtk
main :: IO ()
main = do
initGUI
window <- windowNew
set window [windowTitle := "Range Controls",
windowDefaultWidth := 250 ]
mainbox <- vBoxNew False 10
containerAdd window mainbox
containerSetBorderWidth mainbox 10
box1 <- hBoxNew False 0
boxPackStart mainbox box1 PackGrow 0
adj1 <- adjustmentNew 0.0 0.0 101.0 0.1 1.0 1.0
vsc <- vScaleNew adj1
boxPackStart box1 vsc PackGrow 0
box2 <- vBoxNew False 0
boxPackStart box1 box2 PackGrow 0
hsc1 <- hScaleNew adj1
boxPackStart box2 hsc1 PackGrow 0
hsc2 <- hScaleNew adj1
boxPackStart box2 hsc2 PackGrow 0
chb <- checkButtonNewWithLabel "Display Value on Scale Widgets"
boxPackStart mainbox chb PackNatural 10
toggleButtonSetActive chb True
box3 <- hBoxNew False 10
boxPackStart mainbox box3 PackNatural 0
label1 <- labelNew (Just "Scale Value Position:")
boxPackStart box3 label1 PackNatural 0
opt1 <- makeOpt1
boxPackStart box3 opt1 PackNatural 0
box4 <- hBoxNew False 10
boxPackStart mainbox box4 PackNatural 0
label2 <- labelNew (Just "Scale Update Policy:")
boxPackStart box4 label2 PackNatural 0
opt2 <- makeOpt2
boxPackStart box4 opt2 PackNatural 0
adj2 <- adjustmentNew 1.0 0.0 5.0 1.0 1.0 0.0
box5 <- hBoxNew False 0
containerSetBorderWidth box5 10
boxPackStart mainbox box5 PackGrow 0
label3 <- labelNew (Just "Scale Digits:")
boxPackStart box5 label3 PackNatural 10
dsc <- hScaleNew adj2
boxPackStart box5 dsc PackGrow 0
scaleSetDigits dsc 0
adj3 <- adjustmentNew 1.0 1.0 101.0 1.0 1.0 0.0
box6 <- hBoxNew False 0
containerSetBorderWidth box6 10
boxPackStart mainbox box6 PackGrow 0
label4 <- labelNew (Just "Scrollbar Page Size:")
boxPackStart box6 label4 PackNatural 10
psc <- hScaleNew adj3
boxPackStart box6 psc PackGrow 0
scaleSetDigits psc 0
onToggled chb $ do toggleDisplay chb [hsc1,hsc2]
toggleDisplay chb [vsc]
onChanged opt1 $ do setScalePos opt1 hsc1
setScalePos opt1 hsc2
setScalePos opt1 vsc
onChanged opt2 $ do setUpdatePol opt2 hsc1
setUpdatePol opt2 hsc2
setUpdatePol opt2 vsc
onValueChanged adj2 $ do setDigits hsc1 adj2
setDigits hsc2 adj2
setDigits vsc adj2
onValueChanged adj3 $ do val <- adjustmentGetValue adj3
adjustmentSetPageSize adj1 val
widgetShowAll window
onDestroy window mainQuit
mainGUI
makeOpt1 :: IO ComboBox
makeOpt1 = do
cb <- comboBoxNewText
comboBoxAppendText cb "TOP"
comboBoxAppendText cb "BOTTOM"
comboBoxAppendText cb "LEFT"
comboBoxAppendText cb "RIGHT"
comboBoxSetActive cb 0
return cb
setScalePos :: ScaleClass self => ComboBox -> self -> IO ()
setScalePos cb sc = do
ntxt <- comboBoxGetActiveText cb
let pos = case ntxt of
(Just "TOP") -> PosTop
(Just "BOTTOM") -> PosBottom
(Just "LEFT") -> PosLeft
(Just "RIGHT") -> PosRight
Nothing -> error "GtkChap9.hs setScalePos: no position set"
scaleSetValuePos sc pos
makeOpt2 :: IO ComboBox
makeOpt2 = do
cb <- comboBoxNewText
comboBoxAppendText cb "Continuous"
comboBoxAppendText cb "Discontinuous"
comboBoxAppendText cb "Delayed"
comboBoxSetActive cb 0
return cb
setUpdatePol :: RangeClass self => ComboBox -> self -> IO ()
setUpdatePol cb sc = do
ntxt <- comboBoxGetActiveText cb
let pol = case ntxt of
(Just "Continuous") -> UpdateContinuous
(Just "Discontinuous") -> UpdateDiscontinuous
(Just "Delayed") -> UpdateDelayed
Nothing -> error "GtkChap9.hs setUpdatePol: no policy set"
rangeSetUpdatePolicy sc pol
toggleDisplay :: ScaleClass self => CheckButton -> [self] -> IO ()
toggleDisplay b scls = sequence_ (map change scls) where
change sc = do st <- toggleButtonGetActive b
scaleSetDrawValue sc st
setDigits :: ScaleClass self => self -> Adjustment -> IO ()
setDigits sc adj = do val <- get adj adjustmentValue
set sc [scaleDigits := (round val) ]
| mimi1vx/gtk2hs | docs/tutorial/Tutorial_Port/Example_Code/GtkChap4-2.hs | gpl-3.0 | 4,255 | 0 | 14 | 1,163 | 1,293 | 559 | 734 | 113 | 5 |
module Bugs (bugs) where
import Test.Framework
import qualified Bugs.Bug2
import qualified Bugs.Bug6
import qualified Bugs.Bug9
import qualified Bugs.Bug35
import qualified Bugs.Bug39
bugs :: [Test]
bugs = [ Bugs.Bug2.main
, Bugs.Bug6.main
, Bugs.Bug9.main
, Bugs.Bug35.main
, Bugs.Bug39.main ]
| omefire/megaparsec | old-tests/Bugs.hs | bsd-2-clause | 327 | 0 | 6 | 69 | 87 | 57 | 30 | 13 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TemplateHaskell #-}
{-|
Module : Stack.Sig.GPG
Description : GPG Functions
Copyright : (c) FPComplete.com, 2015
License : BSD3
Maintainer : Tim Dysinger <tim@fpcomplete.com>
Stability : experimental
Portability : POSIX
-}
module Stack.Sig.GPG (gpgSign, gpgVerify) where
import Prelude ()
import Prelude.Compat
import Control.Monad (unless, when)
import Control.Monad.Catch (MonadThrow, throwM)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger (MonadLogger, logWarn)
import qualified Data.ByteString.Char8 as C
import Data.List (find, isPrefixOf)
import Data.Monoid ((<>))
import qualified Data.Text as T
import Path
import Stack.Types
import System.Directory (findExecutable)
import System.Environment (lookupEnv)
import System.Exit (ExitCode(..))
import System.IO (Handle, hGetContents, hPutStrLn)
import System.Info (os)
import System.Process (ProcessHandle, runInteractiveProcess,
waitForProcess)
-- | Sign a file path with GPG, returning the @Signature@.
gpgSign
:: (MonadIO m, MonadLogger m, MonadThrow m)
=> Path Abs File -> m Signature
gpgSign path = do
gpgWarnTTY
(_hIn,hOut,hErr,process) <-
gpg
[ "--output"
, "-"
, "--use-agent"
, "--detach-sig"
, "--armor"
, toFilePath path]
(out,err,code) <-
liftIO
((,,) <$>
hGetContents hOut <*>
hGetContents hErr <*>
waitForProcess process)
if code /= ExitSuccess
then throwM (GPGSignException $ out <> "\n" <> err)
else return (Signature $ C.pack out)
-- | Verify the @Signature@ of a file path returning the
-- @Fingerprint@.
gpgVerify
:: (MonadIO m, MonadThrow m)
=> Signature -> Path Abs File -> m Fingerprint
gpgVerify (Signature signature) path = do
(hIn,hOut,hErr,process) <-
gpg ["--verify", "--with-fingerprint", "-", toFilePath path]
(_in,out,err,code) <-
liftIO
((,,,) <$>
hPutStrLn hIn (C.unpack signature) <*>
hGetContents hOut <*>
hGetContents hErr <*>
waitForProcess process)
if code /= ExitSuccess
then throwM (GPGVerifyException (out ++ "\n" ++ err))
else maybe
(throwM
(GPGFingerprintException
("unable to extract fingerprint from output\n: " <>
out)))
return
(mkFingerprint . T.pack . concat . drop 3 <$>
find
((==) ["Primary", "key", "fingerprint:"] . take 3)
(map words (lines err)))
-- | Try to execute `gpg2` but fallback to `gpg` (as a backup)
gpg
:: (MonadIO m, MonadThrow m)
=> [String] -> m (Handle, Handle, Handle, ProcessHandle)
gpg args = do
mGpg2Path <- liftIO (findExecutable "gpg2")
case mGpg2Path of
Just _ -> liftIO (runInteractiveProcess "gpg2" args Nothing Nothing)
Nothing -> do
mGpgPath <- liftIO (findExecutable "gpg")
case mGpgPath of
Just _ ->
liftIO (runInteractiveProcess "gpg" args Nothing Nothing)
Nothing -> throwM GPGNotFoundException
-- | `man gpg-agent` shows that you need GPG_TTY environment variable set to
-- properly deal with interactions with gpg-agent. (Doesn't apply to Windows
-- though)
gpgWarnTTY :: (MonadIO m, MonadLogger m) => m ()
gpgWarnTTY =
unless
("ming" `isPrefixOf` os)
(do mTTY <- liftIO (lookupEnv "GPG_TTY")
when
(null mTTY)
($logWarn
"Environment variable GPG_TTY is not set (see `man gpg-agent`)"))
| Heather/stack | src/Stack/Sig/GPG.hs | bsd-3-clause | 4,032 | 0 | 17 | 1,304 | 935 | 510 | 425 | 93 | 3 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module UnitTests.Distribution.Solver.Modular.QuickCheck (tests) where
import Control.Monad (foldM)
import Data.Either (lefts)
import Data.Function (on)
import Data.List (groupBy, isInfixOf, nub, sort)
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>), (<*>))
import Data.Monoid (Monoid)
#endif
import Text.Show.Pretty (parseValue, valToStr)
import Test.Tasty (TestTree)
import Test.Tasty.QuickCheck
import Distribution.Client.Dependency.Types
( Solver(..) )
import Distribution.Client.Setup (defaultMaxBackjumps)
import qualified Distribution.Solver.Types.ComponentDeps as CD
import Distribution.Solver.Types.ComponentDeps
( Component(..), ComponentDep, ComponentDeps )
import Distribution.Solver.Types.PkgConfigDb
(pkgConfigDbFromList)
import Distribution.Solver.Types.Settings
import UnitTests.Distribution.Solver.Modular.DSL
tests :: [TestTree]
tests = [
-- This test checks that certain solver parameters do not affect the
-- existence of a solution. It runs the solver twice, and only sets those
-- parameters on the second run. The test also applies parameters that
-- can affect the existence of a solution to both runs.
testProperty "target order and --reorder-goals do not affect solvability" $
\(SolverTest db targets) targetOrder reorderGoals indepGoals solver ->
let r1 = solve' (ReorderGoals False) targets db
r2 = solve' reorderGoals targets2 db
solve' reorder = solve (EnableBackjumping True) reorder
indepGoals solver
targets2 = case targetOrder of
SameOrder -> targets
ReverseOrder -> reverse targets
in counterexample (showResults r1 r2) $
noneReachedBackjumpLimit [r1, r2] ==>
isRight (resultPlan r1) === isRight (resultPlan r2)
, testProperty
"solvable without --independent-goals => solvable with --independent-goals" $
\(SolverTest db targets) reorderGoals solver ->
let r1 = solve' (IndependentGoals False) targets db
r2 = solve' (IndependentGoals True) targets db
solve' indep = solve (EnableBackjumping True)
reorderGoals indep solver
in counterexample (showResults r1 r2) $
noneReachedBackjumpLimit [r1, r2] ==>
isRight (resultPlan r1) `implies` isRight (resultPlan r2)
, testProperty "backjumping does not affect solvability" $
\(SolverTest db targets) reorderGoals indepGoals ->
let r1 = solve' (EnableBackjumping True) targets db
r2 = solve' (EnableBackjumping False) targets db
solve' enableBj = solve enableBj reorderGoals indepGoals Modular
in counterexample (showResults r1 r2) $
noneReachedBackjumpLimit [r1, r2] ==>
isRight (resultPlan r1) === isRight (resultPlan r2)
]
where
noneReachedBackjumpLimit :: [Result] -> Bool
noneReachedBackjumpLimit =
not . any (\r -> resultPlan r == Left BackjumpLimitReached)
showResults :: Result -> Result -> String
showResults r1 r2 = showResult 1 r1 ++ showResult 2 r2
showResult :: Int -> Result -> String
showResult n result =
unlines $ ["", "Run " ++ show n ++ ":"]
++ resultLog result
++ ["result: " ++ show (resultPlan result)]
implies :: Bool -> Bool -> Bool
implies x y = not x || y
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
solve :: EnableBackjumping -> ReorderGoals -> IndependentGoals
-> Solver -> [PN] -> TestDb -> Result
solve enableBj reorder indep solver targets (TestDb db) =
let (lg, result) =
exResolve db Nothing Nothing
(pkgConfigDbFromList [])
(map unPN targets)
solver
-- The backjump limit prevents individual tests from using
-- too much time and memory.
(Just defaultMaxBackjumps)
indep reorder enableBj []
failure :: String -> Failure
failure msg
| "Backjump limit reached" `isInfixOf` msg = BackjumpLimitReached
| otherwise = OtherFailure
in Result {
resultLog = lg
, resultPlan = either (Left . failure) (Right . extractInstallPlan) result
}
-- | How to modify the order of the input targets.
data TargetOrder = SameOrder | ReverseOrder
deriving Show
instance Arbitrary TargetOrder where
arbitrary = elements [SameOrder, ReverseOrder]
shrink SameOrder = []
shrink ReverseOrder = [SameOrder]
data Result = Result {
resultLog :: [String]
, resultPlan :: Either Failure [(ExamplePkgName, ExamplePkgVersion)]
}
data Failure = BackjumpLimitReached | OtherFailure
deriving (Eq, Show)
-- | Package name.
newtype PN = PN { unPN :: String }
deriving (Eq, Ord, Show)
instance Arbitrary PN where
arbitrary = PN <$> elements ("base" : [[pn] | pn <- ['A'..'G']])
-- | Package version.
newtype PV = PV { unPV :: Int }
deriving (Eq, Ord, Show)
instance Arbitrary PV where
arbitrary = PV <$> elements [1..10]
type TestPackage = Either ExampleInstalled ExampleAvailable
getName :: TestPackage -> PN
getName = PN . either exInstName exAvName
getVersion :: TestPackage -> PV
getVersion = PV . either exInstVersion exAvVersion
data SolverTest = SolverTest {
testDb :: TestDb
, testTargets :: [PN]
}
-- | Pretty-print the test when quickcheck calls 'show'.
instance Show SolverTest where
show test =
let str = "SolverTest {testDb = " ++ show (testDb test)
++ ", testTargets = " ++ show (testTargets test) ++ "}"
in maybe str valToStr $ parseValue str
instance Arbitrary SolverTest where
arbitrary = do
db <- arbitrary
let pkgs = nub $ map getName (unTestDb db)
Positive n <- arbitrary
targets <- randomSubset n pkgs
return (SolverTest db targets)
shrink test =
[test { testDb = db } | db <- shrink (testDb test)]
++ [test { testTargets = targets } | targets <- shrink (testTargets test)]
-- | Collection of source and installed packages.
newtype TestDb = TestDb { unTestDb :: ExampleDb }
deriving Show
instance Arbitrary TestDb where
arbitrary = do
-- Avoid cyclic dependencies by grouping packages by name and only
-- allowing each package to depend on packages in the groups before it.
groupedPkgs <- shuffle . groupBy ((==) `on` fst) . nub . sort =<<
boundedListOf 10 arbitrary
db <- foldM nextPkgs (TestDb []) groupedPkgs
TestDb <$> shuffle (unTestDb db)
where
nextPkgs :: TestDb -> [(PN, PV)] -> Gen TestDb
nextPkgs db pkgs = TestDb . (++ unTestDb db) <$> mapM (nextPkg db) pkgs
nextPkg :: TestDb -> (PN, PV) -> Gen TestPackage
nextPkg db (pn, v) = do
installed <- arbitrary
if installed
then Left <$> arbitraryExInst pn v (lefts $ unTestDb db)
else Right <$> arbitraryExAv pn v db
shrink (TestDb pkgs) = map TestDb $ shrink pkgs
arbitraryExAv :: PN -> PV -> TestDb -> Gen ExampleAvailable
arbitraryExAv pn v db =
ExAv (unPN pn) (unPV v) <$> arbitraryComponentDeps db
arbitraryExInst :: PN -> PV -> [ExampleInstalled] -> Gen ExampleInstalled
arbitraryExInst pn v pkgs = do
hash <- vectorOf 10 $ elements $ ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9']
numDeps <- min 3 <$> arbitrary
deps <- randomSubset numDeps pkgs
return $ ExInst (unPN pn) (unPV v) hash (map exInstHash deps)
arbitraryComponentDeps :: TestDb -> Gen (ComponentDeps [ExampleDependency])
arbitraryComponentDeps (TestDb []) = return $ CD.fromList []
arbitraryComponentDeps db =
-- CD.fromList combines duplicate components.
CD.fromList <$> boundedListOf 3 (arbitraryComponentDep db)
arbitraryComponentDep :: TestDb -> Gen (ComponentDep [ExampleDependency])
arbitraryComponentDep db = do
comp <- arbitrary
deps <- case comp of
ComponentSetup -> smallListOf (arbitraryExDep db Setup)
_ -> boundedListOf 5 (arbitraryExDep db NonSetup)
return (comp, deps)
-- | Location of an 'ExampleDependency'. It determines which values are valid.
data ExDepLocation = Setup | NonSetup
arbitraryExDep :: TestDb -> ExDepLocation -> Gen ExampleDependency
arbitraryExDep db@(TestDb pkgs) level =
let flag = ExFlag <$> arbitraryFlagName
<*> arbitraryDeps db
<*> arbitraryDeps db
other = [
ExAny . unPN <$> elements (map getName pkgs)
-- existing version
, let fixed pkg = ExFix (unPN $ getName pkg) (unPV $ getVersion pkg)
in fixed <$> elements pkgs
-- random version of an existing package
, ExFix . unPN . getName <$> elements pkgs <*> (unPV <$> arbitrary)
]
in oneof $
case level of
NonSetup -> flag : other
Setup -> other
arbitraryDeps :: TestDb -> Gen Dependencies
arbitraryDeps db = frequency
[ (1, return NotBuildable)
, (20, Buildable <$> smallListOf (arbitraryExDep db NonSetup))
]
arbitraryFlagName :: Gen String
arbitraryFlagName = (:[]) <$> elements ['A'..'E']
arbitraryComponentName :: Gen String
arbitraryComponentName = (:[]) <$> elements "ABC"
instance Arbitrary ReorderGoals where
arbitrary = ReorderGoals <$> arbitrary
shrink (ReorderGoals reorder) = [ReorderGoals False | reorder]
instance Arbitrary IndependentGoals where
arbitrary = IndependentGoals <$> arbitrary
shrink (IndependentGoals indep) = [IndependentGoals False | indep]
instance Arbitrary Solver where
arbitrary = frequency [ (1, return TopDown)
, (5, return Modular) ]
shrink Modular = []
shrink TopDown = [Modular]
instance Arbitrary Component where
arbitrary = oneof [ ComponentLib <$> arbitraryComponentName
, ComponentExe <$> arbitraryComponentName
, ComponentTest <$> arbitraryComponentName
, ComponentBench <$> arbitraryComponentName
, return ComponentSetup
]
shrink (ComponentLib "") = []
shrink _ = [ComponentLib ""]
instance Arbitrary ExampleInstalled where
arbitrary = error "arbitrary not implemented: ExampleInstalled"
shrink ei = [ ei { exInstBuildAgainst = deps }
| deps <- shrinkList shrinkNothing (exInstBuildAgainst ei)]
instance Arbitrary ExampleAvailable where
arbitrary = error "arbitrary not implemented: ExampleAvailable"
shrink ea = [ea { exAvDeps = deps } | deps <- shrink (exAvDeps ea)]
instance (Arbitrary a, Monoid a) => Arbitrary (ComponentDeps a) where
arbitrary = error "arbitrary not implemented: ComponentDeps"
shrink = map CD.fromList . shrink . CD.toList
instance Arbitrary ExampleDependency where
arbitrary = error "arbitrary not implemented: ExampleDependency"
shrink (ExAny _) = []
shrink (ExFix pn _) = [ExAny pn]
shrink (ExFlag flag th el) =
deps th ++ deps el
++ [ExFlag flag th' el | th' <- shrink th]
++ [ExFlag flag th el' | el' <- shrink el]
where
deps NotBuildable = []
deps (Buildable ds) = ds
shrink dep = error $ "Dependency not handled: " ++ show dep
instance Arbitrary Dependencies where
arbitrary = error "arbitrary not implemented: Dependencies"
shrink NotBuildable = [Buildable []]
shrink (Buildable deps) = map Buildable (shrink deps)
randomSubset :: Int -> [a] -> Gen [a]
randomSubset n xs = take n <$> shuffle xs
boundedListOf :: Int -> Gen a -> Gen [a]
boundedListOf n gen = take n <$> listOf gen
-- | Generates lists with average length less than 1.
smallListOf :: Gen a -> Gen [a]
smallListOf gen =
frequency [ (fr, vectorOf n gen)
| (fr, n) <- [(3, 0), (5, 1), (2, 2)]]
| headprogrammingczar/cabal | cabal-install/tests/UnitTests/Distribution/Solver/Modular/QuickCheck.hs | bsd-3-clause | 12,092 | 0 | 17 | 3,213 | 3,394 | 1,772 | 1,622 | 240 | 3 |
module SyntaxExt where
import Auxillary
import Data.List(nub)
import ParserAll -- This for defining parsers
-- To import ParserAll you must define CommentDef.hs and TokenDef.hs
-- These should be in the same directory as this file.
import Data.Char(isLower)
import qualified Text.PrettyPrint.HughesPJ as PP
import Text.PrettyPrint.HughesPJ(Doc,text,int,(<>),(<+>),($$),($+$),render)
data SyntaxStyle = OLD | NEW
type SynAssoc a = Either a a
data SynExt t -- Syntax Extension
= Ox -- no extension
| Ix (String,Maybe (SynAssoc (t,t)),Maybe(t,t),Maybe (SynAssoc t),Maybe (SynAssoc (t,t)),Maybe t,Maybe t,Maybe t,Maybe (t,t,t,t))
| Parsex (String,SyntaxStyle,[(t,Int)],[(t,[t])])
data Extension t
= Listx (SynAssoc [t]) (Maybe t) String -- [x,y ; zs]i [x ; y,z]i
| Natx Int (Maybe t) String -- 4i (2+x)i
| Pairx (SynAssoc [t]) String -- (a,b,c)i
| Recordx (SynAssoc [(t,t)]) (Maybe t) String -- {x=t,y=s ; zs}i {zs ; y=s,x=t}i
| Tickx Int t String -- (e`3)i
| Unitx String -- ()i
| Itemx t String -- (e)i
| Applicativex t String -- (f a b)i
-------------------------------------------------------------
-- Show instances
instance Show a => Show (SynExt a) where
show Ox = "Ox"
show (Ix(k,l,n,p,r,t,u,i,a)) = "Ix "++k++f' "List" l++f "Nat" n++g' "Pair" p++f' "Record" r++g "Tick" t++g "Unit" u++g "Item" i++g "Applicative" a
where f nm Nothing = ""
f nm (Just(x,y)) = " "++nm++"["++show x++","++show y++"]"
f' nm (Just (Right x)) = f nm (Just x)
f' nm (Just (Left x)) = f ("Left"++nm) (Just x)
f' _ Nothing = ""
g nm Nothing = ""
g nm (Just x) = " "++nm++"["++show x++"]"
g' nm Nothing = ""
g' nm (Just (Right x)) = g nm (Just x)
g' nm (Just (Left x)) = g ("Left"++nm) (Just x)
show (Parsex(k,_,_,zs)) = "Px "++k++show zs
instance Show x => Show(Extension x) where
show (Listx ts' Nothing tag) = plist "[" ts "," ("]"++tag)
where (_, ts) = outLR ts'
show (Listx (Right ts) (Just t) tag) = plist "[" ts "," "; " ++ show t ++"]"++tag
show (Listx (Left ts) (Just t) tag) = "[" ++ show t ++ "; " ++ plist "" ts "," ("]"++tag)
show (Natx n Nothing tag) = show n++tag
show (Natx n (Just t) tag) = "("++show n++"+"++show t++")"++tag
show (Unitx tag) = "()"++tag
show (Itemx x tag) = "("++show x++")"++tag
show (Pairx ts' tag) = "("++ help ts ++")"++tag
where help [] = ""
help [x] = show x
help (x:xs) = show x++","++help xs
(_, ts) = outLR ts'
show (Recordx ts' Nothing tag) = plistf f "{" ts "," ("}"++tag)
where f (x,y) = show x++"="++show y
(_, ts) = outLR ts'
show (Recordx (Right ts) (Just ys) tag) = plistf f "{" ts "," (";"++show ys++"}"++tag)
where f (x,y) = show x++"="++show y
show (Recordx (Left ts) (Just ys) tag) = "{" ++ show ys ++ "; " ++ plistf f "" ts "," ("}"++tag)
where f (x,y) = show x++"="++show y
show (Tickx n t tag) = "("++show t++"`"++show n++")"++tag
show (Applicativex x tag) = "("++show x++")"++tag
extKey :: Extension a -> String
extKey (Listx xs _ s) = s
extKey (Recordx xs _ s) = s
extKey (Natx n _ s) = s
extKey (Unitx s) = s
extKey (Itemx x s) = s
extKey (Pairx xs s) = s
extKey (Tickx n x s) = s
extKey (Applicativex x s) = s
extName :: Extension a -> String
extName (Listx (Right xs) _ s) = "List"
extName (Listx (Left xs) _ s) = "LeftList"
extName (Recordx (Right xs) _ s) = "Record"
extName (Recordx (Left xs) _ s) = "LeftRecord"
extName (Natx n _ s) = "Nat"
extName (Unitx s) = "Unit"
extName (Itemx _ s) = "Item"
extName (Pairx (Right xs) s) = "Pair"
extName (Pairx (Left xs) s) = "LeftPair"
extName (Tickx n _ s) = "Tick"
extName (Applicativex _ s) = "Applicative"
outLR (Right xs) = (Right, xs)
outLR (Left xs) = (Left, xs)
----------------------------------------------------
-- Creating formatted documents
ppExt :: (a -> Doc) -> Extension a -> Doc
ppExt f((Listx (Right xs) (Just x) s)) = PP.sep (PP.lbrack: PP.punctuate PP.comma (map f xs)++[PP.semi,f x,text ("]"++s)])
ppExt f((Listx (Left xs) (Just x) s)) = PP.sep (PP.lbrack: f x: PP.semi: PP.punctuate PP.comma (map f xs)++[text ("]"++s)])
ppExt f((Listx xs' Nothing s)) = PP.sep (PP.lbrack: PP.punctuate PP.comma (map f xs)++[text ("]"++s)])
where (_, xs) = outLR xs'
ppExt f((Natx n (Just x) s)) = PP.hcat [PP.lparen,PP.int n,text "+",f x,text (")"++s)]
ppExt f((Natx n Nothing s)) = PP.hcat [PP.int n,text s]
ppExt f((Unitx s)) = text ("()"++s)
ppExt f((Itemx x s)) = PP.lparen <> f x <> text (")"++s)
ppExt f((Pairx xs' s)) = PP.lparen <> PP.hcat(PP.punctuate PP.comma (map f xs)) <> text (")"++s)
where (_, xs) = outLR xs'
ppExt f((Recordx (Right xs) (Just x) s)) = PP.lbrace <> PP.hcat(PP.punctuate PP.comma (map g xs)) <> PP.semi <> f x <> text ("}"++s)
where g (x,y) = f x <> PP.equals <> f y
ppExt f((Recordx (Left xs) (Just x) s)) = PP.lbrace <> f x <> PP.semi <> PP.hcat(PP.punctuate PP.comma (map g xs)) <> text ("}"++s)
where g (x,y) = f x <> PP.equals <> f y
ppExt f (Recordx xs' Nothing s) = PP.lbrace <> PP.hcat(PP.punctuate PP.comma (map g xs)) <> text ("}"++s)
where g (x,y) = f x <> PP.equals <> f y
(_, xs) = outLR xs'
ppExt f((Tickx n x s)) = PP.hcat [PP.lparen,f x,text "`",PP.int n,text (")"++s)]
ppExt f((Applicativex x s)) = PP.hcat [PP.lparen,f x,text (")"++s)]
-------------------------------------------------------
-- map and fold-like operations
extList :: Extension a -> [a]
extList ((Listx (Right xs) (Just x) _)) = x:xs
extList ((Listx (Left xs) (Just x) _)) = foldr (:) [x] xs
extList ((Listx xs' Nothing _)) = xs
where (_, xs) = outLR xs'
extList ((Recordx (Right xs) (Just x) _)) = (x: flat2 xs)
extList ((Recordx (Left xs) (Just x) _)) = foldr (:) [x] (flat2 xs)
extList ((Recordx xs' Nothing _)) = flat2 xs
where (_, xs) = outLR xs'
extList ((Natx n (Just x) _)) = [x]
extList ((Natx n Nothing _)) = []
extList ((Unitx _)) = []
extList ((Itemx x _)) = [x]
extList ((Pairx xs' _)) = xs
where (_, xs) = outLR xs'
extList ((Tickx n x _)) = [x]
extList ((Applicativex x _)) = [x]
instance Eq t => Eq (Extension t) where
(Listx (Right ts1) (Just t1) s1) == (Listx (Right xs1) (Just x1) s2) = s1==s2 && (t1:ts1)==(x1:xs1)
(Listx (Left ts1) (Just t1) s1) == (Listx (Left xs1) (Just x1) s2) = s1==s2 && (t1:ts1)==(x1:xs1)
(Listx ts1 Nothing s1) == (Listx xs1 Nothing s2) = s1==s2 && ts1==xs1
(Natx n (Just t1) s1) == (Natx m (Just x1) s2) = s1==s2 && t1==x1 && n==m
(Natx n Nothing s1) == (Natx m Nothing s2) = s1==s2 && n==m
(Unitx s) == (Unitx t) = s==t
(Itemx x s) == (Itemx y t) = x==y && s==t
(Pairx xs s) == (Pairx ys t) = xs==ys && s==t
(Recordx (Right ts1) (Just t1) s1) == (Recordx (Right xs1) (Just x1) s2) = s1==s2 && t1==x1 && ts1==xs1
(Recordx (Left ts1) (Just t1) s1) == (Recordx (Left xs1) (Just x1) s2) = s1==s2 && t1==x1 && ts1==xs1
(Recordx ts1 Nothing s1) == (Recordx xs1 Nothing s2) = s1==s2 && ts1==xs1
(Tickx n t1 s1) == (Tickx m x1 s2) = s1==s2 && t1==x1 && n==m
(Applicativex x s) == (Applicativex y t) = x==y && s==t
_ == _ = False
extM :: Monad a => (b -> a c) -> Extension b -> a (Extension c)
extM f (Listx (Right xs) (Just x) s) = do { ys <- mapM f xs; y <- f x; return((Listx (Right ys) (Just y) s))}
extM f (Listx (Left xs) (Just x) s) = do { y <- f x; ys <- mapM f xs; return((Listx (Left ys) (Just y) s))}
extM f (Listx xs' Nothing s) = do { ys <- mapM f xs; return((Listx (lr ys) Nothing s))}
where (lr, xs) = outLR xs'
extM f (Natx n (Just x) s) = do { y <- f x; return((Natx n (Just y) s))}
extM f (Natx n Nothing s) = return((Natx n Nothing s))
extM f (Unitx s) = return(Unitx s)
extM f (Itemx x s) = do { y <- f x; return((Itemx y s))}
extM f (Pairx xs' s) = do { ys <- mapM f xs; return((Pairx (lr ys) s))}
where (lr, xs) = outLR xs'
extM f (Recordx (Right xs) (Just x) s) = do { ys <- mapM g xs; y <- f x; return(Recordx (Right ys) (Just y) s)}
where g (x,y) = do { a <- f x; b <- f y; return(a,b) }
extM f (Recordx (Left xs) (Just x) s) = do { y <- f x; ys <- mapM g xs; return(Recordx (Left ys) (Just y) s)}
where g (x,y) = do { a <- f x; b <- f y; return(a,b) }
extM f (Recordx xs' Nothing s) = do { ys <- mapM g xs; return(Recordx (lr ys) Nothing s)}
where g (x,y) = do { a <- f x; b <- f y; return(a,b) }
(lr, xs) = outLR xs'
extM f (Tickx n x s) = do { y <- f x; return((Tickx n y s))}
extM f (Applicativex x s) = do { y <- f x; return((Applicativex y s))}
threadL f [] n = return([],n)
threadL f (x:xs) n =
do { (x',n1) <- f x n
; (xs',n2) <- threadL f xs n1
; return(x' : xs', n2)}
threadPair f (x,y) n = do { (a,n1) <- f x n; (b,n2) <- f y n1; return((a,b),n2)}
extThread :: Monad m => (b -> c -> m(d,c)) -> c -> Extension b -> m(Extension d,c)
extThread f n (Listx (Right xs) (Just x) s) =
do { (ys,n1) <- threadL f xs n; (y,n2) <- f x n1; return(Listx (Right ys) (Just y) s,n2)}
extThread f n (Listx (Left xs) (Just x) s) =
do { (y,n1) <- f x n; (ys,n2) <- threadL f xs n1; return(Listx (Left ys) (Just y) s,n2)}
extThread f n (Listx xs' Nothing s) =
do { (ys,n1) <- threadL f xs n; return(Listx (lr ys) Nothing s,n1)}
where (lr, xs) = outLR xs'
extThread f n (Natx m (Just x) s) = do { (y,n1) <- f x n; return(Natx m (Just y) s,n1)}
extThread f n (Natx m Nothing s) = return(Natx m Nothing s,n)
extThread f n (Unitx s) = return(Unitx s,n)
extThread f n (Itemx x s) = do { (y,n1) <- f x n; return(Itemx y s,n1)}
extThread f n (Pairx xs' s) = do { (ys,n1) <- threadL f xs n; return(Pairx (lr ys) s,n1)}
where (lr, xs) = outLR xs'
extThread f n (Recordx (Right xs) (Just x) s) =
do { (ys,n1) <- threadL (threadPair f) xs n; (y,n2) <- f x n1; return(Recordx (Right ys) (Just y) s,n2)}
extThread f n (Recordx (Left xs) (Just x) s) =
do { (y,n1) <- f x n; (ys,n2) <- threadL (threadPair f) xs n1; return(Recordx (Left ys) (Just y) s,n2)}
extThread f n (Recordx xs' Nothing s) =
do { (ys,n1) <- threadL (threadPair f) xs n; return(Recordx (lr ys) Nothing s,n1)}
where (lr, xs) = outLR xs'
extThread f n (Tickx m x s) = do { (y,n1) <- f x n; return(Tickx m y s,n1)}
cross f (x,y) = (f x,f y)
instance Functor Extension where
fmap f (Listx xs' (Just x) s) = (Listx (lr (map f xs)) (Just(f x)) s)
where (lr, xs) = outLR xs'
fmap f (Listx xs' Nothing s) = (Listx (lr (map f xs)) Nothing s)
where (lr, xs) = outLR xs'
fmap f (Natx n (Just x) s) = (Natx n (Just (f x)) s)
fmap f (Natx n Nothing s) = (Natx n Nothing s)
fmap f (Unitx s) = (Unitx s)
fmap f (Itemx x s) = (Itemx (f x) s)
fmap f (Pairx xs' s) = (Pairx (lr $ map f xs) s)
where (lr, xs) = outLR xs'
fmap f (Recordx xs' (Just x) s) = (Recordx (lr (map (cross f) xs)) (Just(f x)) s)
where (lr, xs) = outLR xs'
fmap f (Recordx xs' Nothing s) = (Recordx (lr (map (cross f) xs)) Nothing s)
where (lr, xs) = outLR xs'
fmap f (Tickx n x s) = (Tickx n (f x) s)
fmap f (Applicativex x s) = (Applicativex (f x) s)
--------------------------------------------------------
-- Other primitive operations like selection and equality
-- Equal if the same kind and the same key
instance Eq a => Eq (SynExt a) where
Ox == Ox = True
(Ix(k1,_,_,_,_,_,_,_,_)) == (Ix(k2,_,_,_,_,_,_,_,_)) = k1==k2
(Parsex(k1,_,_,_)) == (Parsex(k2,_,_,_)) = k1==k2
_ == _ = False
synKey Ox = ""
synKey (Ix (s,_,_,_,_,_,_,_,_)) = s
synKey (Parsex(s,_,_,_)) = s
synName Ox = ""
synName (Ix (s,Just(Right _),_,_,_,_,_,_,_)) = "List"
synName (Ix (s,Just(Left _),_,_,_,_,_,_,_)) = "LeftList"
synName (Ix (s,_,Just _,_,_,_,_,_,_)) = "Nat"
synName (Ix (s,_,_,Just(Right _),_,_,_,_,_)) = "Pair"
synName (Ix (s,_,_,Just(Left _),_,_,_,_,_)) = "LeftPair"
synName (Ix (s,_,_,_,Just(Right _),_,_,_,_)) = "Record"
synName (Ix (s,_,_,_,Just(Left _),_,_,_,_)) = "LeftRecord"
synName (Ix (s,_,_,_,_,Just _,_,_,_)) = "Tick"
synName (Ix (s,_,_,_,_,_,Just _,_,_)) = "Unit"
synName (Ix (s,_,_,_,_,_,_,Just _,_)) = "Item"
synName (Ix (s,_,_,_,_,_,_,_,Just _)) = "Applicative"
synName (Parsex (s,_,_,_)) = "Parse"
-- Both the name and the type match. Different types (i.e. List,Nat,Pair)
-- can use the same name.
matchExt (Listx (Right _) _ s) (Ix(t,Just(Right _),_,_,_,_,_,_,_)) | s==t = return True
matchExt (Listx (Left _) _ s) (Ix(t,Just(Left _),_,_,_,_,_,_,_)) | s==t = return True
matchExt (Natx _ _ s) (Ix(t,_,Just _,_,_,_,_,_,_)) | s==t = return True
matchExt (Unitx s) (Ix(t,_,_,_,_,_,Just _,_,_)) | s==t = return True
matchExt (Itemx _ s) (Ix(t,_,_,_,_,_,_,Just _,_)) | s==t = return True
matchExt (Pairx (Right _) s) (Ix(t,_,_,Just(Right _),_,_,_,_,_)) | s==t = return True
matchExt (Pairx (Left _) s) (Ix(t,_,_,Just(Left _),_,_,_,_,_)) | s==t = return True
matchExt (Recordx (Right _) _ s) (Ix(t,_,_,_,Just(Right _),_,_,_,_)) | s==t = return True
matchExt (Recordx (Left _) _ s) (Ix(t,_,_,_,Just(Left _),_,_,_,_)) | s==t = return True
matchExt (Tickx _ _ s) (Ix(t,_,_,_,_,Just _,_,_,_)) | s==t = return True
matchExt (Applicativex _ s) (Ix(t,_,_,_,_,_,_,_,Just _)) | s==t = return True
matchExt _ _ = return False
----------------------------------------------------------
-- Building such objects in an abstract manner
findM:: Monad m => String -> (a -> m Bool) -> [a] -> m a
findM mes p [] = fail mes
findM mes p (x:xs) =
do { b <- p x
; if b then return x else findM mes p xs}
-- harmonizeExt: correct inevitable little errors that happened during parsing
--
harmonizeExt x@(Listx (Right xs) Nothing s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Listx (Left xs) Nothing s
harmonizeExt x@(Listx (Right [h]) (Just t) s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Listx (Left [t]) (Just h) s
harmonizeExt x@(Recordx (Right xs) Nothing s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Recordx (Left xs) Nothing s
harmonizeExt x@(Pairx (Right xs) s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Pairx (Left xs) s
harmonizeExt x@(Itemx e s) ys = case findM "" (matchExt x') ys of
Nothing -> return x
Just _ -> return x'
where x' = Applicativex e s
harmonizeExt x _ = return x
data ApplicativeSyntaxDict a = AD { var :: a -> a
, app :: a -> a -> a
, lam :: a -> a -> a
, lt :: a -> a -> a -> a }
class ApplicativeSyntax a where
expandApplicative :: Show a => ApplicativeSyntaxDict a -> a -> a
expandApplicative _ a = error ("Cannot expand applicative: "++show a)
rot3 f a b c = f c a b
buildExt :: (Show c,Show b,Monad m,ApplicativeSyntax c) => String -> (b -> c,b -> c -> c,b -> c -> c -> c,b -> c -> c -> c -> c) ->
Extension c -> [SynExt b] -> m c
buildExt loc (lift0,lift1,lift2,lift3) x ys =
do { x <- harmonizeExt x ys
; y <- findM ("\nAt "++loc++
"\nCan't find a "++extName x++" syntax extension called: '"++
extKey x++"', for "++show x++"\n "++plistf show "" ys "\n " "")
(matchExt x) ys
; case (x,y) of
(Listx (Right xs) (Just x) _,Ix(tag,Just(Right(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (lift2 cons) x xs)
(Listx (Left xs) (Just x) _,Ix(tag,Just(Left(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (flip $ lift2 cons) x (reverse xs))
(Listx (Right xs) Nothing _,Ix(tag,Just(Right(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (lift2 cons) (lift0 nil) xs)
(Listx (Left xs) Nothing _,Ix(tag,Just(Left(nil,cons)),_,_,_,_,_,_,_)) -> return(foldr (flip $ lift2 cons) (lift0 nil) (reverse xs))
(Recordx (Right xs) (Just x) _,Ix(tag,_,_,_,Just(Right(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(lift3 cons)) x xs)
(Recordx (Left xs) (Just x) _,Ix(tag,_,_,_,Just(Left(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(rot3 $ lift3 cons)) x (reverse xs))
(Recordx (Right xs) Nothing _,Ix(tag,_,_,_,Just(Right(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(lift3 cons)) (lift0 nil) xs)
(Recordx (Left xs) Nothing _,Ix(tag,_,_,_,Just(Left(nil,cons)),_,_,_,_)) -> return(foldr (uncurry(rot3 $ lift3 cons)) (lift0 nil) (reverse xs))
(Tickx n x _,Ix(tag,_,_,_,_,Just tick,_,_,_)) -> return(buildNat x (lift1 tick) n)
(Natx n (Just x) _,Ix(tag,_,Just(zero,succ),_,_,_,_,_,_)) -> return(buildNat x (lift1 succ) n)
(Natx n Nothing _,Ix(tag,_,Just(zero,succ),_,_,_,_,_,_)) -> return(buildNat (lift0 zero) (lift1 succ) n)
(Unitx _,Ix(tag,_,_,_,_,_,Just unit,_,_)) -> return(buildUnit (lift0 unit))
(Itemx x _,Ix(tag,_,_,_,_,_,_,Just item,_)) -> return(buildItem (lift1 item) x)
(Pairx (Right xs) _,Ix(tag,_,_,Just(Right pair),_,_,_,_,_)) -> return(buildTuple (lift2 pair) xs)
(Pairx (Left xs) _,Ix(tag,_,_,Just(Left pair),_,_,_,_,_)) -> return(buildTuple (flip $ lift2 pair) (reverse xs))
(Applicativex x _,Ix(tag,_,_,_,_,_,_,_,Just (va,ap,la,le))) -> return(expandApplicative dict x)
where dict = AD {var = lift1 va, app = lift2 ap, lam = lift2 la, lt = lift3 le}
_ -> fail ("\nSyntax extension: "++extKey x++" doesn't match use, at "++loc)}
buildNat :: (Eq a, Num a) => b -> (b -> b) -> a -> b
buildNat z s 0 = z
buildNat z s n = s(buildNat z s (n-1))
buildUnit unit = unit
buildItem item i = item i
buildTuple pair [] = error "No empty tuples: ()"
buildTuple pair [p] = p
buildTuple pair [x,y] = pair x y
buildTuple pair (x:xs) = pair x (buildTuple pair xs)
flat2 [] = []
flat2 ((a,b):xs) = a : b : flat2 xs
-----------------------------------------------------------------------
-- extensions for predefined data structures
listx = Ix("",Just$Right("[]",":"),Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing) -- Lx("","[]",":")
natx = Ix("n",Nothing,Just("Z","S"),Nothing,Nothing,Nothing,Nothing,Nothing,Nothing) -- Nx("n","Z","S")
pairx = Ix("",Nothing,Nothing,Just$Right "(,)",Nothing,Nothing,Nothing,Nothing,Nothing) -- Px("","(,)")
recordx = Ix("",Nothing,Nothing,Nothing,Just$Right("Rnil","Rcons"),Nothing,Nothing,Nothing,Nothing) -- Rx("","Rnil","Rcons")
tickx tag tick = Ix(tag,Nothing,Nothing,Nothing,Nothing,Just tick,Nothing,Nothing,Nothing)
normalList (Ix("",Just(Right("[]",":")),_,_,_,_,_,_,_)) = True
normalList _ = False
------------------------------------------------------
-- Recognizing Extension constructors
listCons c (Ix(k,Just(Right(nil,cons)),_,_,_,_,_,_,_)) = c==cons
listCons c _ = False
listNil c (Ix(k,Just(Right(nil,cons)),_,_,_,_,_,_,_)) = c==nil
listNil c _ = False
leftListCons c (Ix(k,Just(Left(nil,cons)),_,_,_,_,_,_,_)) = c==cons
leftListCons c _ = False
leftListNil c (Ix(k,Just(Left(nil,cons)),_,_,_,_,_,_,_)) = c==nil
leftListNil c _ = False
natZero c (Ix(k,_,Just(z,s),_,_,_,_,_,_)) = c==z
natZero c _ = False
natSucc c (Ix(k,_,Just(z,s),_,_,_,_,_,_)) = c==s
natSucc c _ = False
unitUnit c (Ix(k,_,_,_,_,_,Just unit,_,_)) = c==unit
unitUnit c _ = False
itemItem c (Ix(k,_,_,_,_,_,_,Just item,_)) = c==item
itemItem c _ = False
pairProd c (Ix(k,_,_,Just(Right prod),_,_,_,_,_)) = c==prod
pairProd c _ = False
leftPairProd c (Ix(k,_,_,Just(Left prod),_,_,_,_,_)) = c==prod
leftPairProd c _ = False
recordCons c (Ix(k,_,_,_,Just(Right(nil,cons)),_,_,_,_)) = c==cons
recordCons c _ = False
recordNil c (Ix(k,_,_,_,Just(Right(nil,cons)),_,_,_,_)) = c==nil
recordNil c _ = False
leftRecordCons c (Ix(k,_,_,_,Just(Left(nil,cons)),_,_,_,_)) = c==cons
leftRecordCons c _ = False
leftRecordNil c (Ix(k,_,_,_,Just(Left(nil,cons)),_,_,_,_)) = c==nil
leftRecordNil c _ = False
tickSucc c (Ix(k,_,_,_,_,Just succ,_,_,_)) = c==succ
tickSucc c _ = False
applicativeVar c (Ix(k,_,_,_,_,_,_,_,Just (var,_,_,_))) = c==var
applicativeVar _ _ = False
applicativeApply c (Ix(k,_,_,_,_,_,_,_,Just (_,app,_,_))) = c==app
applicativeApply _ _ = False
-- recognizing extension tags
listExt c x = listCons c x || listNil c x
leftListExt c x = leftListCons c x || leftListNil c x
natExt c x = natZero c x || natSucc c x
recordExt c x = recordCons c x || recordNil c x
leftRecordExt c x = leftRecordCons c x || leftRecordNil c x
-----------------------------------------------------------
-- Parsers for Syntactic Extensions
-- #"abc" [x,y; zs]i #4 4i (2+x)i (a,b,c)i {a=Int,b=String; r}i
semiTailSeq left right elem tail buildf =
do { lexeme left
; xs <- sepBy elem comma
; x <- (do { semi; y <- tail; return(Just y)}) <|>
(return Nothing)
; right -- No lexeme here because the tag must follow immediately
; tag <- many (lower <|> char '\'')
; return(buildf xs x tag)}
semiHeadSeq left right head elem buildf =
do { lexeme left
; x <- head
; semi
; xs <- sepBy elem comma
; right -- No lexeme here because the tag must follow immediately
; tag <- many (lower <|> char '\'')
; return(buildf (Just x) xs tag)}
--extP :: Parsec [Char] u a -> Parsec [Char] u (Extension a)
extP p = try(lexeme(try(listP p) <|> leftListP p <|> parensP p <|> try(recP p) <|> leftRecP p))
where listP p = semiTailSeq (char '[') (char ']') p p (\xs x t -> Listx (Right xs) x t)
leftListP p = semiHeadSeq (char '[') (char ']') p p (\x xs t -> Listx (Left xs) x t)
recP p = semiTailSeq (char '{') (char '}') pair p (\xs x t -> Recordx (Right xs) x t)
where pair = do { x <- p; symbol "="; y <- p; return(x,y)}
leftRecP p = semiHeadSeq (char '{') (char '}') p pair (\x xs t -> Recordx (Left xs) x t)
where pair = do { x <- p; symbol "="; y <- p; return(x,y)}
parensP p =
do { f <- try(incr p) <|> try(seqX p) <|> try(tickP p)
; tag <- many lower
; return(f tag)}
incr p =
do { lexeme (char '(')
; n <- lexeme natNoSpace
; symbol "+"; x <- p
; char ')'
; return(Natx n (Just x))}
tickP p =
do { lexeme (char '(')
; x <- p
; symbol "`";
; n <- lexeme natNoSpace
; char ')'
; return(Tickx n x)}
seqX p =
do { lexeme (char '(')
; xs <- sepBy p comma
; char ')'
; return(pairlike xs)}
where pairlike xs "" = Pairx (Right xs) ""
pairlike [] tag = Unitx tag
pairlike [x] tag = Itemx x tag
pairlike xs tag = Pairx (Right xs) tag
--natP :: Parsec [Char] u (Extension a)
natP = try $ lexeme $
(do{ satisfy ('#'==); n <- natNoSpace; return(Natx n Nothing "n")}) <|>
(do{ n <- natNoSpace; tag <- many lower; return(Natx n Nothing tag)})
---------------------------------------------------------------------
mergey ("List",[a,b]) (Ix(k,Nothing,n,p,r,t,u,i,ap)) = Ix(k,Just$Right(a,b),n,p,r,t,u,i,ap)
mergey ("LeftList",[a,b]) (Ix(k,Nothing,n,p,r,t,u,i,ap)) = Ix(k,Just$Left(a,b),n,p,r,t,u,i,ap)
mergey ("Nat",[a,b]) (Ix(k,l,Nothing,p,r,t,u,i,ap)) = Ix(k,l,Just(a,b),p,r,t,u,i,ap)
mergey ("Unit",[a]) (Ix(k,l,n,p,r,t,Nothing,i,ap)) = Ix(k,l,n,p,r,t,Just a,i,ap)
mergey ("Item",[a]) (Ix(k,l,n,p,r,t,u,Nothing,ap)) = Ix(k,l,n,p,r,t,u,Just a,ap)
mergey ("Pair",[a]) (Ix(k,l,n,Nothing,r,t,u,i,ap)) = Ix(k,l,n,Just$Right a,r,t,u,i,ap)
mergey ("LeftPair",[a]) (Ix(k,l,n,Nothing,r,t,u,i,ap)) = Ix(k,l,n,Just$Left a,r,t,u,i,ap)
mergey ("Record",[a,b]) (Ix(k,l,n,p,Nothing,t,u,i,ap)) = Ix(k,l,n,p,Just$Right(a,b),t,u,i,ap)
mergey ("LeftRecord",[a,b]) (Ix(k,l,n,p,Nothing,t,u,i,ap)) = Ix(k,l,n,p,Just$Left(a,b),t,u,i,ap)
mergey ("Tick",[a]) (Ix(k,l,n,p,r,Nothing,u,i,ap)) = Ix(k,l,n,p,r,Just a,u,i,ap)
mergey ("Applicative",[v,a,lam,lt]) (Ix(k,l,n,p,r,t,u,i,Nothing)) = Ix(k,l,n,p,r,t,u,i,Just (v,a,lam,lt))
mergey _ i = i
-----------------------------------------------------------
-- check that in a syntactic extension like:
-- deriving syntax(i) List(A,B) Nat(C,D) Tick(G)
-- that the constructors (A,B,C,D,G) have the correct arity for
-- the extension they belong to (0,2, 0,1, 1)
-- List Nat Tick
-- for each extension, the name of the roles, and their expected arities
expectedArities =
[("List",Just "LeftList",[("Nil ",0),("Cons ",2::Int)])
,("LeftList",Just "List",[("Nil ",0),("Snoc ",2)])
,("Nat" ,Nothing ,[("Zero ",0),("Succ ",1)])
,("Unit" ,Nothing ,[("Unit ",0)])
,("Item" ,Nothing ,[("Item ",1)])
,("Pair",Just "LeftPair",[("Pair ",2)])
,("LeftPair",Just "Pair",[("Pair ",2)])
,("Record",Just "LeftRecord",[("RecNil ",0),("RecCons",3)])
,("LeftRecord",Just "Record",[("RecNil ",0),("RecSnoc",3)])
,("Tick" ,Nothing ,[("Tick ",1)])
,("Applicative",Nothing ,[("Var ",1),("Apply ",2),("Lambda ",2),("Let ",3)])
]
-- Check a list of arities against the expected arities, indicate with
-- (False,_) if 1) arities don't match
-- 2) there are extra constructors with no corresponding role
-- 3) there are too few constructors for the roles of that extension
checkArities name style expected actual =
case (expected,actual) of
([],[]) -> []
((c,n):xs,(d,m):ys) -> (n==m,(c,show n,d,show m),arityfix (n==m) d)
: checkArities name style xs ys
([] ,(d,m):ys) -> (False,(" "," ",d++" unexpected extra constructor",show m),extrafix style d)
: checkArities name style [] ys
((c,n):xs,[] ) -> (False,(c,show n,"? - missing role.","?"),missingfix style c)
: checkArities name style xs []
where suffix OLD = " from the deriving clause."
suffix NEW = " from the constructors of the data declaration."
arityfix True d = ""
arityfix False d = "Fix the arity of "++d++" in the data declaration."
extrafix OLD d = "Remove, extra constructor "++detrail d++" from the data declaration."
extrafix NEW d = "Remove, extra constructor "++detrail d++" from the syntax clause for "++name++"."
missingfix OLD c = "Add a constructor for "++detrail c++" to the data declaration."
missingfix NEW c = "Add a constructor for "++detrail c++" to the syntax clause for "++name++"."
suggestFix style [] = ""
suggestFix style ((True,_,fix): xs) = suggestFix style xs
suggestFix style ((False,_,fix): xs) = "\n "++fix ++ suggestFix style xs
detrail xs = reverse (dropWhile (==' ') (reverse xs))
fstOfTriple (x,y,z) = x
dropMid (x,y,z) = (x,z)
-- If the extension name doesn't fit, report an error
badName name = Right ("\n'"++name++"' is not a valid syntactic extension name, choose from: "++
plistf fstOfTriple "" expectedArities ", " ".\n")
reportRepeated name = Just ("'"++name++"' syntactic extension cannot be specified twice.")
reportIncompatible (name, Just reversed, _) = Just ("'"++name++"' and '"++reversed++"' syntactic extensions cannot be specified together.")
wellFormed (("List",_,_):_) (name@"List") (Ix(tag,Just(Right _),_,_,_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("List",Just _, _):_) "List" (Ix(tag,Just(Left _),_,_,_,_,_,_,_)) = reportIncompatible syn
wellFormed (("LeftList",_,_):_) (name@"LeftList") (Ix(tag,Just(Left _),_,_,_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("LeftList", Just no, _):_) "LeftList" (Ix(tag,Just(Right _),_,_,_,_,_,_,_)) = reportIncompatible syn
wellFormed (("Nat",_,_):_) (name@"Nat") (Ix(tag,_,Just _,_,_,_,_,_,_)) = reportRepeated name
wellFormed (("Unit",_,_):_) (name@"Unit") (Ix(tag,_,_,_,_,_,Just _,_,_)) = reportRepeated name
wellFormed (("Item",_,_):_) (name@"Item") (Ix(tag,_,_,_,_,_,_,Just _,_)) = reportRepeated name
wellFormed (("Pair",_,_):_) (name@"Pair") (Ix(tag,_,_,Just(Left _),_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("Pair",Just _,_):_) "Pair" (Ix(tag,_,_,Just(Right _),_,_,_,_,_)) = reportIncompatible syn
wellFormed (("LeftPair",_,_):_) (name@"LeftPair") (Ix(tag,_,_,Just(Right _),_,_,_,_,_)) = reportRepeated name
wellFormed (syn@("LeftPair",Just _,_):_) "LeftPair" (Ix(tag,_,_,Just(Left _),_,_,_,_,_)) = reportIncompatible syn
wellFormed (("Record",_,_):_) (name@"Record") (Ix(tag,_,_,_,Just(Right _),_,_,_,_)) = reportRepeated name
wellFormed (syn@("Record",Just _,_):_) "Record" (Ix(tag,_,_,_,Just(Left _),_,_,_,_)) = reportIncompatible syn
wellFormed (("LeftRecord",_,_):_) (name@"LeftRecord") (Ix(tag,_,_,_,Just(Left _),_,_,_,_)) = reportRepeated name
wellFormed (syn@("LeftRecord",Just _,_):_) "LeftRecord" (Ix(tag,_,_,_,Just(Right _),_,_,_,_)) = reportIncompatible syn
wellFormed (("Tick",_,_):_) (name@"Tick") (Ix(tag,_,_,_,_,Just _,_,_,_)) = reportRepeated name
wellFormed (("Applicative",_,_):_) (name@"Applicative") (Ix(tag,_,_,_,_,_,_,_,Just _)) = reportRepeated name
wellFormed (_:rest) name info = wellFormed rest name info
wellFormed [] _ _ = Nothing
-- Check a list of extensions, and build a Ix synExt data structure
checkMany :: SyntaxStyle -> String -> [(String,[(String,Int)])] -> Either (SynExt String) String
checkMany style tag [] = Left (Ix(tag,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing))
checkMany style tag ((name,args):more) =
case checkMany style tag more of
Right x -> Right x
Left info ->
case (lookup name (map dropMid expectedArities), wellFormed expectedArities name info) of
(Nothing, _) -> badName name
(_, Just problem) -> Right problem
(Just expected, _) -> if not good then Right s else Left info'
where ans = checkArities name style expected args
good = all fstOfTriple ans
printname = case style of
OLD -> name++"("++tag++")"
NEW -> name++ plistf fst "(" args "," ")"
g (bool,(c,n,d,m),fix) = concat["\n ",c," ",n," ",m," ",d]
s = concat(["\nError in syntactic extension declaration ",printname
,"\n Expected Actual"
,"\n Role Arity Arity Constructor\n"]
++ map g ans) ++ fixes
fixes = if good then "" else "\n\nPossible fix(es):" ++ suggestFix style ans
info' = mergey (name,map fst args) info
duplicates [] = []
duplicates (x:xs) = nub(if elem x xs then x : duplicates xs else duplicates xs)
liftEither (Left x) = return x
liftEither (Right x) = fail x
checkClause arityCs (name,args) =
do { let printname = name++plistf id "(" args "," ")"
; ys <- mapM (computeArity printname arityCs) args
; return(name,ys) }
computeArity printname arityCs c =
case lookup c arityCs of
Nothing -> fail (concat["\nThe name "++c++", in the syntax derivation "
,printname,",\nis not amongst the declared"
," constructors: ",plistf fst "" arityCs ", " ".\n"])
Just n -> return (c,n)
wExt = Ix("w",Just$Right("Nil","Cons"),Just("Zero","Succ"),Just$Right "Pair",Just$Right("RNil","RCons"),
Just "Next",Just "Unit",Just "Item",Just ("Var","Apply","Lambda","Let"))
go x = case checkMany OLD "tag" x of
Left x -> putStrLn(show x)
Right y -> putStrLn y
| cartazio/omega | src/SyntaxExt.hs | bsd-3-clause | 32,127 | 6 | 18 | 7,722 | 18,190 | 9,770 | 8,420 | 514 | 17 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
-- GIMP Toolkit (GTK) UTF aware string marshalling
--
-- Author : Axel Simon
--
-- Created: 22 June 2001
--
-- Copyright (c) 1999..2002 Axel Simon
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- |
-- Maintainer : gtk2hs-users@lists.sourceforge.net
-- Stability : provisional
-- Portability : portable (depends on GHC)
--
-- This module adds CString-like functions that handle UTF8 strings.
--
module System.Glib.UTFString (
GlibString(..),
readUTFString,
readCString,
withUTFStrings,
withUTFStringArray,
withUTFStringArray0,
peekUTFStringArray,
peekUTFStringArray0,
readUTFStringArray0,
UTFCorrection,
ofsToUTF,
ofsFromUTF,
glibToString,
stringToGlib,
DefaultGlibString,
GlibFilePath(..),
withUTFFilePaths,
withUTFFilePathArray,
withUTFFilePathArray0,
peekUTFFilePathArray0,
readUTFFilePathArray0
) where
import Codec.Binary.UTF8.String
import Control.Applicative ((<$>))
import Control.Monad (liftM)
import Data.Char (ord, chr)
import Data.Maybe (maybe)
import Data.String (IsString)
import Data.Monoid (Monoid)
import System.Glib.FFI
import qualified Data.Text as T (replace, length, pack, unpack, Text)
import qualified Data.Text.Foreign as T
(withCStringLen, peekCStringLen)
import Data.ByteString (useAsCString)
import Data.Text.Encoding (encodeUtf8)
class (IsString s, Monoid s, Show s) => GlibString s where
-- | Like 'withCString' but using the UTF-8 encoding.
--
withUTFString :: s -> (CString -> IO a) -> IO a
-- | Like 'withCStringLen' but using the UTF-8 encoding.
--
withUTFStringLen :: s -> (CStringLen -> IO a) -> IO a
-- | Like 'peekCString' but using the UTF-8 encoding.
--
peekUTFString :: CString -> IO s
-- | Like 'maybePeek' 'peekCString' but using the UTF-8 encoding to retrieve
-- UTF-8 from a 'CString' which may be the 'nullPtr'.
--
maybePeekUTFString :: CString -> IO (Maybe s)
-- | Like 'peekCStringLen' but using the UTF-8 encoding.
--
peekUTFStringLen :: CStringLen -> IO s
-- | Like 'newCString' but using the UTF-8 encoding.
--
newUTFString :: s -> IO CString
-- | Like Define newUTFStringLen to emit UTF-8.
--
newUTFStringLen :: s -> IO CStringLen
-- | Create a list of offset corrections.
--
genUTFOfs :: s -> UTFCorrection
-- | Length of the string in characters
--
stringLength :: s -> Int
-- Escape percent signs (used in MessageDialog)
unPrintf :: s -> s
-- GTK+ has a lot of asserts that the ptr is not NULL even if the length is 0
-- Until they fix this we need to fudge pointer values to keep the noise level
-- in the logs.
noNullPtrs :: CStringLen -> CStringLen
noNullPtrs (p, 0) | p == nullPtr = (plusPtr p 1, 0)
noNullPtrs s = s
instance GlibString [Char] where
withUTFString = withCAString . encodeString
withUTFStringLen s f = withCAStringLen (encodeString s) (f . noNullPtrs)
peekUTFString = liftM decodeString . peekCAString
maybePeekUTFString = liftM (maybe Nothing (Just . decodeString)) . maybePeek peekCAString
peekUTFStringLen = liftM decodeString . peekCAStringLen
newUTFString = newCAString . encodeString
newUTFStringLen = newCAStringLen . encodeString
genUTFOfs str = UTFCorrection (gUO 0 str)
where
gUO n [] = []
gUO n (x:xs) | ord x<=0x007F = gUO (n+1) xs
| ord x<=0x07FF = n:gUO (n+1) xs
| ord x<=0xFFFF = n:n:gUO (n+1) xs
| otherwise = n:n:n:gUO (n+1) xs
stringLength = length
unPrintf s = s >>= replace
where
replace '%' = "%%"
replace c = return c
foreign import ccall unsafe "string.h strlen" c_strlen
:: CString -> IO CSize
instance GlibString T.Text where
withUTFString = useAsCString . encodeUtf8
withUTFStringLen s f = T.withCStringLen s (f . noNullPtrs)
peekUTFString s = do
len <- c_strlen s
T.peekCStringLen (s, fromIntegral len)
maybePeekUTFString = maybePeek peekUTFString
peekUTFStringLen = T.peekCStringLen
newUTFString = newUTFString . T.unpack -- TODO optimize
newUTFStringLen = newUTFStringLen . T.unpack -- TODO optimize
genUTFOfs = genUTFOfs . T.unpack -- TODO optimize
stringLength = T.length
unPrintf = T.replace "%" "%%"
glibToString :: T.Text -> String
glibToString = T.unpack
stringToGlib :: String -> T.Text
stringToGlib = T.pack
-- | Like like 'peekUTFString' but then frees the string using g_free
--
readUTFString :: GlibString s => CString -> IO s
readUTFString strPtr = do
str <- peekUTFString strPtr
g_free strPtr
return str
-- | Like 'peekCString' but then frees the string using @g_free@.
--
readCString :: CString -> IO String
readCString strPtr = do
str <- peekCAString strPtr
g_free strPtr
return str
foreign import ccall unsafe "g_free"
g_free :: Ptr a -> IO ()
-- | Temporarily allocate a list of UTF-8 'CString's.
--
withUTFStrings :: GlibString s => [s] -> ([CString] -> IO a) -> IO a
withUTFStrings hsStrs = withUTFStrings' hsStrs []
where withUTFStrings' :: GlibString s => [s] -> [CString] -> ([CString] -> IO a) -> IO a
withUTFStrings' [] cs body = body (reverse cs)
withUTFStrings' (s:ss) cs body = withUTFString s $ \c ->
withUTFStrings' ss (c:cs) body
-- | Temporarily allocate an array of UTF-8 encoded 'CString's.
--
withUTFStringArray :: GlibString s => [s] -> (Ptr CString -> IO a) -> IO a
withUTFStringArray hsStr body =
withUTFStrings hsStr $ \cStrs -> do
withArray cStrs body
-- | Temporarily allocate a null-terminated array of UTF-8 encoded 'CString's.
--
withUTFStringArray0 :: GlibString s => [s] -> (Ptr CString -> IO a) -> IO a
withUTFStringArray0 hsStr body =
withUTFStrings hsStr $ \cStrs -> do
withArray0 nullPtr cStrs body
-- | Convert an array (of the given length) of UTF-8 encoded 'CString's to a
-- list of Haskell 'String's.
--
peekUTFStringArray :: GlibString s => Int -> Ptr CString -> IO [s]
peekUTFStringArray len cStrArr = do
cStrs <- peekArray len cStrArr
mapM peekUTFString cStrs
-- | Convert a null-terminated array of UTF-8 encoded 'CString's to a list of
-- Haskell 'String's.
--
peekUTFStringArray0 :: GlibString s => Ptr CString -> IO [s]
peekUTFStringArray0 cStrArr = do
cStrs <- peekArray0 nullPtr cStrArr
mapM peekUTFString cStrs
-- | Like 'peekUTFStringArray0' but then free the string array including all
-- strings.
--
-- To be used when functions indicate that their return value should be freed
-- with @g_strfreev@.
--
readUTFStringArray0 :: GlibString s => Ptr CString -> IO [s]
readUTFStringArray0 cStrArr | cStrArr == nullPtr = return []
| otherwise = do
cStrs <- peekArray0 nullPtr cStrArr
strings <- mapM peekUTFString cStrs
g_strfreev cStrArr
return strings
foreign import ccall unsafe "g_strfreev"
g_strfreev :: Ptr a -> IO ()
-- | Offset correction for String to UTF8 mapping.
--
newtype UTFCorrection = UTFCorrection [Int] deriving Show
ofsToUTF :: Int -> UTFCorrection -> Int
ofsToUTF n (UTFCorrection oc) = oTU oc
where
oTU [] = n
oTU (x:xs) | n<=x = n
| otherwise = 1+oTU xs
ofsFromUTF :: Int -> UTFCorrection -> Int
ofsFromUTF n (UTFCorrection oc) = oFU n oc
where
oFU n [] = n
oFU n (x:xs) | n<=x = n
| otherwise = oFU (n-1) xs
type DefaultGlibString = T.Text
class fp ~ FilePath => GlibFilePath fp where
withUTFFilePath :: fp -> (CString -> IO a) -> IO a
peekUTFFilePath :: CString -> IO fp
instance GlibFilePath FilePath where
withUTFFilePath = withUTFString . T.pack
peekUTFFilePath f = T.unpack <$> peekUTFString f
withUTFFilePaths :: GlibFilePath fp => [fp] -> ([CString] -> IO a) -> IO a
withUTFFilePaths hsStrs = withUTFFilePath' hsStrs []
where withUTFFilePath' :: GlibFilePath fp => [fp] -> [CString] -> ([CString] -> IO a) -> IO a
withUTFFilePath' [] cs body = body (reverse cs)
withUTFFilePath' (fp:fps) cs body = withUTFFilePath fp $ \c ->
withUTFFilePath' fps (c:cs) body
withUTFFilePathArray :: GlibFilePath fp => [fp] -> (Ptr CString -> IO a) -> IO a
withUTFFilePathArray hsFP body =
withUTFFilePaths hsFP $ \cStrs -> do
withArray cStrs body
withUTFFilePathArray0 :: GlibFilePath fp => [fp] -> (Ptr CString -> IO a) -> IO a
withUTFFilePathArray0 hsFP body =
withUTFFilePaths hsFP $ \cStrs -> do
withArray0 nullPtr cStrs body
peekUTFFilePathArray0 :: GlibFilePath fp => Ptr CString -> IO [fp]
peekUTFFilePathArray0 cStrArr = do
cStrs <- peekArray0 nullPtr cStrArr
mapM peekUTFFilePath cStrs
readUTFFilePathArray0 :: GlibFilePath fp => Ptr CString -> IO [fp]
readUTFFilePathArray0 cStrArr | cStrArr == nullPtr = return []
| otherwise = do
cStrs <- peekArray0 nullPtr cStrArr
fps <- mapM peekUTFFilePath cStrs
g_strfreev cStrArr
return fps
| mimi1vx/gtk2hs | glib/System/Glib/UTFString.hs | gpl-3.0 | 9,544 | 0 | 13 | 2,133 | 2,473 | 1,283 | 1,190 | 175 | 2 |
{-# OPTIONS_GHC -XDeriveDataTypeable -XStandaloneDeriving #-}
-- See Trac #1825
module ShouldFail where
import Data.OldTypeable
data T1 a = T1 a deriving( Typeable1 )
data T2 a b = T2 a b
deriving instance (Typeable a, Typeable b) => Typeable (T2 a b)
-- c.f. drv021.hs
| frantisekfarka/ghc-dsi | testsuite/tests/deriving/should_fail/drvfail014.hs | bsd-3-clause | 278 | 0 | 7 | 53 | 73 | 43 | 30 | -1 | -1 |
{-# LANGUAGE ParallelArrays #-}
{-# OPTIONS_GHC -fvectorise #-}
module DefsVect where
import Data.Array.Parallel
-- {-# VECTORISE SCALAR instance Eq Char #-}
-- {-# VECTORISE SCALAR instance Eq Float #-}
-- {-# VECTORISE SCALAR instance Ord Char #-}
-- {-# VECTORISE SCALAR instance Ord Float #-}
data MyBool = MyTrue | MyFalse
class Eq a => Cmp a where
cmp :: a -> a -> Bool
-- FIXME:
-- instance Cmp Int where
-- cmp = (==)
-- isFive :: (Eq a, Num a) => a -> Bool
isFive :: Int -> Bool
isFive x = x == 5
isEq :: Eq a => a -> Bool
isEq x = x == x
fiveEq :: Int -> Bool
fiveEq x = isFive x && isEq x
cmpArrs :: PArray Int -> PArray Int -> Bool
{-# NOINLINE cmpArrs #-}
cmpArrs v w = cmpArrs' (fromPArrayP v) (fromPArrayP w)
cmpArrs' :: [:Int:] -> [:Int:] -> Bool
cmpArrs' xs ys = andP [:x == y | x <- xs | y <- ys:]
isFives :: PArray Int -> Bool
{-# NOINLINE isFives #-}
isFives xs = isFives' (fromPArrayP xs)
isFives' :: [:Int:] -> Bool
isFives' xs = andP (mapP isFive xs)
isEqs :: PArray Int -> Bool
{-# NOINLINE isEqs #-}
isEqs xs = isEqs' (fromPArrayP xs)
isEqs' :: [:Int:] -> Bool
isEqs' xs = andP (mapP isEq xs)
| urbanslug/ghc | testsuite/tests/dph/classes/DefsVect.hs | bsd-3-clause | 1,139 | 16 | 8 | 247 | 379 | 199 | 180 | 28 | 1 |
rnd :: Int -> Double -> Double
rnd n x = (fromIntegral (floor (x * t))) / t
where t = 10^n
printLn :: Show a => a -> IO ()
printLn x = putStrLn $ show x
getPooled asuc an bsuc bn = (asuc + bsuc)/(an + bn)
getPooledSE asuc an bsuc bn = sqrt $ p*(1 - p)/an + p*(1-p)/bn
where p = getPooled asuc an bsuc bn
getTestStat asuc an bsuc bn = (ap - bp)/pooledSE
where ap = asuc / an
bp = bsuc / bn
pooledSE = getPooledSE asuc an bsuc bn
--getPopDevConf confLevel mean s n = (mean - errMargin, mean + errMargin)
-- where errMargin = (getCritZ confLevel) * s/(sqrt n)
getPopDevConf confLevel mean s n = (errMargin, sqrt n)
where errMargin = (getCritZ confLevel) * s/(sqrt n)
getMean xs = (fromIntegral $ sum xs) / (fromIntegral $ length xs)
getS xs = map xs
getSD s n = s/(sqrt n)
getSE as an bs bn = sqrt $ as^2/an + bs^2/bn
getPropSE p n = sqrt $ p*(1-p)/n
getPairPropSE ap an bp bn = sqrt $ ap*(1-ap)/an + bp*(1-bp)/bn
getCritZ z
| z == 0.90 = 1.645
| z == 0.95 = 1.96
| z == 0.99 = 2.575
| otherwise = z
getPropConfInterval confLevel ap bp se = (mean - errMargin, mean + errMargin)
where mean = ap - bp
errMargin = (getCritZ confLevel)*se
getConfInterval confLevel mean s n = (mean - errMargin, mean + errMargin)
where errMargin = (getCritZ confLevel) * (getSD s n)
getT ay by se = (ay - by)/se
getDF as an bs bn = truncate $ numer/denom
where arat = (as^2/an)
brat = (bs^2/bn)
numer = (^2) $ arat + brat
denom = arat^2/(an - 1) + brat^2/(bn - 1)
dunnoT mean tdf se = (mean - errMargin, mean + errMargin)
where errMargin = tdf * se
main = do
let an = 17
ay = 8.92
as = 3.45
bn = 25
by = 12.19
bs = 3.68
let t = getT ay by (getSE as an bs bn)
let df = getDF as an bs bn
printLn $ getSE as an bs bn
printLn $ rnd 2 t
printLn $ df
printLn $ dunnoT (ay - by) 2.70118130 (getSE as an bs bn)
| wd0/-stats | pooling.hs | mit | 1,958 | 0 | 12 | 558 | 972 | 498 | 474 | 51 | 1 |
module Y2016.M08.D19.Exercise where
import Data.Aeson
import Data.Set (Set)
import Data.MultiMap (MultiMap)
import Data.Twitter
import Graph.JSON.Cypher.Read.Graphs
import Graph.JSON.Cypher.Read.Tweets
import Y2016.M08.D15.Exercise (twitterGraphUrl)
{--
So, yesterday we extracted URLs from twitter graph-JSON.
Today we'll extract users, or, in twitter-parlance: tweeps.
From the twitter graph-data at twitterGraphUrl, extract the users. The user
node data has the following structure:
{"id":"504",
"labels":["User"],
"properties":{"screen_name":"1HaskellADay",
"name":"1HaskellADay",
"location":"U.S.A.",
"followers":1911,
"following":304,
"profile_image_url":"http://pbs.twimg.com/profile_images/437994037543309312/zkQSpXnp_normal.jpeg"}
Reify these data into a Haskell-type
--}
data User = YourRepresentationOfATwitterUser
instance FromJSON User where
parseJSON = undefined
readTwitterUsers :: FilePath -> IO [User]
readTwitterUsers = undefined
-- recall that readGraphJSON twitterGraphUrl gets us the twitter data
-- How many unique users are found in this data-set?
uniqueUsers :: [GraphJ] -> Set User
uniqueUsers = undefined
-- hint: define uniqueUsers to define readTwitterUsers
{-- BONUS -----------------------------------------------------------------
From Read.Tweets we can get [GraphJ] of the nodes and relations. Answer the
below:
What is the distribution of tweets to users?
--}
userTweets :: [GraphJ] -> MultiMap User (Tweet String) (Set (Tweet String))
userTweets = undefined
-- hint: recall that we related tweets to ids in Y2016.M08.D17.Exercise
-- hint: recall we extracted a set of unique tweets from graph-JSON in
-- Graph.JSON.Cypher.Read.Tweets
| geophf/1HaskellADay | exercises/HAD/Y2016/M08/D19/Exercise.hs | mit | 1,775 | 0 | 10 | 297 | 176 | 107 | 69 | 17 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Head where
import qualified Args as A
import qualified Data.ByteString.Lazy.Char8 as B
import Coreutils (bsContents)
head :: A.Args -> IO ()
head a = mapM op (A.files a) >>= B.putStr . B.intercalate "\n" where
op f = header f <$> case A.operation a of
A.Lines n -> firstLines f n
A.Bytes b -> firstBytes f b
A.LastLines n -> lastLines f n
A.LastBytes b -> lastBytes f b
header f = B.append $ if A.showHeaders a
then "==> " `B.append` B.pack f `B.append` " <==\n"
else ""
firstLines :: FilePath -> Int -> IO B.ByteString
firstLines f i = bsContents f >>= pure . B.unlines . take i . B.lines where
firstBytes :: FilePath -> Int -> IO B.ByteString
firstBytes f i = bsContents f >>= pure . B.take (fromIntegral i) where
lastLines :: FilePath -> Int -> IO B.ByteString
lastLines f i = bsContents f >>= pure . B.unlines . reverse . drop i . reverse . B.lines where
lastBytes :: FilePath -> Int -> IO B.ByteString
lastBytes f i = bsContents f >>= pure . B.reverse . B.drop (fromIntegral i) . B.reverse where
| mrak/coreutils.hs | src/head/Head.hs | mit | 1,231 | 0 | 12 | 378 | 451 | 227 | 224 | 24 | 5 |
module Database ( module DatabaseTypes
, mkInitialDatabase
, users
, updateLender
, searchLenders
, getOwnedItems
, getLendedItems
, getBorrowedItems
, updateItem
, searchItems
, deleteItem
, insertAsNewItem
, getItemCategoryName
, emptyItem, emptyBook, emptyGame, emptyCD, emptyDVD, emptyTool
) where
import Prelude hiding ((.), id) -- fclabels
import Control.Category ((.), id) -- fclabels
import Data.List
import Data.Maybe
import Data.Char
import Data.Map (Map)
import qualified Data.Map as Map
import ObloUtils
import DatabaseTypes
import qualified Imported
import Data.Label -- fclabels
import Debug.Trace
users :: Map String (String, String)
users = Map.fromList [ ("martijn", ("p", "Martijn"))
]
-- TODO: maybe this can be (a special) part of db?
searchLenders :: String -> Database -> [Lender]
searchLenders term db = [ lender | lender <- Map.elems $ get allLenders db
, any (\str -> map toLower term `isInfixOf` map toLower str)
[get lenderFirstName lender, get lenderLastName lender, get lenderZipCode lender, get (lenderIdLogin . lenderId) lender]
]
updateLender :: LenderId -> (Lender -> Lender) -> Database -> Database
updateLender i f db =
let lender = unsafeLookup "updateLender" i $ get allLenders db
in modify allLenders (Map.insert i (let r = f lender in trace (show r) r)) db
-- add error
removeLender :: LenderId -> Database -> Database
removeLender i = modify allLenders (Map.delete i)
{-
newLender :: Database -> (LenLenderatabase)
newLender db =
let ids = [ i | LenderId i <- map fst (Map.toList $ allLenders db) ]
newId = LenderId $ if null ids then 0 else (maximum ids + 1)
newLender = Lender newId "" "" []
in ( newLender, db { allLenders = Map.insert newId newLender (allLenders db) } )
-}
getItemIdNr item = get (itemIdNr . itemId) item
noItemId :: ItemId
noItemId = ItemId (-1)
assignUniqueItemIds :: [Item] -> [Item]
assignUniqueItemIds items = [ set itemId (ItemId i) item | (i,item) <- zip [0..] items ]
-- assign
assignItems :: [Item] -> [Lender] -> [Lender]
assignItems allItems allLenders = [ set lenderItems myItems lender
| lender <- allLenders
, let myItems = map (get itemId) $ filter ((==get lenderId lender) .get itemOwner) allItems
]
searchItems :: String -> Database -> [Item]
searchItems term db = [ item | item <- Map.elems $ get allItems db
, any (\str -> map toLower term `isInfixOf` map toLower str) $
[get (lenderIdLogin . itemOwner) item, show $ get itemPrice item, get itemName item, get itemDescr item ] ++
(categorySearchFields $ get itemCategory item)
]
where categorySearchFields Book{ _bookAuthor=f1, _bookGenre=f2} = [f1, f2]
categorySearchFields Game{ _gamePlatform=f1, _gameDeveloper=f2, _gameGenre=f3} = [f1,f2,f3]
categorySearchFields DVD{ _dvdMovieOrSeries=f1, _dvdDirector=f2, _dvdGenre=f3 } = [if f1 == Movie then "film" else "serie",f2,f3]
categorySearchFields CD{ _cdArtist=f1, _cdGenre=f2 } = [f1,f2]
categorySearchFields Tool{} = []
categorySearchFields Electronics = []
categorySearchFields Misc = []
-- this is more efficient than looking up the lender and looking up all of its owned itemId's
getOwnedItems :: LenderId -> Database -> [Item]
getOwnedItems ownerId db = filter ((ownerId ==) . (get itemOwner)) $ Map.elems (get allItems db)
getLendedItems :: LenderId -> Database -> [Item]
getLendedItems ownerId db = filter (isJust . get itemBorrowed) $ getOwnedItems ownerId db
getBorrowedItems :: LenderId -> Database -> [Item]
getBorrowedItems lenderId db = filter (maybe False (\borrower -> borrower == lenderId) . get itemBorrowed) $ Map.elems (get allItems db)
updateItem :: ItemId -> (Item -> Item) -> Database -> Database
updateItem i f db =
let visit = unsafeLookup "updateItem" i $ get allItems db
in modify allItems (Map.insert i (f visit)) db
-- Remove the item from allItems as well as from the lenderItems field of its owner.
deleteItem :: Item -> Database -> Database
deleteItem item db =
let db' = updateLender (get itemOwner item) (removeLenderItem (get itemId item)) db
in modify allItems (Map.delete (get itemId item)) db'
where removeLenderItem :: ItemId -> Lender -> Lender
removeLenderItem iId = modify lenderItems $ \is ->
let is' = delete iId is
in trace (show is ++ "\n"++ show (get itemId item)++"\n"++show is') $
is'
-- Assign a fresh id to newItem and insert in database as well as lenderItems field of its owner.
insertAsNewItem :: Item -> Database -> Database
insertAsNewItem itemWithoutId db =
let ids = [ i | ItemId i <- map fst (Map.toList $ get allItems db) ]
newId = ItemId $ if null ids then 0 else (maximum ids + 1)
newItem = set itemId newId itemWithoutId
db' = modify allItems (Map.insert newId newItem) db
in updateLender (get itemOwner newItem) (modify lenderItems $ (newId :) ) db'
getItemCategoryName :: Item -> String
getItemCategoryName item = case get itemCategory item of
Book{} -> "Book"
Game{} -> "Game"
CD{} -> "CD"
DVD{} -> "DVD"
Tool{} -> "Tool"
Electronics{} -> "Gadget"
Misc{} -> "Misc"
emptyItem :: LenderId -> Category -> Item
emptyItem lenderId category = Item (ItemId $ -1) lenderId 0 "" "" "" genericImage category Nothing
where genericImage = case category of
Book{} -> "book.png"
Game{} -> "game.png"
CD{} -> "cd.png"
DVD{} -> "dvd.png"
Tool{} -> "tool.png"
emptyBook, emptyGame, emptyCD, emptyDVD, emptyTool :: LenderId -> Item
emptyBook lenderId = emptyItem lenderId $ Book "" 0 "" "" 0 ""
emptyGame lenderId = emptyItem lenderId $ Game "" 0 "" ""
emptyCD lenderId = emptyItem lenderId $ CD "" 0 ""
emptyDVD lenderId = emptyItem lenderId $ DVD Movie "" "" 0 "" 0 "" 0 0
emptyTool lenderId = emptyItem lenderId $ Tool "" "" 0
mkInitialDatabase :: IO Database
mkInitialDatabase = return initialDatabase
initialDatabase :: Database
initialDatabase = Database
(Map.fromList $ map (\l -> (get lenderId l, l)) $ assignItems spullen Imported.lenders)
(Map.fromList [ (get itemId item,item) | item <- spullen ])
spullen = assignUniqueItemIds $
[ Item noItemId (LenderId "martijn") 3 "Grand Theft Auto 4"
"Wat is er tegenwoordig nog over van die legendarische 'American Dream'? Niko Bellic is net aan wal gestapt na een lange bootreis uit Europa en hoopt in Amerika zijn verleden te begraven. Zijn neef Roman droomt ervan het helemaal te maken in Liberty City, in het land van de onbegrensde mogelijkheden.\nZe raken in de schulden en komen in het criminele circuit terecht door toedoen van oplichters, dieven en ander tuig. Langzamerhand komen ze erachter dat ze hun dromen niet kunnen waarmaken in een stad waar alles draait om geld en status. Heb je genoeg geld, dan staan alle deuren voor je open. Zonder een cent beland je in de goot."
"Uitstekend"
"1.jpg"
(Game "Playstation 3" 2011 "Rockstar Games" "Action adventure / open world" )
(Just $ LenderId "peter")
, Item noItemId (LenderId "martijn") 2 "iPhone 3gs"
"Apple iPhone 3gs, 32Gb"
"Paar krasjes"
"2.jpg"
Electronics
(Just $ LenderId "tommy")
, Item noItemId (LenderId "peter") 1 "Boormachine"
"Het krachtige en compacte toestel Krachtig motor van 600 Watt, ideaal om te boren tot 10 mm boordiameter in metaal Bevestiging van boorspil in het lager voor hoge precisie Compact design en gering gewicht voor optimale bediening bij middelzware boortoepassingen Besturings-electronic voor exact aanboren Metalen snelspanboorhouder voor hoge precisie en lange levensduur Rechts- en linksdraaien Bijzonder geschikt voor boorgaten tot 10 mm in staal Functies: Rechts- en linksdraaien Electronic Softgrip Leveromvang: Snelspanboorhouder 1 - 10 mm"
"Goed"
"3.jpg"
(Tool "Bosch" "XP33" 2005)
Nothing
, Item noItemId (LenderId "peter") 1 "Spyder calibratie-apparaat"
"De Datacolor Spyder 4 Elite geeft nauwkeurig en natuurgetrouwe kleuren bij fotobewerkingen, films en games. Daarmee is hij geschikt voor professionele fotografen en andere creatievelingen. Verder is dit de eerste Spyder die iPhone en iPad ready is. Dit betekent dat hij via een app kan kalibreren met deze gadgets en de weergave van kleuren op je smartphone of tablet kan optimaliseren."
"Goed"
"4.jpg"
Electronics
Nothing
, Item noItemId (LenderId "tommy") 2 "Tomtom"
"Voor de prijsbewuste bestuurder die toch graag in breedbeeld navigeert is er de TomTom XL Classic. Uitermate gemakkelijk in gebruik - plug de 12V autoadapter in en begin onbezorgd aan je reis. Het IQ Routes systeem zorgt op ieder moment van de dag voor de snelste route."
"Goed"
"5.jpg"
Electronics
(Just $ LenderId "peter")
, Item noItemId (LenderId "tommy") 1 "Boormachine"
"De Makita Accuboormachine BDF343SHE Li-Ion 14,4V beschikt niet alleen over uitzonderlijke krachten, hij is ook nog eens bijzonder comfortabel. Hij heeft namelijk een ergonomisch ontwerp meegekregen van Makita. Zo weet u zeker dat u nooit meer last van uw polsen of ellebogen hebt na het klussen. Daarnaast zorgt het softgrip handvat er voor dat hij erg lekker in de hand ligt. En ook blijft liggen, want zelfs met bezwete handen hanteert u hem nog steeds moeiteloos. Dus wilt u een machine die kracht en gebruikscomfort combineert, dan is de Makita Accuboormachine BDF343SHE Li-Ion 14,4V de juiste keuze."
"Goed"
"6.jpg"
(Tool "Makita" "BDF343SHE" 2009)
Nothing
] ++ Imported.items
-- do we want extra params such as pig nrs in sub views?
-- error handling database access
-- Unclear: we need both pig ids and subview ids?
-- make clear why we need an explicit view, and the html rep is not enough.
| Oblosys/webviews | src/exec/BorrowIt/Database.hs | mit | 12,253 | 1 | 19 | 4,434 | 2,292 | 1,204 | 1,088 | 152 | 8 |
module Main (main) where
import Nauva.Server
import Nauva.Product.Template.Catalog (catalogApp)
main :: IO ()
main = devServer catalogApp
| wereHamster/nauva | product/template/catalog/dev/Main.hs | mit | 141 | 0 | 6 | 20 | 44 | 26 | 18 | 5 | 1 |
-- | Wheat. a library for expressing reversible codecs for binary
-- serialisation.
module Data.Wheat
( -- * Codecs
-- | A codec is conceptually a pair of an encoding function and a
-- decoding function. Codecs need to know the concrete types they
-- are dealing with: decoding uses lazy
-- 'Data.ByteString.Lazy.ByteString' and encoding uses
-- 'Data.ByteString.Builder.Builder', for efficiency reasons.
module Data.Wheat.Codecs
-- * Combinators
-- | A combinator is a function for combining two or more codecs
-- into a larger codec. Unlike codecs, a combinator does not need to
-- know the concrete type being encoded to or decoded from, the same
-- combinator can apply to any concrete types, whereas codecs would
-- need to be rewritten.
, module Data.Wheat.Combinators
-- * Types
-- | The codec types and associated functions. Each comes in two or
-- three flavours: the basic ('Codec', 'Encoder', and 'Decoder')
-- which is specialised to work with
-- 'Data.ByteString.Lazy.ByteString' and
-- 'Data.ByteString.Builder.Builder', and the generic ('GCodec',
-- 'GEncoder', 'GDecoder') which are fully generic in the underlying
-- concrete types, there is additionally a middle-ground codec type,
-- 'Codec''. Most of the library is written in terms of the generic
-- types, but users should be able to just use the more concrete
-- ones and have everything just work.
, module Data.Wheat.Types
) where
import Data.Wheat.Codecs
import Data.Wheat.Combinators
import Data.Wheat.Types
{-# ANN module ("HLint: ignore Use import/export shortcut" :: String) #-} | barrucadu/wheat | Data/Wheat.hs | mit | 1,624 | 0 | 5 | 305 | 73 | 58 | 15 | 9 | 0 |
-- Copyright (c) 2016-present, SoundCloud Ltd.
-- All rights reserved.
--
-- This source code is distributed under the terms of a MIT license,
-- found in the LICENSE file.
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Kubernetes.Model.V1.ObjectMeta
( ObjectMeta (..)
, name
, generateName
, namespace
, selfLink
, uid
, resourceVersion
, generation
, creationTimestamp
, deletionTimestamp
, deletionGracePeriodSeconds
, labels
, annotations
, mkObjectMeta
) where
import Control.Lens.TH (makeLenses)
import Data.Aeson.TH (defaultOptions, deriveJSON,
fieldLabelModifier)
import Data.Text (Text)
import GHC.Generics (Generic)
import Kubernetes.Model.V1.Any (Any)
import Prelude hiding (drop, error, max, min)
import qualified Prelude as P
import Test.QuickCheck (Arbitrary, arbitrary)
import Test.QuickCheck.Instances ()
-- | ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create.
data ObjectMeta = ObjectMeta
{ _name :: !(Maybe Text)
, _generateName :: !(Maybe Text)
, _namespace :: !(Maybe Text)
, _selfLink :: !(Maybe Text)
, _uid :: !(Maybe Text)
, _resourceVersion :: !(Maybe Text)
, _generation :: !(Maybe Integer)
, _creationTimestamp :: !(Maybe Text)
, _deletionTimestamp :: !(Maybe Text)
, _deletionGracePeriodSeconds :: !(Maybe Integer)
, _labels :: !(Maybe Any)
, _annotations :: !(Maybe Any)
} deriving (Show, Eq, Generic)
makeLenses ''ObjectMeta
$(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''ObjectMeta)
instance Arbitrary ObjectMeta where
arbitrary = ObjectMeta <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
-- | Use this method to build a ObjectMeta
mkObjectMeta :: ObjectMeta
mkObjectMeta = ObjectMeta Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
| soundcloud/haskell-kubernetes | lib/Kubernetes/Model/V1/ObjectMeta.hs | mit | 2,562 | 0 | 17 | 819 | 505 | 292 | 213 | 72 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Config
-- License : MIT (see the LICENSE file)
-- Maintainer : Felix Klein (klein@react.uni-saarland.de)
--
-- Configuration of the tool, set up via the command line arguments.
--
-----------------------------------------------------------------------------
{-# LANGUAGE
LambdaCase
, MultiParamTypeClasses
, TypeSynonymInstances
, FlexibleInstances
, FlexibleContexts
, RecordWildCards
#-}
-----------------------------------------------------------------------------
module Config
( Configuration(..)
, defaultCfg
, update
, verify
) where
-----------------------------------------------------------------------------
import Data.Convertible
( Convertible(..)
, ConvertError(..)
, safeConvert
, convert
)
import Data.Info
( name
, version
, defaultDelimiter
, defaultPrimeSymbol
, defaultAtSymbol
)
import Data.Maybe
( isJust
)
import Data.Types
( Semantics(..)
, Target(..)
)
import Data.Error
( Error
, parseError
, cfgError
)
import Writer.Formats
( WriteFormat(..)
)
import Text.Parsec.String
( Parser
)
import Text.Parsec
( (<|>)
, (<?>)
, char
, oneOf
, many
, alphaNum
)
import Control.Monad
( void
)
import Writer.Data
( WriteMode(..)
, QuoteMode(..)
)
import Text.Parsec.Prim
( parserZero
)
import Text.Parsec.Token
( GenLanguageDef(..)
, makeTokenParser
, stringLiteral
, identifier
, reserved
, reservedOp
, whiteSpace
)
import Text.Parsec.Language
( emptyDef
)
import qualified Text.Parsec as P
-----------------------------------------------------------------------------
-- | The data type contains all flags and settings
-- that can be adjusted to influence the behavior of the library:
data Configuration =
Configuration
{ inputFiles :: [FilePath]
-- ^ The list of input files containing the specifications.
, outputFile :: Maybe FilePath
-- ^ An optional path to the output file, the transformed
-- specification is written to.
, outputFormat :: WriteFormat
-- ^ The format specifiying the corresponding writer to use.
--
-- /(can be changed via a configuration file, use:/  
-- @ format = ... @ /)/
, outputMode :: WriteMode
-- ^ The output mode used by the writer.
--
-- /(can be changed via a configuration file, use:/  
-- @ mode = ... @ /)/
, quoteMode :: QuoteMode
-- ^ The quote mode used by the writer.
--
-- /(can be changed via a configuration file, use:/  
-- @ quote = ... @ /)/
, partFile :: Maybe String
-- ^ Optional path to a parition file, which is created if
-- set.
, busDelimiter :: String
-- ^ The delimiter string to seperate the bus index from the
-- signal name.
--
-- /(can be changed via a configuration file, use:/  
-- @ bus_delimiter = ... @ /)/
, primeSymbol :: String
-- ^ The prime symbol \/ string representing primes in signals of
-- the input format.
--
-- /(can be changed via a configuration file, use:/  
-- @ prime_symbol = ... @ /)/
, atSymbol :: String
-- ^ The at symbol \/ string representing at symbols in signals
-- of the input format.
--
-- /(can be changed via a configuration file, use:/  
-- @ at_symbol = ... @ /)/
, fromStdin :: Bool
-- ^ A boolean flag specifying whether the input should be read
-- from STDIN or not.
, owSemantics :: Maybe Semantics
-- ^ An optional flag which allows to overwrite the semantics of
-- the given input specifications.
--
-- /(can be changed via a configuration file, use:/  
-- @ overwrite_semantics = ... @ /)/
, owTarget :: Maybe Target
-- ^ An optional flag which allows to overwrite the target of
-- the given input specifications.
--
-- /(can be changed via a configuration file, use:/  
-- @ overwrite_target = ... @ /)/
, owParameter :: [(String,Int)]
-- ^ An optional flag which allows to overwrite a list of
-- parameters of the given input specification.
, simplifyWeak :: Bool
-- ^ A boolean flag specifying whether weak simplifications
-- should be applied or not.
--
-- /(can be changed via a configuration file, use:/  
-- @ weak_simplify = ... @ /)/
, simplifyStrong :: Bool
-- ^ A boolean flag specifying whether strong simplifications
-- should be applied or not.
--
-- /(can be changed via a configuration file, use:/  
-- @ strong_simplify = ... @ /)/
, negNormalForm :: Bool
-- ^ A boolean flag specifying whether the given specification
-- should be turned into negation normal form.
--
-- /(can be changed via a configuration file, use:/  
-- @ negation_normal_form = ... @ /)/
, pushGlobally :: Bool
-- ^ A boolean flag specifying whether globally operators should
-- be pushed over conjunctions deeper into the formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ push_globally_inwards = ... @ /)/
, pushFinally :: Bool
-- ^ A boolean flag specifying whether finally operators should
-- be pushed over disjunctions deeper into the formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ push_finally_inwards = ... @ /)/
, pushNext :: Bool
-- ^ A boolean flag specifying whether next operators should be
-- pushed over conjunctions and disjunctions deeper into the
-- formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ push_next_inwards = ... @ /)/
, pullGlobally :: Bool
-- ^ A boolean flag specifying whether globally perators should
-- be pulled over conjunctions outside the formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ pull_globally_outwards = ... @ /)/
, pullFinally :: Bool
-- ^ A boolean flag specifying whether finally operators should
-- be pulled over disjunctions outside the formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ pull_finally_outwards = ... @ /)/
, pullNext :: Bool
-- ^ A boolean flag specifying whether next operators should be
-- pulled over conjunctions and disjunctions outside the
-- formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ pull_next_outwards = ... @ /)/
, noWeak :: Bool
-- ^ A boolean flag specifying whether weak until operators
-- should be replaced by alternative operators inside the
-- created formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ no_weak_until = ... @ /)/
, noRelease :: Bool
-- ^ A boolean flag specifying whether release operators should
-- be replaced by alternative operators inside the created
-- formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ no_release = ... @ /)/
, noFinally :: Bool
-- ^ A boolean flag specifying whether finally operators should
-- be replaced by alternative operators inside the created
-- formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ no_finally = ... @ /)/
, noGlobally :: Bool
-- ^ A boolean flag specifying whether globally operators should
-- be replaced by alternative operators inside the created
-- formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ no_globally = ... @ /)/
, noDerived :: Bool
-- ^ A boolean flag specifying whether any derived operators
-- should be replaced by alternative operators inside the
-- created formula.
--
-- /(can be changed via a configuration file, use:/  
-- @ no_derived = ... @ /)/
, cGR :: Bool
-- ^ A boolean flag specifying whether to check, whether the
-- input belongs to the class of Generalized Reactivity
-- specifications or not.
, check :: Bool
-- ^ A boolean flag specifying whether the given input files
-- should just be checked for syntactical and type correctenss.
, pTitle :: Bool
-- ^ A boolean flag specifying whether just the title of the
-- given input files should be printed or not.
, pDesc :: Bool
-- ^ A boolean flag specifying whether just the description of
-- the given input files should be printed or not.
, pSemantics :: Bool
-- ^ A boolean flag specifying whether just the semantics of
-- the given input files should be printed or not.
, pTarget :: Bool
-- ^ A boolean flag specifying whether just the target of the
-- given input files should be printed or not.
, pTags :: Bool
-- ^ A boolean flag specifying whether just the tag list of
-- the given input files should be printed or not,
, pParameters :: Bool
-- ^ A boolean flag specifying whether just the parameter list
-- of the given specification should be printed or not.
, pInputs :: Bool
-- ^ A boolean flag specifying whether just the input signals
-- of the given specification should be printed or not.
, pOutputs :: Bool
-- ^ A boolean flag specifying whether just the output signals
-- of the given specification should be printed or not.
, pInfo :: Bool
-- ^ A boolean flag specifying whether just the complete input
-- section of the given input files should be printed or not.
, pVersion :: Bool
-- ^ A boolean flag specifying whether the version info should
-- be printed or not.
, pHelp :: Bool
-- ^ A boolean flag specifying whether the help info should be
-- printed or not.
, pReadme :: Bool
-- ^ A boolean flag specifying whether the content of the README
-- file should be printed to STDOUT or not.
, pReadmeMd :: Bool
-- ^ A boolean flag specifying whether the content of the
-- README.md file should be printed to STDOUT or not.
, saveConfig :: [FilePath]
-- ^ List of file paths to store the current configuration.
} deriving (Eq, Ord)
-----------------------------------------------------------------------------
-- |
-- @
-- inputFiles = []
-- outputFile = Nothing
-- outputFormat = FULL
-- outputMode = Pretty
-- quoteMode = None
-- partFile = Nothing
-- busDelimiter = "_"
-- primeSymbol = "'"
-- atSymbol = "@"
-- fromStdin = False
-- owSemantics = Nothing
-- owTarget = Nothing
-- owParameter = []
-- simplifyWeak = False
-- simplifyStrong = False
-- negNormalForm = False
-- pushGlobally = False
-- pushFinally = False
-- pushNext = False
-- pullGlobally = False
-- pullFinally = False
-- pullNext = False
-- noWeak = False
-- noRelease = False
-- noFinally = False
-- noGlobally = False
-- noDerived = False
-- cGR = False
-- check = False
-- pTitle = False
-- pDesc = False
-- pSemantics = False
-- pTarget = False
-- pTags = False
-- pParameters = False
-- pInputs = False
-- pOutputs = False
-- pInfo = False
-- pVersion = False
-- pHelp = False
-- pReadme = False
-- pReadmeMd = False
-- saveConfig = []
-- @
defaultCfg
:: Configuration
defaultCfg = Configuration
{ inputFiles = []
, outputFile = Nothing
, outputFormat = FULL
, outputMode = Pretty
, quoteMode = NoQuotes
, partFile = Nothing
, busDelimiter = defaultDelimiter
, primeSymbol = defaultPrimeSymbol
, atSymbol = defaultAtSymbol
, fromStdin = False
, owSemantics = Nothing
, owTarget = Nothing
, owParameter = []
, simplifyWeak = False
, simplifyStrong = False
, negNormalForm = False
, pushGlobally = False
, pushFinally = False
, pushNext = False
, pullGlobally = False
, pullFinally = False
, pullNext = False
, noWeak = False
, noRelease = False
, noFinally = False
, noGlobally = False
, noDerived = False
, cGR = False
, check = False
, pTitle = False
, pDesc = False
, pSemantics = False
, pTarget = False
, pTags = False
, pParameters = False
, pInputs = False
, pOutputs = False
, pInfo = False
, pVersion = False
, pHelp = False
, pReadme = False
, pReadmeMd = False
, saveConfig = []
}
-----------------------------------------------------------------------------
-- | Verifies that a configuration does not contain invalid parameter
-- combinations.
verify
:: Configuration -> Either Error ()
verify Configuration{..}
| pHelp || pVersion || pReadme || pReadmeMd =
return ()
| null inputFiles && not fromStdin && null saveConfig =
cfgError
"No input specified."
| not (null inputFiles) && fromStdin =
cfgError
"Select either \"-in, --stdin\" or give an input file."
| pushGlobally && pullGlobally =
cfgError $
"Select either \"-pgi, --push-globally-inwards\" or " ++
"\"-pgo, --pull-globally-outwards\"."
| pushFinally && pullFinally =
cfgError $
"Select either \"-pfi, --push-finally-inwards\" or " ++
"\"-pfo, --pull-finally-outwards\"."
| pushNext && pullNext =
cfgError $
"Select either \"-pxi, --push-next-inwards\" or " ++
"\"-pxo, --pull-next-outwards\"."
| simplifyStrong && (pushGlobally || pushFinally ||
pushNext || noFinally ||
noGlobally || noDerived) =
cfgError $
"The flag 'Advanced Simplifications' cannot be combined " ++
"with any other non-included transformation."
| negNormalForm && noRelease && noGlobally && noWeak =
cfgError $
"The given combination of transformations " ++
"(negation normal form, no release operators, " ++
"no globally operators, and no weak until operatators)" ++
"is impossible to satisfy.\n" ++
"Remove at least one of these constraints."
| negNormalForm && noRelease && noDerived =
cfgError $
"The given combination of transformations " ++
"(negation normal form, no release operatators, " ++
"and no derived operators) is impossible to satisfy.\n" ++
"Remove at least one of these constraints."
| negNormalForm && noRelease &&
(noGlobally || noDerived) && outputFormat == LTLXBA =
cfgError $
"The given combination of transformations " ++
"(negation normal form, no release operators, and " ++
"no globally / derived operators) " ++
"is impossible to satisfy when outputting to the " ++
"LTL2BA / LTL3BA format, since it does not support " ++
"the weak until operator.\n" ++
"Remove at least one of these constraints."
| negNormalForm && noRelease &&
(noGlobally || noDerived) && outputFormat == WRING =
cfgError $
"The given combination of transformations " ++
"(negation normal form, no release operators, and " ++
"no globally / derived operators) " ++
"is impossible to satisfy when outputting to the " ++
"Wring format, since it does not support " ++
"the weak until operator.\n" ++
"Remove at least one of these constraints."
| negNormalForm && noRelease &&
(noGlobally || noDerived) && outputFormat == LILY =
cfgError $
"The given combination of transformations " ++
"(negation normal form, no release operators, and " ++
"no globally / derived operators) " ++
"is impossible to satisfy when outputting to the " ++
"Lily format, since it does not support " ++
"the weak until operator.\n" ++
"Remove at least one of these constraints."
| negNormalForm &&
(noGlobally || noDerived) && outputFormat == ACACIA =
cfgError $
"The given combination of transformations " ++
"(negation normal form, no release operators, and " ++
"no globally / derived operators) " ++
"is impossible to satisfy when outputting to the " ++
"Acacia/Aciacia+ format, since it does not support " ++
"the weak until nor the release operator.\n" ++
"Remove at least one of these constraints."
| negNormalForm && noRelease &&
(noGlobally || noDerived) && outputFormat == SMV =
cfgError $
"The given combination of transformations " ++
"(negation normal form, no release operators, and " ++
"no globally / derived operators) " ++
"is impossible to satisfy when outputting to the " ++
"SMV format, since it does not support " ++
"the weak until operator.\n" ++
"Remove at least one of these constraints."
| negNormalForm && noGlobally && outputFormat == PSL =
cfgError $
"The given combination of transformations " ++
"(negation normal form and no globally operators)" ++
"is impossible to satisfy when outputting to the " ++
"PSL format, since it does not support " ++
"the weak until and the release operator.\n" ++
"Remove at least one of these constraints."
| negNormalForm && noDerived && outputFormat == PSL =
cfgError $
"The given combination of transformations " ++
"(negation normal form and no derived operators)" ++
"is impossible to satisfy when outputting to the " ++
"PSL format, since it does not support " ++
"the release operator.\n" ++
"Remove at least one of these constraints."
| negNormalForm && noDerived && outputFormat == UNBEAST =
cfgError $
"The given combination of transformations " ++
"(negation normal form and no derived operators)" ++
"is impossible to satisfy when outputting to the " ++
"UNBEAST format, since it does not support " ++
"the release operator.\n" ++
"Remove at least one of these constraints."
| outputFormat == FULL &&
(isJust owSemantics || isJust owTarget ||
simplifyWeak || simplifyStrong || negNormalForm ||
pushGlobally || pushFinally || pushNext ||
pullGlobally || pullFinally || pullNext ||
noWeak || noRelease || noFinally || noGlobally ||
noDerived) =
cfgError $
"Applying adaptions is only possible, when transforming to " ++
"low level backends.\n Returning full TLSF only " ++
"allows to change parameters."
| otherwise = return ()
-----------------------------------------------------------------------------
-- | Creates the content of a parsable configuration file restricted
-- to supported configuration file parameters.
instance Convertible Configuration String where
safeConvert Configuration{..} = return $ unlines
[ comment "This configuration file has been automatically " ++
"generated using"
, comment $ name ++ " (v" ++ version ++
"). To reload the configuration pass this file to "
, comment $ name ++ " via '-c <path to config file>'. " ++
"Configuration files can be"
, comment $ "used together with arguments passed via the command " ++
"line interface."
, comment $ "If a parameter occurs multiple times, then it is " ++
"assigned the last"
, comment $ "value in the order of declaration. The same principle " ++
"applies, if"
, comment "multiple configuration files are loaded."
, comment ""
, comment $ "All entries of this configuration file are optional. " ++
"If not set,"
, comment $ "either the default values or the values, passed via " ++
"the command"
, comment "line arguments, are used."
, emptyline
, comment $ "Specifies the format of the generated output file. " ++
"Use "
, comment $ "\"" ++ name ++ " --help\" to check for possible " ++
"values."
, set "format" $ convert $ outputFormat
, emptyline
, comment $ "Specifies the representation mode of the output. " ++
"Use "
, comment $ "\"" ++ name ++ " --help\" to check for possible " ++
"values."
, set "mode" $ convert $ outputMode
, emptyline
, comment $ "Specifies the quote mode of the output. " ++
"Use "
, comment $ "\"" ++ name ++ " --help\" to check for possible " ++
"values."
, set "quote" $ convert $ quoteMode
, emptyline
, comment $ "Specifies the bus delimiter symbol / string. The " ++
"value has to be "
, comment "encapsulated into quotation marks."
, set "bus_delimiter" $ "\"" ++ busDelimiter ++ "\""
, emptyline
, comment $ "Specifies the output representation of prime " ++
"symbols. The value "
, comment "has to be encapsulated into quotation marks."
, set "prime_symbol" $ "\"" ++ primeSymbol ++ "\""
, emptyline
, comment $ "Specifies the output representation of \"@\"-" ++
"symbols. The value "
, comment "has to be encapsulated into quotation marks."
, set "at_symbol" $ "\"" ++ atSymbol ++ "\""
, emptyline
, comment $ "Overwrites the semantics of the input " ++
"specification. Do not set"
, comment "to keep the value unchanged."
, ifJust owSemantics "overwrite_semantics" convert
, emptyline
, comment $ "Overwrites the target of the input " ++
"specification. Do not set"
, comment "to keep the value unchanged."
, ifJust owTarget "overwrite_target" convert
, emptyline
, comment $ "Either enable or disable weak simplifications on " ++
"the LTL"
, comment $ "formula level. Possible values are either \"true\" " ++
"or \"false\"."
, set "weak_simplify" $ convert $ CBool simplifyWeak
, emptyline
, comment $ "Either enable or disable strong simplifications on " ++
"the LTL"
, comment $ "formula level. Possible values are either \"true\" " ++
"or \"false\"."
, set "strong_simplify" $ convert $ CBool simplifyStrong
, emptyline
, comment $ "Either enable or disable that the resulting " ++
"formula is"
, comment "converted into negation normal form. Possible values " ++
"are"
, comment "either \"true\" or \"false\"."
, set "negation_normal_form" $ convert $ CBool negNormalForm
, emptyline
, comment $ "Either enable or disable to push globally operators " ++
"inwards,"
, comment "i.e., to apply the following equivalence:"
, comment ""
, comment " G (a && b) => (G a) && (G b)"
, comment ""
, comment "Possible values are either \"true\" or \"false\"."
, set "push_globally_inwards" $ convert $ CBool pushGlobally
, emptyline
, comment $ "Either enable or disable to push finally operators " ++
"inwards,"
, comment "i.e., to apply the following equivalence:"
, comment ""
, comment " F (a || b) => (F a) || (F b)"
, comment ""
, comment "Possible values are either \"true\" or \"false\"."
, set "push_finally_inwards" $ convert $ CBool pushFinally
, emptyline
, comment $ "Either enable or disable to next operators " ++
"inwards, i.e.,"
, comment "to apply the following equivalences:"
, comment ""
, comment " X (a && b) => (X a) && (X b)"
, comment " X (a || b) => (X a) || (X b)"
, comment ""
, comment "Possible values are either \"true\" or \"false\"."
, set "push_next_inwards" $ convert $ CBool pushNext
, emptyline
, comment $ "Either enable or disable to pull globally operators " ++
"outwards,"
, comment "i.e., to apply the following equivalence:"
, comment ""
, comment " (G a) && (G b) => G (a && b)"
, comment ""
, comment "Possible values are either \"true\" or \"false\"."
, set "pull_globally_outwards" $ convert $ CBool pullGlobally
, emptyline
, comment $ "Either enable or disable to pull finally operators " ++
"outwards,"
, comment "i.e., to apply the following equivalence:"
, comment ""
, comment " (F a) || (F b) => F (a || b)"
, comment ""
, comment "Possible values are either \"true\" or \"false\"."
, set "pull_finally_outwards" $ convert $ CBool pullFinally
, emptyline
, comment $ "Either enable or disable to pull next operators " ++
"outwards,"
, comment "i.e., to apply the following equivalences:"
, comment ""
, comment " (X a) && (X b) => X (a && b)"
, comment " (X a) || (X b) => X (a || b)"
, comment ""
, comment "Possible values are either \"true\" or \"false\"."
, set "pull_next_outwards" $ convert $ CBool pullNext
, emptyline
, comment $ "Either enable or disable to resolve weak until " ++
"operators."
, comment "Possible values are either \"true\" or \"false\"."
, set "no_weak_until" $ convert $ CBool noWeak
, emptyline
, comment $ "Either enable or disable to resolve release " ++
"operators."
, comment "Possible values are either \"true\" or \"false\"."
, set "no_release" $ convert $ CBool noRelease
, emptyline
, comment $ "Either enable or disable to resolve finally " ++
"operators."
, comment "Possible values are either \"true\" or \"false\"."
, set "no_finally" $ convert $ CBool noFinally
, emptyline
, comment $ "Either enable or disable to resolve globally " ++
"operators."
, comment "Possible values are either \"true\" or \"false\"."
, set "no_globally" $ convert $ CBool noGlobally
, emptyline
, comment $ "Either enable or disable to resolve derived " ++
"operators, i.e.,"
, comment "weak until, finally, globally, ... . Possible " ++
"values are"
, comment "either \"true\" or \"false\"."
, set "no_derived" $ convert $ CBool noDerived
, emptyline
]
where
emptyline = ""
comment = ("# " ++)
set s v = s ++ " = " ++ v
ifJust x s f = case x of
Nothing -> "#\n# " ++ set s "..."
Just y -> set s $ f y
-----------------------------------------------------------------------------
-- | Parses configuration parameters from the content of a
-- configuration file and updates the respective entries in the
-- provided configuration.
update
:: Configuration -> String -> Either Error Configuration
update c str =
case P.parse configParser "Configuration Error" str of
Left err -> parseError err
Right xs -> return $ foldl (\x f -> f x) c xs
-----------------------------------------------------------------------------
-- | Configuration file parser, that parses the file to a list of
-- configuration updates to preserve the order inside the
-- configuration file.
configParser
:: Parser [Configuration -> Configuration]
configParser = (~~) >> many entryParser
where
entryParser =
(mParser "format"
>>= (\v -> return (\c -> c { outputFormat = v })))
<|> (mParser "mode"
>>= (\v -> return (\c -> c { outputMode = v })))
<|> (mParser "quote"
>>= (\v -> return (\c -> c { quoteMode = v })))
<|> (sParser "bus_delimiter"
>>= (\v -> return (\c -> c { busDelimiter = v })))
<|> (sParser "prime_symbol"
>>= (\v -> return (\c -> c { primeSymbol = v })))
<|> (sParser "at_symbol"
>>= (\v -> return (\c -> c { atSymbol = v })))
<|> (mParser "overwrite_semantics"
>>= (\v -> return (\c -> c { owSemantics = Just v })))
<|> (mParser "overwrite_target"
>>= (\v -> return (\c -> c { owTarget = Just v })))
<|> (mParser "weak_simplify"
>>= (\(CBool v) -> return (\c -> c { simplifyWeak = v })))
<|> (mParser "strong_simplify"
>>= (\(CBool v) -> return (\c -> c { simplifyStrong = v })))
<|> (mParser "negation_normal_form"
>>= (\(CBool v) -> return (\c -> c { negNormalForm = v })))
<|> (mParser "push_globally_inwards"
>>= (\(CBool v) -> return (\c -> c { pushGlobally = v })))
<|> (mParser "push_finally_inwards"
>>= (\(CBool v) -> return (\c -> c { pushFinally = v })))
<|> (mParser "push_next_inwards"
>>= (\(CBool v) -> return (\c -> c { pushNext = v })))
<|> (mParser "pull_globally_outwards"
>>= (\(CBool v) -> return (\c -> c { pullGlobally = v })))
<|> (mParser "pull_finally_outwards"
>>= (\(CBool v) -> return (\c -> c { pullFinally = v })))
<|> (mParser "pull_next_outwards"
>>= (\(CBool v) -> return (\c -> c { pullNext = v })))
<|> (mParser "no_weak_until"
>>= (\(CBool v) -> return (\c -> c { noWeak = v })))
<|> (mParser "no_release"
>>= (\(CBool v) -> return (\c -> c { noRelease = v })))
<|> (mParser "no_finally"
>>= (\(CBool v) -> return (\c -> c { noFinally = v })))
<|> (mParser "no_globally"
>>= (\(CBool v) -> return (\c -> c { noGlobally = v })))
<|> (mParser "no_derived"
>>= (\(CBool v) -> return (\c -> c { noDerived = v })))
sParser str = do
keyword str
op "="
stringLiteral tokenparser
mParser str = do
keyword str
op "="
v <- identifier tokenparser
case safeConvert v of
Left _ -> parserZero <?> v
Right m -> return m
tokenparser = makeTokenParser configDef
keyword = void . reserved tokenparser
(~~) = whiteSpace tokenparser
op = reservedOp tokenparser
configDef = emptyDef
{ opStart = oneOf "="
, opLetter = oneOf "="
, identStart = alphaNum
, identLetter = alphaNum <|> char '_'
, commentLine = "#"
, nestedComments = False
, caseSensitive = True
, reservedOpNames = ["="]
, reservedNames =
[ "format", "mode", "quote", "bus_delimiter", "prime_symbol", "at_symbol",
"overwrite_semantics", "overwrite_target", "weak_simplify",
"strong_simplify", "negation_normal_form",
"push_globally_inwards", "push_finally_inwards",
"push_next_inwards", "pull_globally_outwards",
"pull_finally_outwards", "pull_next_outwards", "no_weak_until",
"no_release", "no_finally", "no_globally", "no_derived" ]
}
-----------------------------------------------------------------------------
newtype CBool = CBool Bool
-----------------------------------------------------------------------------
instance Convertible CBool String where
safeConvert = return . \case
(CBool True) -> "true"
(CBool False) -> "false"
-----------------------------------------------------------------------------
instance Convertible String CBool where
safeConvert = \case
"true" -> return $ CBool True
"false" -> return $ CBool False
str -> Left ConvertError
{ convSourceValue = str
, convSourceType = "String"
, convDestType = "Bool"
, convErrorMessage = "Unknown value"
}
-----------------------------------------------------------------------------
| reactive-systems/syfco | src/lib/Config.hs | mit | 31,317 | 0 | 36 | 8,498 | 4,680 | 2,668 | 2,012 | 554 | 2 |
module Main where
import Control.Monad.IO.Class
import Control.Monad.Bayes.Sampler
import Control.Monad.Bayes.Weighted
import Control.Monad.Bayes.Population
import Control.Monad.Bayes.Inference.SMC
import Control.Monad.Bayes.Inference.RMSMC
import Control.Monad.Bayes.Inference.PMMH as PMMH
import Control.Monad.Bayes.Inference.SMC2 as SMC2
import NonlinearSSM
main :: IO ()
main = sampleIO $ do
let t = 5
dat <- generateData t
let ys = map snd dat
liftIO $ print "SMC"
smcRes <- runPopulation $ smcMultinomial t 10 (param >>= model ys)
liftIO $ print $ show smcRes
liftIO $ print "RM-SMC"
smcrmRes <- runPopulation $ rmsmcLocal t 10 10 (param >>= model ys)
liftIO $ print $ show smcrmRes
liftIO $ print "PMMH"
pmmhRes <- prior $ pmmh 2 t 3 param (model ys)
liftIO $ print $ show pmmhRes
liftIO $ print "SMC2"
smc2Res <- runPopulation $ smc2 t 3 2 1 param (model ys)
liftIO $ print $ show smc2Res
| adscib/monad-bayes | benchmark/SSM.hs | mit | 935 | 0 | 13 | 172 | 335 | 171 | 164 | 27 | 1 |
str2action :: String -> IO ()
str2action input = putStrLn $ "Data: " ++ input
list2actions :: [String] -> [IO ()]
list2actions = map str2action
strings = show <$> [1..10]
actions :: [IO ()]
actions = list2actions strings
printall :: IO ()
printall = runall actions
where runall [] = return ()
runall (x:xs) = do
putStr "awating: "
x
runall xs
main = do
str2action "Start of the program"
printall
str2action "Done."
| sclereid/collections | haskell-learning/actions.hs | mit | 467 | 0 | 9 | 125 | 179 | 87 | 92 | 18 | 2 |
{-# LANGUAGE RankNTypes, RecursiveDo, RecordWildCards, GADTs, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}
module GMEWriter (writeTipToiFile) where
import qualified Data.ByteString.Lazy as B
import qualified Data.Binary.Builder as Br
import Text.Printf
import Control.Monad
import Control.Applicative (Applicative)
import qualified Data.Map as M
import Control.Monad.Writer.Lazy
import Control.Monad.State.Lazy
import Debug.Trace
import Types
import Constants
import Cypher
-- Assembling .gme files
-- Assembly monad
-- We need a data structure that we can extract its length from before we know its values
-- So we will use a lazy pair of length (Int) and builder
newtype SPutM a = SPutM (StateT Word32 (Writer Br.Builder) a)
deriving (Functor, Applicative, Monad, MonadFix)
type SPut = SPutM ()
putWord8 :: Word8 -> SPut
putWord8 w = SPutM (tell (Br.singleton w) >> modify (+1))
putWord16 :: Word16 -> SPut
putWord16 w = SPutM (tell (Br.putWord16le w) >> modify (+2))
putWord32 :: Word32 -> SPut
putWord32 w = SPutM (tell (Br.putWord32le w) >> modify (+4))
putBS :: B.ByteString -> SPut
putBS bs = SPutM (tell (Br.fromLazyByteString bs) >> modify (+ fromIntegral (B.length bs)))
putArray :: Integral n => (n -> SPut) -> [SPut] -> SPut
putArray h xs = do
h (fromIntegral (length xs))
sequence_ xs
data FunSplit m where
FunSplit :: forall m a . (a -> m ()) -> m a -> FunSplit m
mapFstMapSnd :: forall m. MonadFix m => [FunSplit m] -> m ()
mapFstMapSnd xs = go xs (return ())
where
go :: [FunSplit m] -> m b -> m b
go [] cont = cont
go (FunSplit f s:xs) cont = mdo
f v
(v,vs) <- go xs $ do
vs <- cont
v <- s
return (v,vs)
return vs
offsetsAndThen :: [SPut] -> SPut
offsetsAndThen = mapFstMapSnd . map go
where go x = FunSplit putWord32 (getAddress x)
putOffsets :: Integral n => (n -> SPut) -> [SPut] -> SPut
putOffsets h xs = mdo
h (fromIntegral (length xs))
offsetsAndThen xs
seek :: Word32 -> SPut
seek to = SPutM $ do
now <- get
when (now > to) $ do
fail $ printf "Cannot seek to 0x%08X, already at 0x%08X" to now
tell $ (Br.fromLazyByteString (B.replicate (fromIntegral (to-now)) 0))
modify (+ (to-now))
-- Puts something, returning the offset to the beginning of it.
getAddress :: SPut -> SPutM Word32
getAddress (SPutM what) = SPutM $ do
a <- get
what
return a
runSPut :: SPut -> B.ByteString
--runSPut (SPutM act) = Br.toLazyByteString $ evalState (execWriterT act) 0
runSPut (SPutM act) = Br.toLazyByteString $ execWriter (evalStateT act 0)
putTipToiFile :: TipToiFile -> SPut
putTipToiFile (TipToiFile {..}) = mdo
putWord32 sto
putWord32 mft
putWord32 0x238b
putWord32 ast -- Additional script table
putWord32 gto -- Game table offset
putWord32 ttProductId
putWord32 iro
putWord32 ttRawXor
putWord8 $ fromIntegral (B.length ttComment)
putBS ttComment
putBS ttDate
seek 0x0071 -- Just to be safe
putWord32 ipllo
seek 0x0200 -- Just to be safe
sto <- getAddress $ putScriptTable ttScripts
ast <- getAddress $ putWord16 0x00 -- For now, no additional script table
gto <- getAddress $ putGameTable ttGames
iro <- getAddress $ putInitialRegs ttInitialRegs
mft <- getAddress $ putAudioTable ttAudioXor ttAudioFiles
ipllo <- getAddress $ putPlayListList ttWelcome
return ()
putGameTable :: [Game] -> SPut
putGameTable games = putOffsets putWord32 $ map putGame games
putGame :: Game -> SPut
putGame (Game6 {..}) = mdo
putWord16 6
putWord16 (fromIntegral (length gSubgames) - gBonusSubgameCount)
putWord16 gRounds
putWord16 gBonusSubgameCount
putWord16 gBonusRounds
putWord16 gBonusTarget
putWord16 gUnknownI
putWord16 gEarlyRounds
putWord16 gUnknownQ
putWord16 gRepeatLastMedia
putWord16 gUnknownX
putWord16 gUnknownW
putWord16 gUnknownV
putWord32 spl
putWord32 repl
putWord32 fpl
putWord32 rspl
putWord32 lrspl
putWord32 rspl2
putWord32 lrspl2
mapM_ putWord32 sgo
mapM_ putWord16 gTargetScores
mapM_ putWord16 gBonusTargetScores
mapM_ putWord32 fpll
mapM_ putWord32 fpll2
putWord32 gilo
spl <- getAddress $ putPlayListList gStartPlayList
repl <- getAddress $ putPlayListList gRoundEndPlayList
fpl <- getAddress $ putPlayListList gFinishPlayList
rspl <- getAddress $ putPlayListList gRoundStartPlayList
lrspl <- getAddress $ putPlayListList gLaterRoundStartPlayList
rspl2 <- getAddress $ putPlayListList gRoundStartPlayList2
lrspl2 <- getAddress $ putPlayListList gLaterRoundStartPlayList2
fpll <- mapM (getAddress . putPlayListList) gFinishPlayLists
fpll2 <- mapM (getAddress . putPlayListList) gBonusFinishPlayLists
sgo <- mapM (getAddress . putSubGame) gSubgames
gilo <- getAddress $ putGameIdList gBonusSubgameIds
return ()
putGame (Game253) = mdo
putWord16 253
putGame g = mdo
putWord16 (gameType g)
putWord16 (fromIntegral $ length (gSubgames g))
putWord16 (gRounds g)
putWord16 (gUnknownC g)
putWord16 (gEarlyRounds g)
putWord16 (gRepeatLastMedia g)
putWord16 (gUnknownX g)
putWord16 (gUnknownW g)
putWord16 (gUnknownV g)
putWord32 spl
putWord32 repl
putWord32 fpl
putWord32 rspl
putWord32 lrspl
mapM_ putWord32 sgo
mapM_ putWord16 (gTargetScores g)
mapM_ putWord32 fpll
case g of
Game7 {..} -> mdo
putWord32 sggo
sggo <- getAddress $ do
putOffsets putWord16 $ map putGameIdList gSubgameGroups
return ()
Game8 {..} -> mdo
putWord32 gso
putWord32 gs
putWord32 gse1
putWord32 gse2
gso <- getAddress $ putOidList gGameSelectOIDs
gs <- getAddress $ putArray putWord16 $ map putWord16 gGameSelect
gse1 <- getAddress $ putPlayListList gGameSelectErrors1
gse2 <- getAddress $ putPlayListList gGameSelectErrors2
return ()
Game9 {..} -> mdo
mapM_ putWord32 epll
epll <- mapM (getAddress . putPlayListList) gExtraPlayLists
return ()
Game10 {..} -> mdo
mapM_ putWord32 epll
epll <- mapM (getAddress . putPlayListList) gExtraPlayLists
return ()
Game16 {..} -> mdo
putWord32 eoids
mapM_ putWord32 epll
eoids <- getAddress $ putOidList gExtraOIDs
epll <- mapM (getAddress . putPlayListList) gExtraPlayLists
return ()
_ -> return ()
spl <- getAddress $ putPlayListList $ gStartPlayList g
repl <- getAddress $ putPlayListList $ gRoundEndPlayList g
fpl <- getAddress $ putPlayListList $ gFinishPlayList g
rspl <- getAddress $ putPlayListList $ gRoundStartPlayList g
lrspl <- getAddress $ putPlayListList $ gLaterRoundStartPlayList g
fpll <- mapM (getAddress . putPlayListList) (gFinishPlayLists g)
sgo <- mapM (getAddress . putSubGame) (gSubgames g)
return ()
putPlayListList :: [PlayList] -> SPut
putPlayListList playlistlist = do
putOffsets putWord16 $ map putPlayList playlistlist
putGameIdList :: [GameId] -> SPut
putGameIdList = putArray putWord16 . map (putWord16 . (+1))
putOidList :: [GameId] -> SPut
putOidList = putArray putWord16 . map putWord16
putSubGame :: SubGame -> SPut
putSubGame (SubGame {..}) = mdo
putBS sgUnknown
putArray putWord16 $ map putWord16 sgOids1
putArray putWord16 $ map putWord16 sgOids2
putArray putWord16 $ map putWord16 sgOids3
mapM_ putWord32 pll
pll <- mapM (getAddress . putPlayListList) sgPlaylist
return ()
putScriptTable :: [(Word16, Maybe [Line ResReg])] -> SPut
putScriptTable [] = error "Cannot create file with an empty script table"
putScriptTable scripts = mdo
putWord32 (fromIntegral last)
putWord32 (fromIntegral first)
mapFstMapSnd (map go [first .. last])
return ()
where
go i = case M.lookup i m of
Just (Just l) -> FunSplit putWord32 (getAddress $ putLines l)
_ -> FunSplit (\_ -> putWord32 0xFFFFFFFF) (return ())
m = M.fromList scripts
first = fst (M.findMin m)
last = fst (M.findMax m)
putInitialRegs :: [Word16] -> SPut
putInitialRegs = putArray putWord16 . map putWord16
putLines :: [Line ResReg] -> SPut
putLines = putOffsets putWord16 . map putLine
putLine :: Line ResReg -> SPut
putLine (Line _ conds acts idx) = do
putArray putWord16 $ map putCond conds
putArray putWord16 $ map putCommand acts
putPlayList idx
putPlayList :: PlayList -> SPut
putPlayList = putArray putWord16 . map putWord16
putCond :: Conditional ResReg -> SPut
putCond (Cond v1 o v2) = do
putTVal v1
putCondOp o
putTVal v2
putTVal :: TVal ResReg -> SPut
putTVal (Reg n) = do
putWord8 0
putWord16 n
putTVal (Const n) = do
putWord8 1
putWord16 n
putCondOp :: CondOp -> SPut
putCondOp Eq = mapM_ putWord8 [0xF9, 0xFF]
putCondOp Gt = mapM_ putWord8 [0xFA, 0xFF]
putCondOp Lt = mapM_ putWord8 [0xFB, 0xFF]
putCondOp GEq = mapM_ putWord8 [0xFD, 0xFF]
putCondOp LEq = mapM_ putWord8 [0xFE, 0xFF]
putCondOp NEq = mapM_ putWord8 [0xFF, 0xFF]
putCondOp (Unknowncond b) = putBS b
putCommand :: Command ResReg -> SPut
putCommand (ArithOp o r v) = do
putWord16 r
mapM_ putWord8 $ arithOpCode o
putTVal v
putCommand (Neg r) = do
putWord16 r
mapM_ putWord8 [0xF8, 0xFF]
putTVal (Const 0)
putCommand (RandomVariant v) = do
putWord16 0
mapM_ putWord8 [0xE0, 0xFF]
putTVal v
putCommand (PlayAllVariant v) = do
putWord16 0
mapM_ putWord8 [0xE1, 0xFF]
putTVal v
putCommand (Play n) = do
putWord16 0
mapM_ putWord8 [0xE8, 0xFF]
putTVal (Const (fromIntegral n))
putCommand (Random a b) = do
putWord16 0
mapM_ putWord8 [0x00, 0xFC]
putTVal (Const (lowhigh a b))
putCommand (PlayAll a b) = do
putWord16 0
mapM_ putWord8 [0x00, 0xFB]
putTVal (Const (lowhigh a b))
putCommand (Game n) = do
putWord16 0
mapM_ putWord8 [0x00, 0xFD]
putTVal (Const n)
putCommand Cancel = do
putWord16 0
mapM_ putWord8 [0xFF, 0xFA]
putTVal (Const 0xFFFF)
putCommand (Jump v) = do
putWord16 0
mapM_ putWord8 [0xFF, 0xF8]
putTVal v
putCommand (Timer r v) = do
putWord16 r
mapM_ putWord8 [0x00, 0xFF]
putTVal v
putCommand (NamedJump s) = error "putCommand: Unresolved NamedJump"
putCommand (Unknown b r v) = do
putWord16 r
putBS b
putTVal v
putAudioTable :: Word8 -> [B.ByteString] -> SPut
putAudioTable x as = mapFstMapSnd
[ FunSplit (\o -> putWord32 o >> putWord32 (fromIntegral (B.length a)))
(getAddress (putBS (cypher x a)))
| a <- as ]
lowhigh :: Word8 -> Word8 -> Word16
lowhigh a b = fromIntegral a + fromIntegral b * 2^8
writeTipToiFile :: TipToiFile -> B.ByteString
writeTipToiFile tt = runSPut (putTipToiFile tt)
| colinba/tip-toi-reveng | src/GMEWriter.hs | mit | 10,993 | 0 | 17 | 2,673 | 3,828 | 1,786 | 2,042 | 306 | 6 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
module EDDA.Data.Import.EDDB.Systems where
import EDDA.Types
import EDDA.Data.Database (query, saveSystems)
import EDDA.Schema.Util (getStr, getInt, getDouble)
import EDDA.Data.Import.EDDB.Util
import Data.IORef
import qualified Data.Vector as V
import Control.Monad.Trans
import Control.Monad.Trans.Reader
import Control.Concurrent
import Control.Applicative ((<|>))
import System.IO.Temp (withSystemTempFile)
import System.IO.MMap (mmapFileByteString)
import qualified Data.Text as T
import qualified Data.ByteString as BC
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.Lazy.Char8 as LC
import Data.Aeson
import Data.Aeson.Types
import Data.Int (Int32(..))
import qualified Data.Bson as B
url = "https://eddb.io/archive/v6/systems_populated.json"
toDocument :: Value -> Maybe (Int32,Str,B.Document)
toDocument obj = do !edsmId <- fromIntegral <$> (getInt obj "edsm_id" <|> (Just 0 :: Maybe Int))
!name <- getStr obj "name"
!doc <- mapToDocument [mapIntNullable "id" "eddbId",
mapIntNullable "edsm_id" "edsmId",
mapConst "systemName" (B.val (toText name)),
mapStrNullable "security" "security",
mapObjectArray "states" "states" (
mapToDocument [mapIntNullable "id" "id",
mapStrNullable "name" "name"]
),
mapStrNullable "government" "government",
mapIntNullable "controlling_minor_faction_id" "factionId",
mapStrNullable "controlling_minor_faction" "faction",
mapStrNullable "allegiance" "allegiance",
mapDoubleNullable "population" "population",
mapStrNullable "power" "power",
mapStrNullable "power_state" "powerState",
mapBoolNullable "is_populated" "isPopulated",
mapStrNullable "primary_economy" "primaryEconomy",
mapBoolNullable "needs_permit" "needsPermit",
mapDouble "x" "x",
mapDouble "y" "y",
mapDouble "z" "z" ] obj
return (edsmId,name,doc)
toDocumentList :: V.Vector Value -> ConfigT (V.Vector (Maybe (Int32,Str,B.Document)))
toDocumentList = V.mapM (\v -> case toDocument v of
Just d -> return $ Just d
Nothing -> do liftIO $ C.putStrLn "Couldn't parse system: " >> print v
return Nothing)
saveToDatabase systems = do liftIO $ C.putStrLn "Importing into database..."
saveSystems systems
liftIO $ C.putStrLn ("Systems imported: " `C.append` C.pack (show (length systems)))
convertAndSaveToDB :: Config -> C.ByteString -> IO ()
convertAndSaveToDB c d = do total <- newIORef 0
runReaderT (query (do context <- ask
liftIO (streamParseIO 10000 d (saveToDB context total)))) c
totalCount <- readIORef total
C.putStrLn ("Total systems imported: " `C.append` C.pack (show totalCount))
where substr d s e = C.concat ["[",C.take (e-s-1) $ C.drop s d,"]"]
convert s = case (decodeStrict' s :: Maybe Value) of
Just (Array systems) -> Just . onlyJustVec <$> runReaderT (toDocumentList systems) c
Just _ -> return Nothing
Nothing -> return Nothing
saveToDB context total d s e =
do maybeSystems <- convert (substr d s e)
case maybeSystems of
Just systems -> do runReaderT (saveToDatabase (V.toList systems)) context
let !totalCount = length systems in modifyIORef' total (+ totalCount)
Nothing -> putStrLn "Couldn't decode a batch" >> C.putStrLn (substr d s e)
downloadAndImport :: ConfigT ()
downloadAndImport =
do
liftIO $ C.putStrLn "Downloading EDDB Systems data..."
r <- ask
liftIO $ withSystemTempFile "systems.json" (\f h -> download url "EDDB Systems data downloaded" f h >> mmapFileByteString f Nothing >>= convertAndSaveToDB r)
| troydm/edda | src/EDDA/Data/Import/EDDB/Systems.hs | mit | 5,133 | 0 | 19 | 2,122 | 1,136 | 584 | 552 | 79 | 4 |
{-|
Module : Utils.Executable
Description : Utilities for reading commandline arguments
Copyright : (c) Tessa Belder 2015-2016
This module contains useful functions for reading commandline arguments. It should be used in all executables of the madl toolset.
-}
module Utils.Executable(parseArgs) where
import Control.Monad (when)
import System.Console.GetOpt
import System.Environment
import System.Exit (exitSuccess)
-- | Extends an options object with a "help" option
data CommandLineOptions a = CommandLineOptions {
help :: Bool,
options :: a
}
-- | Default extended options: pairs the given default options with the default "help" flag
defaultOptions :: a -> CommandLineOptions a
defaultOptions opts = CommandLineOptions{
help = False,
options = opts
}
-- | Lift the optionsdescription of an options object to an extended optionsdescriptions including the "help (-h)" flag
exeOptions :: [OptDescr (a -> a)] -> [OptDescr (CommandLineOptions a -> CommandLineOptions a)]
exeOptions = (helpOption :) . map liftOption where
helpOption = Option "h" ["help"] (NoArg (\opts -> opts {help = True})) "Show this help.\n "
liftOption :: OptDescr (a -> a) -> OptDescr (CommandLineOptions a -> CommandLineOptions a)
liftOption (Option short long fun descr) = Option short long (lift fun) descr
lift :: ArgDescr (a -> a) -> ArgDescr (CommandLineOptions a -> CommandLineOptions a)
lift (NoArg fun) = NoArg (\opts -> opts{options = fun $ options opts})
lift (ReqArg fun descr) = ReqArg (\arg opts -> opts{options = fun arg $ options opts}) descr
lift (OptArg fun descr) = OptArg (\arg opts -> opts{options = fun arg $ options opts}) descr
-- | Given an optionsdescription and a set of default options, read user input from commandline and return the selected options
parseArgs :: [OptDescr (a -> a)] -> a -> IO a
parseArgs exeOpts defaultOpts = do
args <- getArgs
case getOpt RequireOrder (exeOptions exeOpts) args of
(opts, [], []) -> do
let cmdOptions = foldl (flip id) (defaultOptions defaultOpts) opts
when (help cmdOptions) $ showHelp (exeOptions exeOpts)
return $ options cmdOptions
(_, args', []) -> ioError . userError $ "Unsupported arguments: " ++ show args' ++ ".\nUse -h or --help for an overview of supported arguments."
(_, _, errs) -> ioError . userError $ concat errs ++ "Use -h or --help for an overview of supported options."
-------------------------
-- Help message
-------------------------
-- | Given an optionsdescription, shows a help message
showHelp :: [OptDescr (a -> a)] -> IO()
showHelp exeOpts = do
putStrLn $ usageInfo helpHeader exeOpts
exitSuccess
-- | Header of the help message triggered by the "help" flag
helpHeader :: String
helpHeader = unlines [
"\nCopyright @ TU/e"
, "**********************************************************************"
, "** **"
, "** MaDL Modelling and Verification Environment **"
, "** **"
, "**********************************************************************"
] | julienschmaltz/madl | src/Utils/Executable.hs | mit | 3,237 | 0 | 17 | 755 | 744 | 393 | 351 | 43 | 3 |
module Lesson02 where
-- Each of our lessons is going to end up reusing a lot of the
-- same code, like the definitions of Suit and Rank. Instead of
-- copy-pasting all of that, I've created a module called Helper
-- that contains that shared code. Then we just need to *import*
-- that module to make those data types, functions, and values
-- available here.
import Helper
-- In this lesson, we're going to want to shuffle our deck and
-- deal out a few hands for 5-card stud. To do so, let's import
-- a helper library that will let us shuffle:
import System.Random.Shuffle
-- If you want more information about that module, click on it and
-- then click the "Info of identifier" icon below (the "i" just above
-- the messages tab).
main = do
-- We defined deck in Helper, but it's always in the same order.
-- Let's get a randomly shuffled deck.
shuffled <- shuffleM deck
-- shuffled is now a list of Cards. If you want to see that,
-- double-click on the word shuffled, and in the Messages tab
-- you should see:
--
-- shuffled :: [Card]
--
-- The :: means "is of type", and the square brackets around "Card"
-- means "a list of." Altogether, that means "shuffled is of type
-- list of Card," which is just a stilted way of saying "shuffled is
-- a list of cards."
--
-- Now that we have a list of shuffled cards, we want to take the first
-- five cards and "deal" it to player one, then the next five cards and
-- deal to player two. To do that, we'll use splitAt:
let (player1, rest) = splitAt 5 shuffled
-- player1 is now a list with 5 cards, and rest is a list with the other 47.
-- One important thing to mention is that the original shuffled list *didn't
-- change.* Haskell has something called immutable data. Instead of destroying
-- the old list of cards, we've created two new lists of cards based on the
-- original.
--
-- Now let's get the second player's hand. We *could* use splitAt, but we don't
-- actually care about the rest of the deck in this case. Instead, we'll use the
-- simply take function:
let player2 = take 5 rest
-- Notice that we took the 5 cards from rest, not shuffled. Think about what
-- would happen if we took from shuffled instead. Then try changing the code
-- and see if your assumptions were correct.
-- Alright, time to print out the hands:
putStrLn "Player 1:"
print player1
putStrLn "Player 2:"
print player2
{-
Remember: make sure to switch your target module before trying to run this code.
Exercises:
1. Change player2 to be take 5 shuffled, and see what the result is.
2. Try and modify the example to have 3 players. (A generalized version of
this exercise will be our goal in lesson 3.)
3. Replace putStrLn with print and see how that changes the output.
Behind the scenes:
Let's answer some easy questions first. putStrLn means "put a string and a line." In
most programming languages, a String is a piece of text, or a list of characters.
In order to make the next bit of text appear on its own line, we need to output a
newline character at the end. putStrLn does that for you automatically. (Yes, there's
also a putStr function that doesn't do that.)
The print function does something else. It first "show"s your data. In other words, it
converts your data to a String form. If you look back in lesson 1, one of our
deriving clauses was for Show. That was Haskell's way of saying "just figure out how to
convert this to a string automatically, I don't care."
Now let's ask a few other questions:
* Why is the function called shuffleM, and not shuffle?
* Why do we sometimes use "let," and sometimes use that funny "<-" symbol?
* What's up with that word "do?"
In Haskell, we have a distinction between "pure" and "impure" functions. The latter
is often thought of as actions, or things which have some kind of side effect on the rest
of the world. I won't get into the theory of why this is a good distinction to make for
now.
So let's describe some things that would be consider side effects. One would be "we displayed
some data to the user." Perhaps surprisingly, another would be "we got some random data." The
reason this is impure is that, if we call that function a second time, it will give a different
result. Since shuffling needs to be random, each call needs to have a different result, and
therefore shuffling is in fact an impure action. Therefore, the function is called shuffleM:
the M at the end stands for "monad," which is our scary-Haskell-way of saying "has some context,
such as allowing side effects."
This also explains our other two questions. The "<-" symbol means "please run some impure function,
and get the result out of it." let, on the other hand, means "here's some pure function, get the
result." You might be wondering if we really need two different ways of doing this. The answer
is that this setup really is very useful, but it'll take a bit more time before I can demonstrate
why, so please just take my word on it for now.
The word "do" is also part of this whole setup. It says, "I'm about to start running a bunch of
things, one per line. Some of them will be actions, some will be actions that produce values that
I care about (and I'll use <- to capture those values), and sometimes I'll just use let to capture
pure results."
One of the most confusing things for beginning Haskellers is knowing when to use <-, when to use let,
and what to start do notation. Since this is a tutorial for the impatient, I'm not going to explain
those rules right now, just give you the general guidelines I've already mentioned, and teach by example.
Don't worry, by the time you finish this tutorial, the distinction should be second nature for you.
-} | snoyberg/haskell-impatient-poker-players | src/Lesson02.hs | mit | 5,815 | 0 | 10 | 1,224 | 129 | 82 | 47 | 11 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module MinionsApi.Config
( Config(..)
, Environment(..)
, makePool -- IO
, lookupSetting -- IO
, setLogger
, defaultConfig
) where
import System.Environment (lookupEnv)
import Network.Wai.Middleware.RequestLogger (logStdoutDev, logStdout)
import Network.Wai (Middleware)
import Control.Monad.Logger (runNoLoggingT, runStdoutLoggingT)
import Database.Persist.Sql (ConnectionPool)
import Database.Persist.Postgresql (ConnectionString, createPostgresqlPool, pgConnStr)
import Database.Persist.Sqlite (SqliteConf(..), createSqlitePool)
import Web.Heroku.Persist.Postgresql (postgresConf)
data Config = Config {
getPool :: ConnectionPool,
getEnv :: Environment
}
data Environment =
Development
| Test
| Docker
| Production
deriving (Eq, Show, Read)
defaultConfig :: Config
defaultConfig = Config {
getPool = undefined,
getEnv = Development
}
setLogger :: Environment -> Middleware
setLogger Test = id
setLogger Development = logStdoutDev
setLogger Docker = logStdoutDev
setLogger Production = logStdout
makePool :: Environment -> IO ConnectionPool
makePool Test = runNoLoggingT $ createSqlitePool (sqlDatabase $ sqliteConf Test) (envPool Test)
makePool Development = runStdoutLoggingT $ createSqlitePool (sqlDatabase $ sqliteConf Development) (envPool Development)
makePool Production = do
connStr <- lookupDatabaseUrl
runStdoutLoggingT $ createPostgresqlPool connStr (envPool Production)
makePool e = runStdoutLoggingT $ createPostgresqlPool (psqlConf e) (envPool e)
envPool :: Environment -> Int
envPool Test = 1
envPool Development = 1
envPool Docker = 1
envPool Production = 8
sqliteConf :: Environment -> SqliteConf
sqliteConf Test = SqliteConf "./tmp/db-test.sqlite" 1
sqliteConf Development = SqliteConf "./tmp/db-dev.sqlite" 1
sqliteConf _ = undefined
psqlConf :: Environment -> ConnectionString
psqlConf Docker = "host=db dbname=postgres user=postgres password=postgres port=5432"
psqlConf _ = undefined
lookupSetting :: Read a => String -> a -> IO a
lookupSetting env def = do
param <- lookupEnv env
return $ case param of Nothing -> def
Just a -> read a
lookupDatabaseUrl :: IO ConnectionString
lookupDatabaseUrl = pgConnStr <$> postgresConf 1 -- Need to remove the `1` ?
| dzotokan/minions-api | src/lib/MinionsApi/Config.hs | mit | 2,466 | 0 | 11 | 529 | 603 | 328 | 275 | 60 | 2 |
-----------------------------------------------------------------------------
--
-- Module : Language.TypeScript.Docs
-- Copyright : (c) DICOM Grid Inc. 2013
-- License : MIT
--
-- Maintainer : Phillip Freeman <paf31@cantab.net>
-- Stability : experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module Language.TypeScript.Docs (
convertDeclarationsToHtml,
module Language.TypeScript.Docs.Comments,
module Language.TypeScript.Docs.Html
) where
import Language.TypeScript.Docs.Comments
import Language.TypeScript.Docs.Html
import Language.TypeScript.Parser
import Text.Parsec
import Text.Blaze.Html.Renderer.String
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
convertDeclarationsToHtml :: String -> Either String String
convertDeclarationsToHtml dts = do
decls <- either (Left . show) Right $ parse declarationSourceFile "TypeScript Declaration File" dts
return . renderHtml . generateDocument $ appendComments dts decls
| paf31/typescript-docs | src/Language/TypeScript/Docs.hs | mit | 1,040 | 0 | 11 | 136 | 164 | 102 | 62 | 15 | 1 |
module Solution
( Observation(..)
, solution
) where
----------------------------------------
-- STDLIB
----------------------------------------
import Data.Ratio
import Data.Bits
import Data.List
import Data.Word
import Safe
import Debug.Trace
type ObsHash = Word8
data Observation
= Observation
{ obs_probability :: Double
-- ^ Probability that a random element would be selected for hashing.
, obs_serverA :: ObsHash -- ^ Hash received from server A
, obs_serverB :: ObsHash -- ^ Hash received from server B
}
deriving Show
-- | solution obss maxDocuments - returns the maximum likelihood estimate for the count of
-- elements within [0;maxDocuments] that are not on both servers.
solution :: [Observation] -> Int -> Int
solution observations maxDocuments = 42
| ekarayel/SetDifferenceEstimator | Solution.hs | mit | 804 | 0 | 8 | 150 | 114 | 73 | 41 | 18 | 1 |
data Something
= Something String String | haskellbr/meetups | 09-2016/programas-como-linguagens/haskell-web-repl/tmp.hs | mit | 42 | 0 | 6 | 7 | 12 | 6 | 6 | 2 | 0 |
-----------------------------------------------------------------------------
--
-- Module : Language.TypeScript.Parser
-- Copyright : (c) DICOM Grid Inc. 2013
-- License : MIT
--
-- Maintainer : Phillip Freeman <paf31@cantab.net>
-- Stability : experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module Language.TypeScript.Parser (
declarationSourceFile,
nextIdentifier
) where
import Language.TypeScript.Types
import Language.TypeScript.Lexer
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.String (parseFromFile)
import Control.Applicative
(Applicative(..), (<$>), (<*>), (<*), (*>))
commentPlaceholder = fmap toOffset getPosition where
toOffset pos = Left $ (sourceLine pos, sourceColumn pos)
nextIdentifier =
skipMany (choice (map (try . reserved) [ "export", "declare", "public", "private", "static" ]))
>> choice (map (try . reserved) [ "var", "function", "class", "interface", "enum", "module" ])
>> identifier
declarationSourceFile = whiteSpace >> many declarationElement <* eof
exported = reserved "export" >> return Exported
declarationElement = choice $ map try
[ InterfaceDeclaration <$> commentPlaceholder <*> optionMaybe exported <*> interface
, ExportDeclaration <$> (reserved "export" >> lexeme (char '=') *> identifier)
, ExternalImportDeclaration <$> optionMaybe exported <*> (reserved "import" *> identifier) <*> (lexeme (char '=') *> reserved "require" *> parens stringLiteral <* semi)
, ImportDeclaration <$> optionMaybe exported <*> (reserved "import" *> identifier) <*> (lexeme (char '=') *> entityName)
, AmbientDeclaration <$> commentPlaceholder <*> optionMaybe exported <*> (reserved "declare" *> ambientDeclaration)
]
ambientDeclaration = choice (map try
[ ambientVariableDeclaration
, ambientFunctionDeclaration
, ambientClassDeclaration
, ambientInterfaceDeclaration
, ambientEnumDeclaration
, ambientModuleDeclaration
, ambientExternalModuleDeclaration
])
ambientVariableDeclaration = AmbientVariableDeclaration <$> commentPlaceholder <*> (reserved "var" *> identifier) <*> (optionMaybe typeAnnotation <* semi)
ambientFunctionDeclaration = AmbientFunctionDeclaration <$> commentPlaceholder <*> (reserved "function" *> identifier) <*> (parameterListAndReturnType <* semi)
ambientClassDeclaration = AmbientClassDeclaration <$> commentPlaceholder <*> (reserved "class" *> identifier) <*> optionMaybe typeParameters <*> optionMaybe extendsClause <*> optionMaybe implementsClause <*> braces (sepEndBy ambientClassBodyElement semi)
ambientInterfaceDeclaration = AmbientInterfaceDeclaration <$> interface
ambientEnumDeclaration = AmbientEnumDeclaration <$> commentPlaceholder <*> (reserved "enum" *> identifier) <*> braces (sepEndBy enumMember comma)
where
enumMember = (,) <$> propertyName <*> optionMaybe (lexeme (char '=') >> integer)
ambientModuleDeclaration = AmbientModuleDeclaration <$> commentPlaceholder <*> (reserved "module" *> sepBy identifier dot) <*> braces (many ambientDeclaration)
ambientExternalModuleDeclaration = AmbientExternalModuleDeclaration <$> commentPlaceholder <*> (reserved "module" *> stringLiteral) <*> braces (many ambientExternalModuleElement)
ambientExternalModuleElement = choice (map try
[ AmbientModuleElement <$> ambientDeclaration
, exportAssignment
, externalImportDeclaration ])
exportAssignment = ExportAssignment <$> (reserved "export" *> lexeme (char '=') *> identifier <* semi)
externalImportDeclaration =
AmbientModuleExternalImportDeclaration <$> optionMaybe exported
<*> (reserved "import" *> identifier)
<*> (lexeme (char '=') *> reserved "require" *> stringLiteral)
ambientClassBodyElement = (,) <$> commentPlaceholder <*> (choice $ map try
[ ambientConstructorDeclaration
, ambientMemberDeclaration
, ambientIndexSignature ])
ambientConstructorDeclaration = AmbientConstructorDeclaration <$> (reserved "constructor" *> parameterList <* semi)
ambientMemberDeclaration = AmbientMemberDeclaration <$> optionMaybe publicOrPrivate <*> optionMaybe static <*> propertyName <*> choice [fmap Right parameterListAndReturnType, fmap Left (optionMaybe typeAnnotation)]
ambientIndexSignature = AmbientIndexSignature <$> indexSignature
interface = Interface <$> commentPlaceholder <*> (reserved "interface" *> identifier) <*> optionMaybe typeParameters <*> optionMaybe extendsClause <*> objectType
extendsClause = reserved "extends" >> classOrInterfaceTypeList
implementsClause = reserved "implements" >> classOrInterfaceTypeList
classOrInterfaceTypeList = commaSep typeRef
objectType = braces typeBody
typeBody = TypeBody <$> sepEndBy typeMember semi
where
typeMember = (,) <$> commentPlaceholder <*> (choice $ map try [ methodSignature, propertySignature, callSignature, constructSignature, typeIndexSignature ])
propertySignature = PropertySignature <$> propertyName <*> optionMaybe (lexeme (char '?' >> return Optional)) <*> optionMaybe typeAnnotation
propertyName = identifier <|> stringLiteral
typeAnnotation = colon >> _type
callSignature = CallSignature <$> parameterListAndReturnType
parameterListAndReturnType = ParameterListAndReturnType <$> optionMaybe typeParameters <*> parens parameterList <*> optionMaybe typeAnnotation
parameterList = commaSep parameter
parameter = choice
[ try $ RequiredOrOptionalParameter <$> optionMaybe publicOrPrivate <*> identifier <*> optionMaybe (lexeme (char '?' >> return Optional)) <*> optionMaybe typeAnnotation
, RestParameter <$> (lexeme (string "...") *> identifier) <*> optionMaybe typeAnnotation
]
static = reserved "static" >> return Static
publicOrPrivate = choice
[ reserved "public" >> return Public
, reserved "private" >> return Private ]
stringOrNumber = choice
[ reserved "string" >> return String
, reserved "number" >> return Number ]
constructSignature = ConstructSignature <$> (reserved "new" *> optionMaybe typeParameters) <*> parens parameterList <*> optionMaybe typeAnnotation
typeIndexSignature = TypeIndexSignature <$> indexSignature
indexSignature = squares (IndexSignature <$> identifier <*> (colon *> stringOrNumber)) <*> typeAnnotation
methodSignature = MethodSignature <$> propertyName <*> optionMaybe (lexeme (char '?' >> return Optional)) <*> parameterListAndReturnType
typeParameters = angles $ commaSep1 typeParameter
typeParameter = TypeParameter <$> identifier <*> optionMaybe (reserved "extends" >> _type)
fold :: Stream s m t => ParsecT s u m a -> ParsecT s u m b -> (a -> b -> a) -> ParsecT s u m a
fold first more combine = do
a <- first
bs <- many more
return $ foldl combine a bs
_type = lexeme $ choice [ arrayType, functionType, constructorType ]
where
arrayType = fold atomicType (squares whiteSpace) (flip $ const ArrayType)
atomicType = choice $ map try
[ Predefined <$> predefinedType
, TypeReference <$> typeRef
, ObjectType <$> objectType
]
functionType = FunctionType <$> optionMaybe typeParameters <*> parens parameterList <*> returnType
constructorType = ConstructorType <$> (reserved "new" *> optionMaybe typeParameters) <*> parens parameterList <*> returnType
returnType = lexeme (string "=>") *> _type
typeRef = TypeRef <$> typeName <*> optionMaybe typeArguments
predefinedType = choice
[ reserved "any" >> return AnyType
, reserved "number" >> return NumberType
, (reserved "boolean" <|> reserved "bool") >> return BooleanType
, reserved "string" >> return StringType
, reserved "void" >> return VoidType
]
entityName = fmap toEntityName (sepBy1 identifier dot)
where
toEntityName [t] = EntityName Nothing t
toEntityName ts = EntityName (Just $ ModuleName $ init ts) (last ts)
typeName = fmap toTypeName (sepBy1 identifier dot)
where
toTypeName [t] = TypeName Nothing t
toTypeName ts = TypeName (Just $ ModuleName $ init ts) (last ts)
typeArguments = angles $ commaSep1 _type
| paf31/language-typescript | src/Language/TypeScript/Parser.hs | mit | 8,024 | 0 | 15 | 1,212 | 2,095 | 1,075 | 1,020 | 113 | 2 |
-- Project Euler Problem 6 - Sum square difference
--
-- difference between the sum of squares and square of the sum of the first one hundred natural numbers
--
--
main = do
let n = 100
let sumsquare = sum [ x^2 | x <- [1..n]]
let squaresum = (sum [1..n])^2
print (squaresum - sumsquare)
| yunwilliamyu/programming-exercises | project_euler/p006_sumsquare.hs | cc0-1.0 | 293 | 0 | 14 | 62 | 89 | 46 | 43 | 5 | 1 |
--
-- Copyright (c) 2014 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 PatternGuards, ScopedTypeVariables, FlexibleContexts #-}
module Vm.Queries
(
getDomainID
, getDomainUuid
, getStubDomainID
, whenDomainID, whenDomainID_
, getFocusVm
, getVms
, getVmsBy
, getVmsByType
, getVmByDomid
, getVmShutdownOrder
, getGuestVms
, getRunningHDX
, getGraphicsFallbackVm
, getDefaultNetworkBackendVm
, getConfigCorruptionInfo
, getNic
, getVmNicDefs
, getVmNicDefs'
, getVmWiredNics
, getVmWirelessNics
, getVmNicMacActual
, getVmDiskEncryptionKeySet
, getVmDiskVirtualSizeMB
, getVmDiskPhysicalUtilizationBytes
, getNicIds
, getCdroms
, getDisks
, getDisk
, getDiskWithPath
, envIsoDir
, envIsoPath
, pickDiskVirtPath
, getVmPrivateSpaceUsedMiB
, getCryptoKeyLookupPaths
, getPciPtRules
, getPciPtDevices
, getVisibleVms
, whenVmRunning
, isRunning
, isLoginRequired
, isManagedVm
, whenManagedVm
, countRunningVm
, backendNode
, getVmBedOperation
, getVmConfig
, getVmIconBytes
, getSeamlessVms
-- property accessors
, getVmType, getVmGraphics, getMaxVgpus, getVmSmbiosOemTypesPt
, getVmWiredNetwork, getVmWirelessNetwork, getVmGpu, getVmCd, getVmMac, getVmAmtPt, getVmPorticaEnabled, getVmPorticaInstalled
, getVmSeamlessTraffic, getVmAutostartPending, getVmHibernated, getVmMemoryStaticMax
, getVmMemoryMin
, getVmMemoryTargetKib
, getVmMemoryTarget, getVmStartOnBoot, getVmHiddenInSwitcher, getVmHiddenInUi, getVmMemory, getVmName
, getVmImagePath, getVmSlot, getVmPvAddons, getVmPvAddonsVersion
, getVmTimeOffset, getVmCryptoUser, getVmCryptoKeyDirs, getVmAutoS3Wake
, getVmNotify, getVmHvm, getVmPae, getVmApic, getVmViridian, getVmNx, getVmSound, getVmDisplay
, getVmBoot, getVmCmdLine, getVmKernel, getVmInitrd, getVmAcpiPt, getVmVcpus, getVmCoresPerSocket
, getVmKernelPath
, getVmKernelExtract
, getVmInitrdExtract
, getVmVideoram, getVmPassthroughMmio, getVmPassthroughIo, getVmFlaskLabel
, getVmAcpiState, getVmHap, getVmSmbiosPt, getVmDescription, getVmMeasured
, getVmExtraXenvm, getVmExtraHvm
, getVmStartOnBootPriority, getVmKeepAlive, getVmProvidesNetworkBackend
, getVmShutdownPriority, getVmProvidesGraphicsFallback
, getVmSeamlessId, getVmStartFromSuspendImage
, getVmQemuDmPath, getVmQemuDmTimeout
, getVmDependencies
, getVmTrackDependencies
, getVmSeamlessMouseLeft, getVmSeamlessMouseRight
, getVmOs, getVmControlPlatformPowerState, getVmGreedyPcibackBind
, getVmFirewallRules, getVmOemAcpiFeatures, getVmUsbEnabled, getVmUsbAutoPassthrough, getVmUsbControl, getVmCpuid, getVmCpuidResponses
, getVmStubdom, getVmStubdomMemory, getVmStubdomCmdline
, getVmRunPostCreate, getVmRunPreDelete, getVmRunOnStateChange, getVmRunOnAcpiStateChange
, getVmRunPreBoot
, getVmRunInsteadofStart
, getVmUsbGrabDevices
, getVmNativeExperience, getVmShowSwitcher, getVmWirelessControl
, getVmXciCpuidSignature
, getVmS3Mode
, getVmS4Mode
, getVmVsnd
, getVmRealm
, getVmSyncUuid
, getVmIcbinnPath
, getVmOvfTransportIso
, getVmDownloadProgress
, getVmReady
, getVmProvidesDefaultNetworkBackend
, getVmVkbd
, getVmVfb
, getVmV4V
, getVmRestrictDisplayDepth
, getVmRestrictDisplayRes
, getVmPreserveOnReboot
, getVmBootSentinel
, getVmHpet
, getVmTimerMode
, getVmNestedHvm
, getVmSerial
) where
import Data.String
import Data.List
import Data.Maybe
import Data.Ord
import Data.Word
import qualified Data.Map as M
import qualified Data.ByteString as B
import Control.Arrow
import qualified Control.Exception as E
import Control.Monad
import Control.Monad.Error
import Control.Applicative
import Directory
import Text.Printf
import XenMgr.Db
import XenMgr.Errors
import Vm.Types
import Vm.DomainCore
import Vm.Dm
import Vm.Config
import Vm.Pci
import Vm.DepGraph
import Vm.Policies
import Vm.ProductProperty
import qualified Vm.V4VFirewall as Firewall
import Tools.Misc
import Tools.Process
import Tools.Text
import Tools.Log
import Tools.Future
import Tools.IfM
import System.FilePath
import System.Posix.Files (fileSize, getFileStatus)
import Tools.XenStore
import XenMgr.Rpc
import XenMgr.Connect.Xenvm (isRunning)
import XenMgr.Connect.NetworkDaemon
import XenMgr.Config
import XenMgr.Errors
import XenMgr.Host
import qualified XenMgr.Connect.Xenvm as Xenvm
import Rpc.Autogen.SurfmanClient
import Data.Bits
import System.IO.Unsafe
-- All VMS in database
allVms :: MonadRpc e m => m [Uuid]
allVms = map fromString <$> dbList "/vm"
-- VMS with corrupt configs
getConfigCorruptionInfo :: Rpc [(Uuid,String)]
getConfigCorruptionInfo = do
vms <- allVms
cfgs <- mapM (\uuid -> getVmConfig uuid False) vms
return $ foldl' f [] cfgs
where
f acc cfg =
case diagnose cfg of
[] -> acc
p:ps -> (vmcfgUuid cfg,p) : acc
-- VMS with correct configs
-- UPDATE: removed the correctness check, it was slowing the RPC extremely and does not protect
-- against anything interesting anyway
correctVms :: MonadRpc e m => m [Uuid]
correctVms = allVms
whenVmRunning :: (MonadRpc e m) => Uuid -> m () -> m ()
whenVmRunning uuid f = go =<< isRunning uuid
where go True = f
go _ = return ()
-- iterate over configured devices and plug proper backend domid
plugBackendDomains :: VmConfig -> Rpc VmConfig
plugBackendDomains cfg =
do plugged <- mapM plugNic (vmcfgNics cfg)
return $ cfg { vmcfgNics = plugged }
where
-- plug a nic to backend by resolving uuid if configured so, otherwise
-- use global network domain id (which is dom0 or ndvm)
plugNic :: NicDef -> Rpc NicDef
plugNic nic = backendFromUuid nic =<< getVmNicBackendUuid nic
where
backendFromUuid nic Nothing = return nic
backendFromUuid nic (Just uuid) = do
domid <- getDomainID uuid
return $ nic { nicdefBackendDomid = domid }
getMaxVgpus :: Rpc Int
getMaxVgpus = vgpu <$> querySurfmanVgpuMode
where vgpu Nothing = 0
vgpu (Just v) = vgpuMaxVGpus v
-- prepare the vm config
getVmConfig :: Uuid -> Bool -> Rpc VmConfig
getVmConfig uuid resolve_backend_uuids =
do disks <- future $ getVmStartupDisks uuid
let setupGeneratedMac uuid nic
| isNothing (nicdefMac nic) = nic { nicdefMac = Just (generatedVmNicMac uuid $ nicdefId nic) }
| otherwise = nic
nics <- future $ (map (setupGeneratedMac uuid) <$> getVmNicDefs' uuid)
nets <- future $ getAvailableVmNetworks =<< force nics
key_dirs <- future $ getCryptoKeyLookupPaths uuid
pcis <- future $ getPciPtDevices uuid
qemu <- future $ getVmQemuDmPath uuid
qemu_timeout <- future $ getVmQemuDmTimeout uuid
excl_cd <- future $ policyQueryCdExclusive
vgpu <- future $ ifM (getVmHvm uuid) querySurfmanVgpuMode (return Nothing)
gfx <- future $ getVmGraphics uuid
oem_acpi <- future $ getVmOemAcpiFeatures uuid
pv_addons <- future $ getVmPvAddons uuid
autostart <- future $ getVmStartOnBoot uuid
seamless <- future $ getVmSeamlessTraffic uuid
oem_types <- future $ getVmSmbiosOemTypesPt uuid
stubdom <- future $ getVmStubdom uuid
stubdom_memory <- future $ getVmStubdomMemory uuid
stubdom_cmdline <- future $ Just <$> getVmStubdomCmdline uuid
os <- future $ getVmOs uuid
cpuidresps <- future $ getVmCpuidResponses uuid
xcisig <- future $ getVmXciCpuidSignature uuid
usb <- future $ getVmUsbEnabled uuid
auto_passthrough <- future $ getVmUsbAutoPassthrough uuid
v <- future $ getHostXcVersion
name <- future $ domain_name
mem <- future $ getVmMemory uuid
memmin <- future $ getVmMemoryMin uuid
memmax <- future $ getVmMemoryStaticMax uuid
kernel <- future $ getVmKernelPath uuid
rdd <- future $ getVmRestrictDisplayDepth uuid
rds <- future $ getVmRestrictDisplayRes uuid
preserve_on_reboot <- future $ getVmPreserveOnReboot uuid
cfg <-
force $ VmConfig
<$> pure uuid
<*> name
<*> qemu
<*> qemu_timeout
<*> kernel
<*> cpuidresps
<*> xcisig
<*> os
<*> nics
<*> disks
<*> nets
<*> key_dirs
<*> pv_addons
<*> gfx
<*> rdd
<*> rds
<*> oem_acpi
<*> vgpu
<*> pcis
<*> excl_cd
<*> autostart
<*> seamless
<*> oem_types
<*> v
<*> usb
<*> auto_passthrough
<*> stubdom
<*> stubdom_memory
<*> stubdom_cmdline
<*> mem
<*> memmin
<*> memmax
<*> preserve_on_reboot
if resolve_backend_uuids
then plugBackendDomains cfg
else return cfg
where
domain_name = of_type =<< getVmType uuid where
of_type Svm = return Nothing
of_type _ = Just <$> getVmName uuid
pickDiskVirtPath :: MonadRpc e m => Uuid -> m String
pickDiskVirtPath uuid = nextFreeVirtPath . M.elems <$> getDisks uuid
-- choose a new available virtual path for disk
nextFreeVirtPath :: [Disk] -> String
nextFreeVirtPath disks = head . filter (not_taken disks) $ candidates
where
candidates = [ "hda", "hdb", "hdc", "hdd" ] ++ map (\s -> "xvd" ++ [s]) ['a'..'z']
not_taken disks virtp = not $ virtp `elem` (map diskDevice disks)
envIsoDir :: FilePath
envIsoDir = "/var/lib/ovf"
envIsoPath :: Uuid -> FilePath
envIsoPath uuid = envIsoDir ++ "/" ++ show uuid ++ "-env.iso"
-- disks used to boot this vm
-- add ovf environment disk here if necessary for the specified transport mode
getVmStartupDisks :: Uuid -> Rpc [Disk]
getVmStartupDisks uuid = do
enviso <- getVmOvfTransportIso uuid
disks <- readConfigPropertyDef uuid vmDisks []
let vpath = nextFreeVirtPath disks
return $ if enviso then envDisk vpath : disks else disks
where
envDisk vpath =
Disk { diskPath = envIsoPath uuid
, diskType = DiskImage
, diskMode = ReadOnly
, diskEnabled = True
, diskDevice = vpath
, diskDeviceType = DiskDeviceTypeCdRom
, diskSnapshotMode = Nothing
, diskSha1Sum = Nothing
, diskShared = False
, diskManagedType = UnmanagedDisk }
getVms :: (MonadRpc e m) => m [Uuid]
getVms = correctVms
getVmsBy :: (MonadRpc e m) => (Uuid -> m Bool) -> m [Uuid]
getVmsBy f = getVms >>= filterM f
getVmType :: (MonadRpc e m) => Uuid -> m VmType
getVmType uuid = readConfigPropertyDef uuid vmType Svm
getVmKernelPath :: (MonadRpc e m) => Uuid -> m (Maybe FilePath)
getVmKernelPath uuid = do
hvm <- getVmHvm uuid
if hvm then return Nothing else do
p <- getVmKernel uuid
if p /= "" then return (Just p) else return (Just $ "/tmp/kernel-"++show uuid)
getVmNicBackendUuid :: NicDef -> Rpc (Maybe Uuid)
getVmNicBackendUuid nic =
case (nicdefBackendUuid nic, nicdefBackendName nic) of
(Nothing , Nothing) -> defaultNetUuid
(Just uuid, _ ) -> return $ Just uuid
(Nothing , Just name) ->
do vms <- getVmsBy (\vm -> (== name) <$> getVmName vm)
case vms of
(uuid:_) -> return $ Just uuid
_ -> return Nothing
where
-- default network backend uuid (if not overriden by nic config) comes from network daemon query
defaultNetUuid = from =<< getNetworkBackend' (nicdefNetwork nic) where
from (Just vm) = return (Just vm)
from Nothing = getDefaultNetworkBackendVm
getAvailableVmNetworks :: [NicDef] -> Rpc [NetworkInfo]
getAvailableVmNetworks [] = return []
getAvailableVmNetworks nics
= do all_networks <- listNetworks
let nic_networks = map nicdefNetwork (filter nicdefEnable nics)
catMaybes <$> (mapM statNetwork $ intersect all_networks nic_networks)
getVmSmbiosOemTypesPt :: Uuid -> Rpc [Int]
getVmSmbiosOemTypesPt uuid = getVmSmbiosPt uuid >>= go where
go True = dbMaybeRead "/xenmgr/smbios-oem-types-pt" >>= from_user_setting
go _ = return []
from_user_setting (Just str) = return $ catMaybes [ maybeRead t | t <- split ',' str ]
from_user_setting Nothing = from_manufacturer <$> liftIO getHostSystemManufacturer'
from_manufacturer DELL = [ 129, 130, 131, 177 ]
from_manufacturer _ = [ 129, 130, 131 ]
getDependencyGraph :: Rpc (DepGraph Uuid)
getDependencyGraph =
do vms <- getVms
edges <- concat <$> mapM edge vms
return $ depgraphFromEdges edges
where
edge uuid =
do nics <- getVmNicDefs' uuid
net_backends <- nub . catMaybes <$> mapM getVmNicBackendUuid nics
return $ map (\dep -> (uuid,dep)) net_backends
getVmDependencies :: Uuid -> Rpc [Uuid]
getVmDependencies uuid =
do graph <- getDependencyGraph
case dependencies uuid graph of
Nothing -> error "errors in dependency graph; check for cycles"
Just xs -> return xs
getVmTrackDependencies :: Uuid -> Rpc Bool
getVmTrackDependencies uuid = readConfigPropertyDef uuid vmTrackDependencies False
getVmSeamlessMouseX :: Uuid -> (String -> Rpc [HostGpu]) -> Rpc (Maybe Uuid)
getVmSeamlessMouseX uuid gpusNextTo =
do gpu <- gpu_id <$> getVmGpu uuid
adjacent_gpus <- map gpuId <$> ( gpusNextTo gpu `catchError` (\ex -> return []))
return . first
=<< filterM isRunning
=<< return . concat
=<< mapM with_gpu adjacent_gpus
where
gpu_id "" = "hdx"
gpu_id x = x
first [] = Nothing
first (uuid:_) = Just $ uuid
with_gpu "hdx" = getVisibleVms
with_gpu gpu = getVmsBy (\vm -> (== gpu) <$> getVmGpu vm)
getVmSeamlessMouseLeft :: Uuid -> Rpc Int
getVmSeamlessMouseLeft uuid = from =<< getVmSeamlessMouseX uuid getGpusLeftOf where
from Nothing = return (-1)
from (Just vm) | vm == uuid = return (-1)
from (Just vm) = getVmSlot vm
getVmSeamlessMouseRight :: Uuid -> Rpc Int
getVmSeamlessMouseRight uuid = from =<< getVmSeamlessMouseX uuid getGpusRightOf where
from Nothing = return (-1)
from (Just vm) | vm == uuid = return (-1)
from (Just vm) = getVmSlot vm
getVmOs :: Uuid -> Rpc SupportedOS
getVmOs uuid = readConfigPropertyDef uuid vmOs "" >>= return . fromMaybe UnknownOS . osFromStr
getVmOemAcpiFeatures :: Uuid -> Rpc Bool
getVmOemAcpiFeatures uuid = readConfigPropertyDef uuid vmOemAcpiFeatures False
getVmUsbEnabled :: Uuid -> Rpc Bool
getVmUsbEnabled uuid = readConfigPropertyDef uuid vmUsbEnabled True
getVmUsbAutoPassthrough :: Uuid -> Rpc Bool
getVmUsbAutoPassthrough uuid = readConfigPropertyDef uuid vmUsbAutoPassthrough True
getVmUsbControl :: Uuid -> Rpc Bool
getVmUsbControl uuid = readConfigPropertyDef uuid vmUsbControl False
getVmStubdom :: Uuid -> Rpc Bool
getVmStubdom uuid = readConfigPropertyDef uuid vmStubdom False
getVmStubdomMemory :: Uuid -> Rpc Int
getVmStubdomMemory uuid = readConfigPropertyDef uuid vmStubdomMemory 128
getVmStubdomCmdline :: Uuid -> Rpc String
getVmStubdomCmdline uuid = readConfigPropertyDef uuid vmStubdomCmdline ""
getVmCpuid :: Uuid -> Rpc String
getVmCpuid uuid = readConfigPropertyDef uuid vmCpuid ""
getVmCpuidResponses :: Uuid -> Rpc [CpuidResponse]
getVmCpuidResponses uuid = map CpuidResponse . filter (not . null) . map strip . split ';' <$> getVmCpuid uuid
getVmXciCpuidSignature :: Uuid -> Rpc Bool
getVmXciCpuidSignature uuid = readConfigPropertyDef uuid vmXciCpuidSignature False
getVmsByType :: VmType -> Rpc [Uuid]
getVmsByType t =
getVmsBy equalTypes
where
equalTypes uuid = getVmType uuid >>= return . (== t)
getVmByDomid :: DomainID -> Rpc (Maybe Uuid)
getVmByDomid domid =
do vms <- getVms
domids <- mapM getDomainID vms
case filter matches (zip vms domids) of
((uuid,_) : _) -> return $ Just uuid
_ -> return Nothing
where
matches (uuid,Just domid') = domid == domid'
matches _ = False
groupVmsBy :: (Eq a) => (Uuid -> Rpc a) -> [Uuid] -> Rpc [[Uuid]]
groupVmsBy get_property uuids =
do props <- mapM get_property uuids
let vs = zip uuids props
rs = groupBy (\a b -> snd a == snd b) vs
return . map (map fst) $ rs
-- get the vm uuid which is supposed to have focus
getFocusVm :: Rpc (Maybe Uuid)
getFocusVm =
do maybe_uuid <- liftIO $ xsRead "/local/domain/0/switcher/focus-uuid"
return . fmap fromString $ maybe_uuid
-- get the visible domains (surfman query)
-- NOTE: this doesn't include vms which surfman does not know about, i.e. something which
-- uses passthrough GPU directly
getVisibleDomids :: Rpc [DomainID]
getVisibleDomids
= map fromIntegral <$>
comCitrixXenclientSurfmanGetVisible "com.citrix.xenclient.surfman" "/" `catchError` \_ -> return []
getVisibleVms :: Rpc [Uuid]
getVisibleVms = catMaybes <$> (mapM getDomainUuid =<< getVisibleDomids)
-- shutdown by descending priority, in parallel if priority equal
getVmShutdownOrder :: Rpc [[Uuid]]
getVmShutdownOrder =
do vms <- getVms
pris <- mapM getVmShutdownPriority vms
let order = reverse . sortBy (comparing snd) $ zip vms pris
order' = groupBy (\a b -> snd a == snd b) order
return . map (map fst) $ order'
getGuestVms :: Rpc [Uuid]
getGuestVms =
getVmsBy is_guest
where
match_guest_type Svm = True
match_guest_type _ = False
is_guest uuid = match_guest_type <$> getVmType uuid
getRunningHDX :: Rpc [Uuid]
getRunningHDX = do
filterM isRunning =<< getVmsBy isHDX
where
isHDX uuid = getVmGraphics uuid >>= return . (== HDX)
getGraphicsFallbackVm :: Rpc (Maybe Uuid)
getGraphicsFallbackVm = do
vms <- getVmsBy getVmProvidesGraphicsFallback
case vms of
(vm : _) -> return $ Just vm
_ -> return Nothing
getDefaultNetworkBackendVm :: Rpc (Maybe Uuid)
getDefaultNetworkBackendVm = do
vms <- getVmsBy getVmProvidesDefaultNetworkBackend
case vms of
(vm : _) -> return $ Just vm
_ -> return Nothing
-- Query for ACPI state, will return 0,3,4, or 5
getVmAcpiState :: Uuid -> Rpc Int
getVmAcpiState uuid = do
-- xenvm acpiState query is bit flaky as it can only be counted to return meaningful
-- value of 3 or 0 (as it just returns the hypercall query value directly). Rest has to be
-- derived from magic ball
-- xen 4.1: hypercall to get acpi state doesn't work on pv domains nor shutdown vms anymore
pv <- not <$> getVmHvm uuid
running <- isRunning uuid
ll_acpi_state <- if pv
then return 0
else (
if not running
then return 5
else Xenvm.acpiState uuid
)
deriveFrom <$> Xenvm.state uuid
<*> return ll_acpi_state
<*> readConfigPropertyDef uuid vmHibernated False
where
deriveFrom :: VmState -> Int -> Bool -> Int
deriveFrom Shutdown _ False = 5
deriveFrom Shutdown _ True = 4
deriveFrom _ 3 _ = 3
deriveFrom _ 0 _ = 0
deriveFrom _ _ _ = 0
-- Get nics from database
getVmNicDefs :: MonadRpc e m => Uuid -> m NicDefMap
getVmNicDefs uuid = readConfigPropertyDef uuid vmNics M.empty
getVmNicDefs' :: MonadRpc e m => Uuid -> m [NicDef]
getVmNicDefs' uuid = sortBy (comparing nicdefId) . M.elems <$> getVmNicDefs uuid
-- Get just nic ids from database
getNicIds :: MonadRpc e m => Uuid -> m [NicID]
getNicIds uuid = map nicdefId <$> getVmNicDefs' uuid
getVmWiredNics, getVmWirelessNics :: MonadRpc e m => Uuid -> m [NicDef]
getVmWiredNics vm = filter (not . nicdefWirelessDriver) <$> getVmNicDefs' vm
getVmWirelessNics vm = filter ( nicdefWirelessDriver) <$> getVmNicDefs' vm
getNic :: MonadRpc e m => Uuid -> NicID -> m (Maybe NicDef)
getNic uuid id = readConfigProperty uuid (vmNic id)
getCryptoKeyLookupPaths :: Uuid -> Rpc [FilePath]
getCryptoKeyLookupPaths uuid =
do user <- getVmCryptoUser uuid
vm_dirs <- split ',' <$> getVmCryptoKeyDirs uuid
platform_dirs <- split ',' <$> appGetPlatformCryptoKeyDirs
let dirs = filter (not . null) $ [user_key_dir user] ++ vm_dirs ++ platform_dirs
liftIO $ filterM doesDirectoryExist dirs
where
user_key_dir "" = ""
user_key_dir user = "/config/sec/s-" ++ user
getDisks :: MonadRpc e m => Uuid -> m DiskMap
getDisks uuid =
readConfigPropertyDef uuid vmDisks M.empty
getDisk :: MonadRpc e m => Uuid -> DiskID -> m (Maybe Disk)
getDisk uuid diskID = readConfigProperty uuid (vmDisk diskID)
getDisk' :: MonadRpc XmError m => Uuid -> DiskID -> m Disk
getDisk' uuid diskID = getDisk uuid diskID >>= \disk -> case disk of
Just d -> return d
Nothing-> failNoSuchDisk
getDiskWithPath :: MonadRpc e m => Uuid -> FilePath -> m (Maybe Disk)
getDiskWithPath uuid p = sh . filter ((== p) . diskPath) . M.elems <$> getDisks uuid where
sh (x:_) = Just x
sh _ = Nothing
orElseIfException :: IO a -> IO a -> IO a
orElseIfException f g =
f `E.catch` ( \(_ :: E.SomeException) -> g )
getVmDiskEncryptionKeySet :: MonadRpc XmError m => Uuid -> DiskID -> m Bool
getVmDiskEncryptionKeySet uuid disk_id =
do disk <- getDisk' uuid disk_id
if (diskType disk == VirtualHardDisk)
then from <$> liftIO (readKey disk)
else return False
where
from Nothing = False
from (Just "none") = False
from _ = True
readKey disk = (Just . chomp <$> readProcessOrDie "vhd-util" ["key", "-p", "-n", diskPath disk] "")
`orElseIfException` return Nothing
getVmDiskVirtualSizeMB :: MonadRpc XmError m => Uuid -> DiskID -> m Integer
getVmDiskVirtualSizeMB uuid disk_id =
do disk <- getDisk' uuid disk_id
liftIO $
if (diskType disk == VirtualHardDisk)
then (read . chomp <$> readProcessOrDie "vhd-util" ["query", "-v", "-n", diskPath disk] "")
`orElseIfException` return 0
else return 0
getVmDiskPhysicalUtilizationBytes :: MonadRpc XmError m => Uuid -> DiskID -> m Integer
getVmDiskPhysicalUtilizationBytes uuid disk_id =
do disk <- getDisk' uuid disk_id
liftIO $
if (diskType disk == VirtualHardDisk)
then (read . chomp <$> (readProcessOrDie "vhd-util" ["query", "-s", "-n", diskPath disk] ""))
`orElseIfException` return 0
else return 0
getVmPrivateSpaceUsedMiB :: Uuid -> Rpc Int
getVmPrivateSpaceUsedMiB uuid =
(M.elems <$> getDisks uuid) >>= mapM diskUsed >>= return . sum where
diskUsed d =
case diskType d of
DiskImage -> fileSz (diskPath d)
QemuCopyOnWrite -> fileSz (diskPath d)
VirtualHardDisk -> fileSz (diskPath d)
ExternalVdi -> fileSz (diskPath d)
Aio -> fileSz (diskPath d)
PhysicalDevice -> return 0 -- TODO
fileSz f = either (const 0) id <$> liftIO (E.try $ fileSz' f :: IO (Either E.SomeException Int))
fileSz' f = fromIntegral . mib . fileSize <$> getFileStatus f
mib = (`div` (1024*1024))
-- Get cdrom definitions from database
getCdroms :: Uuid -> Rpc [Disk]
getCdroms uuid =
getDisks uuid >>= pure . filter isCdrom . M.elems
-- Get passthrough rules for a VM
getPciPtRules :: Uuid -> Rpc PciPtRuleMap
getPciPtRules uuid =
readConfigPropertyDef uuid vmPcis M.empty
getPciPtRulesList :: Uuid -> Rpc [PciPtRule]
getPciPtRulesList uuid =
map snd . M.toList <$> getPciPtRules uuid
-- Get passthrough devices for a VM
getPciPtDevices :: Uuid -> Rpc [PciPtDev]
getPciPtDevices uuid =
do gfx <- getVmGraphics uuid
amt <- amtPtActive uuid
-- We've got PCI rules for a specifc VM
vm_rules <- getPciPtRulesList uuid
-- We've got PCI rules for HDX
hdx_devs <- case gfx of
HDX -> querySurfmanVgpuMode >>= return . vgpu_devs
_ -> return []
-- And then there are AMT passthrough rules
let amt_rules = case amt of True -> amtPciPtRules
_ -> []
-- And optional secondary gpu devs based on GPU property
-- ('hdx' indicates surfman devices and should be ignored here)
gpu_addr_str <- readConfigPropertyDef uuid vmGpu ""
let gpu_addr = case gpu_addr_str of "hdx" -> Nothing
_ -> pciFromStr gpu_addr_str
gpu_dev <- liftIO $ case gpu_addr of
Nothing -> return []
Just addr -> do dev <- pciGetDevice addr
return [PciPtDev dev PciSlotDontCare False SourceConfig]
let rules = amt_rules ++ vm_rules
devs_from_rules <- liftIO $ pciGetMatchingDevices SourceConfig rules
return $ hdx_devs ++ gpu_dev ++ devs_from_rules
where
vgpu_devs Nothing = []
vgpu_devs (Just mode) = vgpuPciPtDevices mode
getVmFirewallRules :: Uuid -> Rpc [Firewall.Rule]
getVmFirewallRules uuid = readConfigPropertyDef uuid vmFirewallRules []
isLoginRequired :: Uuid -> Rpc Bool
isLoginRequired uuid = do
user <- readConfigProperty uuid vmCryptoUser
case user of
Nothing -> return False
Just uid -> liftIO $ notMounted uid
where
notMounted uid = return . isNothing =<< spawnShell' ("grep -q \"/config/sec/s-" ++ uid ++ "\" /proc/mounts")
isManagedVm :: MonadRpc e m => Uuid -> m Bool
isManagedVm uuid =
dbExists $ "/vm/" ++ show uuid ++ "/backend"
whenManagedVm :: (MonadRpc e m) => Uuid -> m () -> m ()
whenManagedVm uuid f = whenM ( isManagedVm uuid ) f
-- count how many vms of given type are running
countRunningVm :: VmType -> Rpc Int
countRunningVm typ = length <$> (filterM running =<< getVmsByType typ)
where
running uuid = Xenvm.isRunning uuid
getVmIconBytes :: Uuid -> Rpc B.ByteString
getVmIconBytes uuid =
do icon_p <- getVmImagePath uuid
let path = html_root </> icon_p
liftIO $ B.readFile path
where
html_root = "/usr/lib/xui"
backendNode = "/local/domain/0/backend-domid"
-- wired network property returns bridge of first wired nic
getVmWiredNetwork :: Uuid -> Rpc (Maybe Network)
getVmWiredNetwork uuid
= getVmWiredNics uuid >>= return . first
where
first [] = Nothing
first (n:_) = Just $ nicdefNetwork n
-- wireless network property returns bridge of first wireless nic
getVmWirelessNetwork :: Uuid -> Rpc (Maybe Network)
getVmWirelessNetwork uuid
= getVmWirelessNics uuid >>= return . first
where
first [] = Nothing
first (n:_) = Just $ nicdefNetwork n
getVmGpu :: MonadRpc e m => Uuid -> m String
getVmGpu uuid
= ifM (getVmNativeExperience uuid)
hdxIfTools {- else -} current
where
current = readConfigPropertyDef uuid vmGpu ""
hdxIfTools
= ifM (getVmPvAddons uuid)
(return "hdx") {- else -} current
getVmGraphics :: MonadRpc e m => Uuid -> m VmGraphics
getVmGraphics uuid =
do gpu <- getVmGpu uuid
return $ case gpu of
"hdx" -> HDX
_ -> VGAEmu
-- cd inserted in virtual drive
getVmCd :: Uuid -> Rpc String
getVmCd uuid =
getCdroms uuid >>= pure . fromFirst
where
fromFirst [] = ""
fromFirst (c:_) = fromIsoName (takeFileName $ diskPath c)
fromIsoName "null.iso" = ""
fromIsoName other = other
-- mac of first nic is considered to be 'VM mac'
getVmMac :: Uuid -> Rpc String
getVmMac uuid =
getVmNicDefs' uuid >>= firstmac where
firstmac [] = return ""
firstmac (n:_) = getVmNicMacActual uuid (nicdefId n)
-- mac as it will be setup on vm, which is either user specified or auto-generated
getVmNicMacActual :: Uuid -> NicID -> Rpc String
getVmNicMacActual uuid nicid
= from_nic =<< getNic uuid nicid
where
from_nic Nothing = failNoSuchNic
from_nic (Just nic) = return $ fromMaybe (generatedVmNicMac uuid nicid) $ nicdefMac nic
-- mac generation algo
generatedVmNicMac :: Uuid -> NicID -> String
generatedVmNicMac uuid nicid
= intercalate ":" . map (printf "%02x") . unicast_local $ hexs
where
hexs = map f [0,2,1,7,6,4] where
f i = ((hdigest !! i ) `shiftL` 4)
.|. (hdigest !! (i+12))
unicast_local [] = []
unicast_local (x:xs) = (0x2 .|. (x .&. 0xFE)) : xs
halfbytes [] = []
halfbytes (x:xs) = (x .&. 0xF0) `shiftR` 4 : (x .&. 0x0F) : halfbytes xs
hdigest = halfbytes (md5 base)
base = show nicid ++ " " ++ show uuid
-- yeah yeah we should do it using haskell lib, i know..
md5 :: String -> [Word8]
md5 x
= parse . head . words . unsafePerformIO $ readProcessOrDie "md5sum" [] x
where
parse (a:b:xs) = byte a b : parse xs
parse _ = []
byte a b = read ('0' : 'x' : a : b : [])
getVmAmtPt :: Uuid -> Rpc Bool
getVmAmtPt uuid = readConfigPropertyDef uuid vmAmtPt False
-- '0' if not installed, '1' if installed and enabled, '2' if installed but disabled
getVmPorticaEnabled :: Uuid -> Rpc Int
getVmPorticaEnabled uuid = fromStatus <$> status <*> traffic where
def = PorticaStatus False False
status = readConfigPropertyDef uuid vmPorticaStatus def
traffic = getVmSeamlessTraffic uuid
-- ui expects kinky stuff here
fromStatus s False | not (porticaInstalled s) = 0
| otherwise = 2
fromStatus s True | not (porticaInstalled s) = 0
| not (Vm.Types.porticaEnabled s) = 2
| otherwise = 1
getVmPorticaInstalled :: Uuid -> Rpc Bool
getVmPorticaInstalled uuid =
readConfigPropertyDef uuid vmPorticaStatus (PorticaStatus False False) >>= return . porticaInstalled
getSeamlessVms :: Rpc [Uuid]
getSeamlessVms = filterM getVmSeamlessTraffic =<< getVms
getVmSeamlessTraffic :: Uuid -> Rpc Bool
getVmSeamlessTraffic uuid = of_type =<< getVmType uuid where
of_type Svm = readConfigProperty uuid vmSeamlessTraffic >>= of_config
of_type _ = return False
of_config (Just v) = return v
of_config Nothing = appSeamlessTrafficDefault
getVmAutostartPending :: Uuid -> Rpc Bool
getVmAutostartPending uuid = do
uuids <- dbReadWithDefault [] "/xenmgr/autostart-pending-vms" :: Rpc [Uuid]
return $ uuid `elem` uuids
getVmHibernated :: Uuid -> Rpc Bool
getVmHibernated uuid = readConfigPropertyDef uuid vmHibernated False
-- returns in MiBs
getVmMemoryStaticMax :: Uuid -> Rpc Int
getVmMemoryStaticMax uuid =
do v <- readConfigPropertyDef uuid vmMemoryStaticMax 0
if v <= 0
then getVmMemory uuid
else return v
-- in MiBs
getVmMemoryMin :: Uuid -> Rpc Int
getVmMemoryMin uuid =
do v <- readConfigPropertyDef uuid vmMemoryMin 0
if v <= 0
then getVmMemory uuid
else return v
-- returns in MiBs
getVmMemoryTarget :: Uuid -> Rpc Int
getVmMemoryTarget uuid = fromIntegral . kibToMib <$> getVmMemoryTargetKib uuid
getVmMemoryTargetKib :: Uuid -> Rpc Integer
getVmMemoryTargetKib uuid = whenDomainID 0 uuid kibS where
kibS :: DomainID -> Rpc Integer
kibS domid = do v <- liftIO $ xsRead ("/local/domain/" ++ show domid ++ "/memory/target")
return $ maybe 0 read v
getVmStartOnBoot :: Uuid -> Rpc Bool
getVmStartOnBoot uuid = nativeOverride uuid True $ readConfigPropertyDef uuid vmStartOnBoot False
getVmHiddenInSwitcher :: Uuid -> Rpc Bool
getVmHiddenInSwitcher uuid = readConfigPropertyDef uuid vmHidden False
getVmHiddenInUi :: Uuid -> Rpc Bool
getVmHiddenInUi uuid = readConfigPropertyDef uuid vmHiddenInUi False
-- returns in MBs
getVmMemory :: Uuid -> Rpc Int
getVmMemory uuid = readConfigPropertyDef uuid vmMemory 0
getVmName :: Uuid -> Rpc String
getVmName uuid = readConfigPropertyDef uuid vmName ""
getVmImagePath :: Uuid -> Rpc FilePath
getVmImagePath uuid = readConfigPropertyDef uuid vmImagePath ""
getVmSlot :: Uuid -> Rpc Int
getVmSlot uuid = readConfigPropertyDef uuid vmSlot 0
getVmPvAddons :: MonadRpc e m => Uuid -> m Bool
getVmPvAddons uuid = readConfigPropertyDef uuid vmPvAddons False
getVmPvAddonsVersion :: Uuid -> Rpc String
getVmPvAddonsVersion uuid = readConfigPropertyDef uuid vmPvAddonsVersion ""
getVmTimeOffset :: Uuid -> Rpc Int
getVmTimeOffset uuid = readConfigPropertyDef uuid vmTimeOffset 0
getVmCryptoUser :: Uuid -> Rpc String
getVmCryptoUser uuid = readConfigPropertyDef uuid vmCryptoUser ""
getVmCryptoKeyDirs :: Uuid -> Rpc String
getVmCryptoKeyDirs uuid = readConfigPropertyDef uuid vmCryptoKeyDirs ""
getVmAutoS3Wake :: Uuid -> Rpc Bool
getVmAutoS3Wake uuid = readConfigPropertyDef uuid vmAutoS3Wake False
getVmNotify uuid = readConfigPropertyDef uuid vmNotify ""
getVmHvm uuid = readConfigPropertyDef uuid vmHvm False
getVmPae uuid = readConfigPropertyDef uuid vmPae False
getVmApic uuid = readConfigPropertyDef uuid vmApic False
getVmViridian uuid = readConfigPropertyDef uuid vmViridian False
getVmNx uuid = readConfigPropertyDef uuid vmNx False
getVmSound uuid = readConfigPropertyDef uuid vmSound ""
getVmDisplay uuid = readConfigPropertyDef uuid vmDisplay ""
getVmBoot uuid = readConfigPropertyDef uuid vmBoot ""
getVmCmdLine uuid = readConfigPropertyDef uuid vmCmdLine ""
getVmKernel uuid = readConfigPropertyDef uuid vmKernel ""
getVmKernelExtract uuid = readConfigPropertyDef uuid vmKernelExtract ""
getVmInitrd uuid = readConfigPropertyDef uuid vmInitrd ""
getVmInitrdExtract uuid = readConfigPropertyDef uuid vmInitrdExtract ""
getVmAcpiPt uuid = readConfigPropertyDef uuid vmAcpiPt False
getVmVcpus uuid = readConfigPropertyDef uuid vmVcpus (0::Int)
getVmCoresPerSocket uuid = readConfigPropertyDef uuid vmCoresPerSocket (0::Int)
getVmVideoram uuid = readConfigPropertyDef uuid vmVideoram (0::Int)
getVmPassthroughMmio uuid = readConfigPropertyDef uuid vmPassthroughMmio ""
getVmPassthroughIo uuid = readConfigPropertyDef uuid vmPassthroughIo ""
getVmFlaskLabel uuid = readConfigPropertyDef uuid vmFlaskLabel ""
getVmHap uuid = readConfigPropertyDef uuid vmHap False
getVmSmbiosPt uuid = readConfigPropertyDef uuid vmSmbiosPt False
getVmDescription uuid = readConfigPropertyDef uuid vmDescription ""
getVmStartOnBootPriority uuid = readConfigPropertyDef uuid vmStartOnBootPriority (0::Int)
getVmKeepAlive uuid = readConfigPropertyDef uuid vmKeepAlive False
getVmProvidesNetworkBackend uuid = readConfigPropertyDef uuid vmProvidesNetworkBackend False
getVmProvidesDefaultNetworkBackend uuid = readConfigPropertyDef uuid vmProvidesDefaultNetworkBackend False
getVmMeasured uuid = readConfigPropertyDef uuid vmMeasured False
getVmProvidesGraphicsFallback uuid = readConfigPropertyDef uuid vmProvidesGraphicsFallback False
getVmSeamlessId uuid = readConfigPropertyDef uuid vmSeamlessId ""
getVmStartFromSuspendImage uuid = readConfigPropertyDef uuid vmStartFromSuspendImage ""
getVmBedOperation uuid = dbMaybeRead ("/vm/" ++ show uuid ++ "/backend/state/operation")
getVmQemuDmPath uuid = readConfigPropertyDef uuid vmQemuDmPath "/opt/xensource/libexec/qemu-dm-wrapper"
getVmQemuDmTimeout uuid = readConfigPropertyDef uuid vmQemuDmTimeout (30::Int)
getVmGreedyPcibackBind uuid = readConfigPropertyDef uuid vmGreedyPcibackBind True
getVmRunPostCreate uuid = readConfigProperty uuid vmRunPostCreate
getVmRunPreDelete uuid = readConfigProperty uuid vmRunPreDelete
getVmRunPreBoot uuid = readConfigProperty uuid vmRunPreBoot
getVmRunInsteadofStart uuid = readConfigProperty uuid vmRunInsteadofStart
getVmRunOnStateChange uuid = readConfigProperty uuid vmRunOnStateChange
getVmRunOnAcpiStateChange uuid = readConfigProperty uuid vmRunOnAcpiStateChange
getVmS3Mode uuid = readConfigPropertyDef uuid vmS3Mode S3Pv
getVmS4Mode uuid = readConfigPropertyDef uuid vmS4Mode S4Pv
getVmVsnd uuid = readConfigPropertyDef uuid vmVsnd False
getVmShutdownPriority uuid =
readConfigProperty uuid vmShutdownPriority >>= test where
test (Just pri) = return pri
-- default shutdown priority of pvm is lower so it gets shutdown later on
test Nothing = getVmGraphics uuid >>= \t -> return $ case t of
HDX -> (-10)
_ -> (0 :: Int)
getVmExtraXenvm uuid = concat . intersperse ";" <$> readConfigPropertyDef uuid vmExtraXenvm []
getVmExtraHvm uuid = concat . intersperse ";" <$> readConfigPropertyDef uuid vmExtraHvms []
-- 'native experience' related properties
nativeOverride uuid value f
= ifM (getVmNativeExperience uuid) (return value) f
getVmNativeExperience uuid = readConfigPropertyDef uuid vmNativeExperience False
getVmShowSwitcher uuid = nativeOverride uuid False $ readConfigPropertyDef uuid vmShowSwitcher True
getVmWirelessControl uuid = nativeOverride uuid True $ readConfigPropertyDef uuid vmWirelessControl False
getVmUsbGrabDevices uuid = nativeOverride uuid True $ readConfigPropertyDef uuid vmUsbGrabDevices False
getVmControlPlatformPowerState uuid = nativeOverride uuid True $ readConfigPropertyDef uuid vmControlPlatformPowerState False
getVmRealm uuid = readConfigPropertyDef uuid vmRealm ""
getVmSyncUuid uuid = readConfigPropertyDef uuid vmSyncUuid ""
getVmIcbinnPath uuid = readConfigPropertyDef uuid vmIcbinnPath ""
getVmOvfTransportIso uuid = readConfigPropertyDef uuid vmOvfTransportIso False
getVmDownloadProgress uuid = fromMaybe (0::Int) <$> dbRead ("/vm/"++show uuid++"/download-progress")
getVmReady uuid = readConfigPropertyDef uuid vmReady True
getVmVkbd uuid = readConfigPropertyDef uuid vmVkbd False
getVmVfb uuid = readConfigPropertyDef uuid vmVfb False
getVmV4V uuid = readConfigPropertyDef uuid vmV4v False
getVmRestrictDisplayDepth uuid = readConfigPropertyDef uuid vmRestrictDisplayDepth False
getVmRestrictDisplayRes uuid = readConfigPropertyDef uuid vmRestrictDisplayRes False
getVmPreserveOnReboot uuid = readConfigPropertyDef uuid vmPreserveOnReboot False
getVmBootSentinel uuid = f <$> readConfigPropertyDef uuid vmBootSentinel "" where
f "" = Nothing
f x = Just x
getVmHpet uuid = readConfigPropertyDef uuid vmHpet vmHpetDefault
getVmTimerMode uuid = readConfigPropertyDef uuid vmTimerMode vmTimerModeDefault
getVmNestedHvm uuid = readConfigPropertyDef uuid vmNestedHvm False
getVmSerial uuid = readConfigPropertyDef uuid vmSerial ""
| crogers1/manager | xenmgr/Vm/Queries.hs | gpl-2.0 | 40,784 | 0 | 41 | 10,514 | 10,334 | 5,183 | 5,151 | 807 | 7 |
module Fenfire.Latex2Png where
-- Copyright (c) 2007, Benja Fallenstein, Tuukka Hastrup
-- This file is part of Fenfire.
--
-- Fenfire 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.
--
-- Fenfire 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 Fenfire; if not, write to the Free
-- Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
-- MA 02111-1307 USA
import System.Cmd (rawSystem)
import System.Environment (getArgs)
import System.Directory (getTemporaryDirectory, getCurrentDirectory,
setCurrentDirectory, createDirectory, getDirectoryContents, removeFile,
removeDirectory, doesFileExist)
import System.IO (openTempFile, openFile, hPutStr, hClose, IOMode(..))
import System.Exit (ExitCode(..))
import Control.Monad (when)
import System.Glib.UTFString (newUTFString, readCString)
import System.IO.Unsafe (unsafePerformIO)
-- XXX real toUTF isn't exported from System.Glib.UTFString
toUTF :: String -> String
toUTF s = unsafePerformIO $ newUTFString s >>= readCString
latex content = unlines [
"\\documentclass[12pt]{article}",
"\\pagestyle{empty}",
"\\usepackage[utf8]{inputenc}",
"\\begin{document}",
toUTF content,
"\\end{document}"
]
withLatexPng :: String -> (Maybe FilePath -> IO a) -> IO a
withLatexPng code block = do
oldCurrentDirectory <- getCurrentDirectory
tmp <- getTemporaryDirectory
let dir = tmp ++ "/latex2png" -- FIXME / and predictable name
createDirectory dir
setCurrentDirectory dir
let latexFile = "latex2png-temp"
writeFile (latexFile++".tex") $ latex code
-- FIXME set environment variables necessary for security, use rlimit
rawSystem "latex" ["--interaction=nonstopmode", latexFile++".tex"]
rawSystem "dvipng" ["-bgTransparent", "-Ttight", "", "--noghostscript", "-l1", latexFile++".dvi"]
let resultname = latexFile++"1.png"
haveResult <- doesFileExist resultname
let resultfile = if haveResult then Just resultname else Nothing
result <- block $ resultfile
setCurrentDirectory tmp
files <- getDirectoryContents dir
flip mapM_ files $ \filename -> do
let file = dir ++ "/" ++ filename -- FIXME /
exists <- doesFileExist file -- XXX to ignore . and ..
when exists $ removeFile $ file
removeDirectory dir
setCurrentDirectory oldCurrentDirectory
return result
main = do
[code,outfile] <- getArgs
handle <- openFile outfile WriteMode
png <- withLatexPng code $ maybe (return "") readFile
hPutStr handle png
hClose handle
| timthelion/fenfire | Fenfire/Latex2Png.hs | gpl-2.0 | 3,003 | 0 | 15 | 569 | 584 | 306 | 278 | 50 | 2 |
module Math.REPL.Prim.Definitions
( unaryOps
, binaryOps
, defVars
, defFuns
, defBinds
) where
--------------------------------------------------------------------------------
import Math.REPL.Prim.Bindings (Bindings, mkBind)
import Math.REPL.Prim.Expr (Operator (..))
import Math.REPL.Prim.Function (Function, oneArg)
--------------------------------------------------------------------------------
import Control.Arrow (second)
--------------------------------------------------------------------------------
unaryOps :: [(Char, Operator)]
unaryOps = [ ('-', UnaryOp negate) ]
--------------------------------------------------------------------------------
-- | Binary Operators
binaryOps :: [(Char, Operator)]
binaryOps = [ ('+', BinaryOp (+))
, ('-', BinaryOp (-))
, ('*', BinaryOp (*))
, ('/', BinaryOp (/))
, ('^', BinaryOp (**))
]
--------------------------------------------------------------------------------
-- | List of pre-defined @Functions@
defFuns :: [(String, Function)]
defFuns = map (second oneArg)
[ ("sin", sin)
, ("cos", cos)
, ("tan", tan)
, ("asin", asin)
, ("acos", acos)
, ("atan", atan)
, ("sinh", sinh)
, ("cosh", cosh)
, ("tanh", tanh)
, ("exp", exp)
, ("log", log)
, ("log10", logBase 10)
, ("sqrt", sqrt)
, ("ceil", fromInteger . ceiling)
, ("floor", fromInteger . floor)
, ("abs", abs)
]
--------------------------------------------------------------------------------
-- | List of provided variables
defVars :: [(String, Double)]
defVars = [ ("pi", pi)
, ("e", exp 1)
]
--------------------------------------------------------------------------------
-- | Default bindings, created using defVars and defFuns
defBinds :: Bindings
defBinds = mkBind defVars defFuns
--------------------------------------------------------------------------------
| sumitsahrawat/calculator | src/Math/REPL/Prim/Definitions.hs | gpl-2.0 | 2,141 | 0 | 8 | 547 | 453 | 293 | 160 | 41 | 1 |
main = putStrLn "hello, world"
--IO
| YPBlib/NaiveFunGame_hs | cw/cli.hs | gpl-3.0 | 36 | 0 | 5 | 6 | 10 | 5 | 5 | 1 | 1 |
{-
Constructs the set of LR(0) parse table items from a deterministic context-free
grammar. This was created as Project 2 for EECS 665 at the University of Kansas.
Author: Ryan Scott
-}
module Main (main) where
import Data.Text.IO (putStr)
import LR0ItemSet.Algorithm
import LR0ItemSet.Data
import LR0ItemSet.Parse
import Prelude hiding (putStr)
import Text.Parsec (parse)
-- | Where the program begins
main :: IO ()
main = do
-- Parse standard input
stuff <- getContents
case parse parseGrammar "" stuff of
-- If unsuccessful, abort with an error message.
Left e -> print e
-- Otherwise, find the LR(0) item set and print the results.
Right g -> putStr . execLR0Writer $ lr0ItemSet g | RyanGlScott/lr0-item-set | src/Main.hs | gpl-3.0 | 740 | 0 | 11 | 166 | 127 | 70 | 57 | 13 | 2 |
module Main where
import System.Console.GetOpt
import System.Environment
import qualified Options as O
import qualified GPSDClient as G
main :: IO ()
main =
do
args <- getArgs
-- Parse options, getting a list of option actions
let (actions, nonOptions, errors) = getOpt Permute O.optionDescriptions args
-- Here we thread defaultOptions through all supplied option actions
opts <- foldl (>>=) (return O.defaultOptions) actions
time_str <- G.processGPSDStream opts
let formatted_time_str = takeWhile ( /= '.' ) time_str
putStrLn formatted_time_str
| jefflasslett/gpstime | Main.hs | gpl-3.0 | 590 | 0 | 11 | 120 | 139 | 75 | 64 | 14 | 1 |
module Main where
import Control.Monad (when)
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as BS
import System.Environment (getArgs)
minimalPNG :: ByteString
minimalPNG = BS.pack
[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x04, 0x00, 0x00, 0x00, 0xb5, 0x1c, 0x0c,
0x02, 0x00, 0x00, 0x00, 0x0b, 0x49, 0x44, 0x41,
0x54, 0x18, 0x57, 0x63, 0x60, 0x60, 0x00, 0x00,
0x00, 0x03, 0x00, 0x01, 0x68, 0x26, 0x59, 0x0d,
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44,
0xae, 0x42, 0x60, 0x82]
magicPNG :: ByteString
magicPNG = BS.take 8 minimalPNG
truncatePNG :: FilePath -> IO Bool
truncatePNG fp =
do isPNG <- BS.isPrefixOf magicPNG <$> BS.readFile fp
when isPNG $ BS.writeFile fp minimalPNG
return isPNG
main :: IO ()
main = getArgs >>= mapM truncatePNG >>= print
| Tuplanolla/ties341-unsafe | Truncate.hs | gpl-3.0 | 939 | 0 | 10 | 179 | 370 | 223 | 147 | 25 | 1 |
{-# LANGUAGE PackageImports #-}
{-
This module provides the public interface to the Archivemount library.
It provides both standard archivemount calls(mount/unmount)
as well as portable versions which can unpack a tarbal rather than mounting it,
when mounting is impossible.
GPL3. License info is at the bottom of the file.
-}
module System.Directory.Archivemount
(Option(ReadOnly,NoBackup,NoSave,Subtree,OtherOption)
,MountStatus(Mounted,CouldNotMount)
,UnmountStatus(Unmounted,CouldNotUnmount,CouldNotUnmountDeviceOrResourceBusy)
,Version
(InstalledVersion
,archivemount,fuse,fusermount,fuseKernelInterface
,NotInstalled
,InstalledButVersionInfoCouldNotBeParsed)
,archivemountVersion
,mountArchive
,unmountArchive
,mountArchivePortable
,unmountArchivePortable
,mountTarballForSavingPortable
,FileTreeMetaData
,saveAndUnmountNoncompressedTarballPortable) where
import System.Directory.Archivemount.Types
import System.Directory.Archivemount.VersionParser
import "base" System.Exit
(ExitCode(ExitSuccess))
import "base" Data.Maybe
(mapMaybe
,fromJust)
import "base" Data.List
(intersperse
,isInfixOf)
import "base" Data.Functor
((<$>))
import "base" System.Environment
(getEnvironment)
import "base" Control.Monad
(filterM)
import qualified "tar" Codec.Archive.Tar as Tar
(extract)
import qualified "containers" Data.Map as Map
(toList
,fromList
,insert
,difference
,intersectionWith
,Map)
import "process" System.Process
(readProcess
,readProcessWithExitCode
,proc
,env)
import "process-shortversions" System.Process.ShortVersions
(commandExists
,runCommandInDir
,readCreateProcessWithExitCode)
import "directory" System.Directory
(createDirectoryIfMissing
,doesDirectoryExist
,doesFileExist
,removeDirectory
,removeFile)
import "small-print" Control.Exception.SmallPrint
((*@)
,(*@@)
,exception)
import "filepath" System.FilePath
(pathSeparators
,(</>)
,takeDirectory
,makeRelative)
import "filepath-extrautils" System.FilePath.ExtraUtils
(getRealDirectoryContents
,getDirectoryContentsRecursive)
import qualified "bytestring" Data.ByteString as BS
(readFile
,writeFile
,ByteString)
import "temporary" System.IO.Temp
(withSystemTempDirectory)
import "unix-compat" System.PosixCompat.Files
(createNamedPipe
,unionFileModes
,ownerReadMode
,ownerWriteMode
,FileStatus
,getFileStatus
,fileSize
,modificationTime)
-- | See `archivemount -h` for details.
data Option
= ReadOnly
| NoBackup
| NoSave
| Subtree String
| OtherOption String
-- ^ Too lazy to write them all out...
-- Passed to archivemount like so:
-- [OtherOption "a",OtherOption "b"] => archivemount -o a,b
optsToArgs
:: [Option]
-> [String]
optsToArgs
options
= "-o"
: (intersperse "," $ map optToArg options)
optToArg :: Option -> String
optToArg ReadOnly = "readonly"
optToArg NoBackup = "nobackup"
optToArg NoSave = "nosave"
optToArg (Subtree match) = "subtree="++match
optToArg (OtherOption option) = option
archivemountCommand = "archivemount"
fusermountCommand = "fusermount"
tarCommand = "tar"
-- | Returns NotInstalled if archivemount is not in the $PATH.
archivemountVersion :: IO Version
archivemountVersion =
(do
(_,versionInfo,errs) <- readProcessWithExitCode archivemountCommand ["-V"] ""
return $ parseVersionInfo $ errs ++ versionInfo) *@@ archivemountNotInstalled
where
archivemountNotInstalled =
exception
(not <$> archivemountInstalled)
(return NotInstalled)
archivemountInstalled :: IO Bool
archivemountInstalled =
commandExists archivemountCommand
mountArchive
:: [Option] -- ^ Standard options to be passed to archivemount
-> [String] -- ^ Arguments to be passed to archivemount as raw strings.
-> FilePath -- ^ What to mount(path to the archive to be mounted)
-> FilePath -- ^ Where to mount it(the desired mount point). If it doesn't exist, this directory will be created.
-> IO MountStatus -- ^ Did the mount succeed
mountArchive options args archive mountPoint
= do
createDirectoryIfMissing True mountPoint
(exitCode,output,errors)
<- readProcessWithExitCode
archivemountCommand
( args
++ optsToArgs options
++ [archive
,mountPoint])
""
case exitCode of
ExitSuccess -> return Mounted
_ -> return $ CouldNotMount
$ unlines
[ "Standard ouput:"
, output
, "Errors:"
, errors]
unmountArchive :: FilePath -> IO UnmountStatus
unmountArchive whatToUnmount = do
environment <- getEnvironment
let unmountCommand = (proc fusermountCommand ["-u",whatToUnmount])
{env=Just $ Map.toList $ Map.insert "LANG" "C" $ Map.fromList environment}
(exitCode,output,errors)
<- readCreateProcessWithExitCode
unmountCommand
""
case exitCode of
ExitSuccess -> return Unmounted
_ -> (return $ CouldNotUnmount
$ unlines
[ "Standard ouput:"
, output
, "Errors:"
, errors]) *@@ (deviceOrResourceBusy errors)
where
deviceOrResourceBusy errors =
exception
(return $ isInfixOf "Device or resource busy" errors)
(return $ CouldNotUnmountDeviceOrResourceBusy)
-- | Mount an archive in a portable fashion.
-- If archivemount >= 0.8.2 is available,
-- then mount with archivemount and the nosave option.
-- Otherwise, unpack the archive to the mountpoint.
-- If the mount point does not exist, create it.
-- WARNING: mount/unmountArchivePortable do not save changes. You must do this yourself.
-- any changes to the archive in it's mounted state will be lost/deleted.
mountArchivePortable
:: FilePath -- ^ What to mount (path to archive)
-> FilePath -- ^ Where to mount it (mountpoint)
-> IO MountStatus
mountArchivePortable archive mountpoint =
mountArchive [NoSave] [] archive mountpoint *@@ nosaveNotSupported
where
nosaveNotSupported =
exception
(return True) -- (not <$> nosaveSupported) -- TODO fix permission denied bugs with archivemount
(unpackArchive archive mountpoint)
-- | Unpack the archive to the given directory using tar.
unpackArchive
:: FilePath -- ^ What to unpack
-> FilePath -- ^ Where to unpack it
-> IO MountStatus
unpackArchive archive unpackTo = do
createDirectoryIfMissing True unpackTo
Tar.extract unpackTo archive -- TODO Check for errors
return Mounted
-- | Return true if archivemount is installed and the nosave option is supported.
nosaveSupported :: IO Bool
nosaveSupported = do
v <- archivemountVersion
case v of
InstalledVersion{} -> return $ archivemount v >= [0,8,2]
_ -> return False
-- | Unmount a mounted archive or delete an unpacked version of an archive.
-- WARNING: mount/unmountArchivePortable do not save changes. You must do this yourself.
-- any changes to the archive in it's mounted state will be lost/deleted.
unmountArchivePortable
:: FilePath -- ^ What to unmount/delete
-> IO UnmountStatus
unmountArchivePortable toUnmount =
(do
status <- unmountArchive toUnmount
removeDirectory toUnmount *@@ mountPointNoLongerExists *@@ archiveNotUnmounted status
return status) *@@ nosaveNotSupported
where
archiveNotUnmounted status =
exception
(return $ status /= Unmounted)
(return ())
mountPointNoLongerExists =
exception
(not <$> doesDirectoryExist toUnmount)
(return ())
nosaveNotSupported =
exception
(return True) --(not <$> nosaveSupported) -- TODO fix Permission Denied bugs with archivemount
(deleteUnpackedDirectoryTree toUnmount)
-- | Delete a directory recursively. If an exception occures, report CouldNotUnmount
deleteUnpackedDirectoryTree
:: FilePath -- ^ Path to directory to be deleted.
-> IO UnmountStatus
deleteUnpackedDirectoryTree dir = do
(exitCode,output,errors) <-
readProcessWithExitCode "rm" ["-rf",dir] ""
case exitCode of
ExitSuccess -> return Unmounted
_ -> return $ CouldNotUnmount $ unlines ["Output:",output,"Errors:",errors]
type FileTreeMetaData = [(FilePath,FileStatus)]
gatherFileTreeMetaData
:: FilePath -- ^ root of file tree where we will gather the metadata
-> IO FileTreeMetaData
gatherFileTreeMetaData root = do
fileTree' <- getDirectoryContentsRecursive root
statuses <- mapM getFileStatus fileTree'
putStrLn $ unwords ["Root:",root]
putStrLn $ unlines fileTree'
let fileTree = map (\path->makeRelative root path) fileTree'
return $ zip fileTree statuses
mountTarballForSavingPortable
:: FilePath -- ^ what to mount(path to archive)
-> FilePath -- ^ where to mount it (mountpoint)
-> IO (MountStatus,Maybe FileTreeMetaData)
mountTarballForSavingPortable archive mountpoint = do
status <- mountArchivePortable archive mountpoint
fileTreeMetaData <- (Just <$> gatherFileTreeMetaData mountpoint) *@@ mountFailed status
return (status,fileTreeMetaData)
where
mountFailed status =
exception
(return $ status /= Mounted)
(return $ Nothing)
saveAndUnmountNoncompressedTarballPortable
:: FileTreeMetaData -- ^ The metadata returned by
-> FilePath -- ^ Path to directory tree which we are saving
-> FilePath -- ^ Path to tarbal to which we are saving
-> IO UnmountStatus
saveAndUnmountNoncompressedTarballPortable before mountpoint archive = do
after <- gatherFileTreeMetaData mountpoint
let diff = mapDiff timeOrSizeChanged (Map.fromList before) (Map.fromList after)
modifiedFiles <- filterM doesFileExist $ modified diff
createdFiles <- filterM doesFileExist $ created diff
modifiedFileContents <- mapM BS.readFile modifiedFiles
createdFileContents <- mapM BS.readFile createdFiles
status <- unmountArchivePortable mountpoint
(do
putStrLn "Deleted files"
mapM putStrLn $ deleted diff
putStrLn "Modified files"
mapM putStrLn $ modified diff
putStrLn "Created files"
mapM putStrLn $ created diff
deleteFromTar archive (deleted diff++modified diff)
appendToTar archive $ zip (modifiedFiles ++ createdFiles) (modifiedFileContents ++ createdFileContents)
return status) *@@ couldNotUnmount status
where
couldNotUnmount status = exception
(return $ not $ status == Unmounted)
(return status)
data Diff a =
Diff
{modified :: [a]
,created :: [a]
,deleted :: [a]}
mapDiff :: (Ord k) => (a->a->Bool)-> Map.Map k a -> Map.Map k a -> Diff k
mapDiff changeCheck before after =
Diff
{modified = map fst $ filter snd $ Map.toList $ Map.intersectionWith changeCheck before after
,created = map fst $ Map.toList $ Map.difference after before
,deleted = map fst $ Map.toList $ Map.difference before after}
timeOrSizeChanged :: FileStatus -> FileStatus -> Bool
timeOrSizeChanged before after
= fileSize before /= fileSize after
|| modificationTime before /= modificationTime after
deleteFromTar
:: FilePath -- ^ Archive
-> [FilePath] -- ^ What to delete from it
-> IO ()
deleteFromTar archive whatToDelete = do
_ <- readProcess tarCommand (("--file="++archive):"--delete":whatToDelete) ""
return ()
appendToTar
:: FilePath -- ^ archive
-> [(FilePath,BS.ByteString)] -- ^ objects to append
-> IO ()
appendToTar archive fileObjects = do
withSystemTempDirectory (filter (\c->notElem c pathSeparators) archive) appendObjects
return ()
where
appendObjects tempDir = mapM (appendObject tempDir) fileObjects
appendObject tempDir (path,content) = do
createDirectoryIfMissing True $ tempDir </> takeDirectory path
putStrLn $ unwords ["Creating named pipe:",tempDir </> path,"tempdir is:",tempDir]
createNamedPipe (tempDir </> path) (unionFileModes ownerReadMode ownerWriteMode)
BS.writeFile (tempDir </> path) content
runCommandInDir tempDir tarCommand ["-r","--file="++archive,path]
removeFile (tempDir </> path)
{-
-- Copyright (C) 2013 Timothy Hobbs <timothyhobbs@seznam.cz>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
-} | timthelion/archivemount-hs | src/System/Directory/Archivemount.hs | gpl-3.0 | 12,246 | 0 | 15 | 1,995 | 2,549 | 1,365 | 1,184 | 313 | 2 |
module Amoeba.View.Language where
import Amoeba.View.Output.Types
data GameNode = TitleScreen | Screen2 | Screen3 | Screen4
deriving (Ord, Eq, Show, Enum)
data Command = Finish
| Render
| StartViewPointMoving ScreenPoint
| ViewPointMoving ScreenPoint
| StopViewPointMoving ScreenPoint
deriving (Ord, Eq, Show) | graninas/The-Amoeba-World | src/Amoeba/View/Language.hs | gpl-3.0 | 373 | 0 | 6 | 102 | 89 | 53 | 36 | 10 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Endpoints.AuthEndpoints where
import qualified Data.Text.Lazy as LT (fromStrict)
import Data.Text
import Auth
import Control.Monad.IO.Class (liftIO)
import Control.Monad (when)
import Network.HTTP.Types
import qualified Web.Scotty as S
import qualified Web.Scotty.Cookie as SC
authenticate :: Text -> S.ActionM ()
authenticate uri =
flip S.rescue (\_ -> S.status badRequest400) $ do
code <- S.param "code"
authenticated <- liftIO $ checkAuth code uri
when authenticated $
SC.setSimpleCookie (getCookieName uri) code
S.redirect $ LT.fromStrict uri
| DunderRoffe/sjolind.se | src/Endpoints/AuthEndpoints.hs | gpl-3.0 | 666 | 0 | 11 | 151 | 187 | 103 | 84 | 18 | 1 |
{-# 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.SWF.TerminateWorkflowExecution
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- 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 <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Records a 'WorkflowExecutionTerminated' event and forces closure of the
-- workflow execution identified by the given domain, runId, and workflowId. The
-- child policy, registered with the workflow type or specified when starting
-- this execution, is applied to any open child workflow executions of this
-- workflow execution.
--
-- If the identified workflow execution was in progress, it is terminated
-- immediately. If a runId is not specified, then the 'WorkflowExecutionTerminated' event is recorded in the history of the current open workflow with the
-- matching workflowId in the domain. You should consider using 'RequestCancelWorkflowExecution' action instead because it allows the workflow to gracefully close while 'TerminateWorkflowExecution' does not. Access Control
--
-- You can use IAM policies to control this action's access to Amazon SWF
-- resources as follows:
--
-- Use a 'Resource' element with the domain name to limit the action to only
-- specified domains. Use an 'Action' element to allow or deny permission to call
-- this action. You cannot use an IAM policy to constrain this action's
-- parameters. If the caller does not have sufficient permissions to invoke the
-- action, or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute's cause parameter will be set to
-- OPERATION_NOT_PERMITTED. For details and example IAM policies, see <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAMto Manage Access to Amazon SWF Workflows>.
--
-- <http://docs.aws.amazon.com/amazonswf/latest/apireference/API_TerminateWorkflowExecution.html>
module Network.AWS.SWF.TerminateWorkflowExecution
(
-- * Request
TerminateWorkflowExecution
-- ** Request constructor
, terminateWorkflowExecution
-- ** Request lenses
, tweChildPolicy
, tweDetails
, tweDomain
, tweReason
, tweRunId
, tweWorkflowId
-- * Response
, TerminateWorkflowExecutionResponse
-- ** Response constructor
, terminateWorkflowExecutionResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.SWF.Types
import qualified GHC.Exts
data TerminateWorkflowExecution = TerminateWorkflowExecution
{ _tweChildPolicy :: Maybe ChildPolicy
, _tweDetails :: Maybe Text
, _tweDomain :: Text
, _tweReason :: Maybe Text
, _tweRunId :: Maybe Text
, _tweWorkflowId :: Text
} deriving (Eq, Read, Show)
-- | 'TerminateWorkflowExecution' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'tweChildPolicy' @::@ 'Maybe' 'ChildPolicy'
--
-- * 'tweDetails' @::@ 'Maybe' 'Text'
--
-- * 'tweDomain' @::@ 'Text'
--
-- * 'tweReason' @::@ 'Maybe' 'Text'
--
-- * 'tweRunId' @::@ 'Maybe' 'Text'
--
-- * 'tweWorkflowId' @::@ 'Text'
--
terminateWorkflowExecution :: Text -- ^ 'tweDomain'
-> Text -- ^ 'tweWorkflowId'
-> TerminateWorkflowExecution
terminateWorkflowExecution p1 p2 = TerminateWorkflowExecution
{ _tweDomain = p1
, _tweWorkflowId = p2
, _tweRunId = Nothing
, _tweReason = Nothing
, _tweDetails = Nothing
, _tweChildPolicy = Nothing
}
-- | If set, specifies the policy to use for the child workflow executions of the
-- workflow execution being terminated. This policy overrides the child policy
-- specified for the workflow execution at registration time or when starting
-- the execution.
--
-- The supported child policies are:
--
-- TERMINATE: the child executions will be terminated. REQUEST_CANCEL: a
-- request to cancel will be attempted for each child execution by recording a 'WorkflowExecutionCancelRequested' event in its history. It is up to the decider to take appropriate actions
-- when it receives an execution history with this event. ABANDON: no action
-- will be taken. The child executions will continue to run. A child policy for
-- this workflow execution must be specified either as a default for the
-- workflow type or through this parameter. If neither this parameter is set nor
-- a default child policy was specified at registration time then a fault will
-- be returned.
tweChildPolicy :: Lens' TerminateWorkflowExecution (Maybe ChildPolicy)
tweChildPolicy = lens _tweChildPolicy (\s a -> s { _tweChildPolicy = a })
-- | /Optional./ Details for terminating the workflow execution.
tweDetails :: Lens' TerminateWorkflowExecution (Maybe Text)
tweDetails = lens _tweDetails (\s a -> s { _tweDetails = a })
-- | The domain of the workflow execution to terminate.
tweDomain :: Lens' TerminateWorkflowExecution Text
tweDomain = lens _tweDomain (\s a -> s { _tweDomain = a })
-- | /Optional./ A descriptive reason for terminating the workflow execution.
tweReason :: Lens' TerminateWorkflowExecution (Maybe Text)
tweReason = lens _tweReason (\s a -> s { _tweReason = a })
-- | The runId of the workflow execution to terminate.
tweRunId :: Lens' TerminateWorkflowExecution (Maybe Text)
tweRunId = lens _tweRunId (\s a -> s { _tweRunId = a })
-- | The workflowId of the workflow execution to terminate.
tweWorkflowId :: Lens' TerminateWorkflowExecution Text
tweWorkflowId = lens _tweWorkflowId (\s a -> s { _tweWorkflowId = a })
data TerminateWorkflowExecutionResponse = TerminateWorkflowExecutionResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'TerminateWorkflowExecutionResponse' constructor.
terminateWorkflowExecutionResponse :: TerminateWorkflowExecutionResponse
terminateWorkflowExecutionResponse = TerminateWorkflowExecutionResponse
instance ToPath TerminateWorkflowExecution where
toPath = const "/"
instance ToQuery TerminateWorkflowExecution where
toQuery = const mempty
instance ToHeaders TerminateWorkflowExecution
instance ToJSON TerminateWorkflowExecution where
toJSON TerminateWorkflowExecution{..} = object
[ "domain" .= _tweDomain
, "workflowId" .= _tweWorkflowId
, "runId" .= _tweRunId
, "reason" .= _tweReason
, "details" .= _tweDetails
, "childPolicy" .= _tweChildPolicy
]
instance AWSRequest TerminateWorkflowExecution where
type Sv TerminateWorkflowExecution = SWF
type Rs TerminateWorkflowExecution = TerminateWorkflowExecutionResponse
request = post "TerminateWorkflowExecution"
response = nullResponse TerminateWorkflowExecutionResponse
| dysinger/amazonka | amazonka-swf/gen/Network/AWS/SWF/TerminateWorkflowExecution.hs | mpl-2.0 | 7,523 | 0 | 9 | 1,478 | 726 | 447 | 279 | 78 | 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.DFAReporting.Files.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists files for a user profile.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.files.list@.
module Network.Google.Resource.DFAReporting.Files.List
(
-- * REST Resource
FilesListResource
-- * Creating a Request
, filesList
, FilesList
-- * Request Lenses
, flXgafv
, flUploadProtocol
, flAccessToken
, flUploadType
, flProFileId
, flSortOrder
, flScope
, flPageToken
, flSortField
, flMaxResults
, flCallback
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.files.list@ method which the
-- 'FilesList' request conforms to.
type FilesListResource =
"dfareporting" :>
"v3.5" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"files" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "sortOrder" FilesListSortOrder :>
QueryParam "scope" FilesListScope :>
QueryParam "pageToken" Text :>
QueryParam "sortField" FilesListSortField :>
QueryParam "maxResults" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] FileList
-- | Lists files for a user profile.
--
-- /See:/ 'filesList' smart constructor.
data FilesList =
FilesList'
{ _flXgafv :: !(Maybe Xgafv)
, _flUploadProtocol :: !(Maybe Text)
, _flAccessToken :: !(Maybe Text)
, _flUploadType :: !(Maybe Text)
, _flProFileId :: !(Textual Int64)
, _flSortOrder :: !FilesListSortOrder
, _flScope :: !FilesListScope
, _flPageToken :: !(Maybe Text)
, _flSortField :: !FilesListSortField
, _flMaxResults :: !(Textual Int32)
, _flCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FilesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'flXgafv'
--
-- * 'flUploadProtocol'
--
-- * 'flAccessToken'
--
-- * 'flUploadType'
--
-- * 'flProFileId'
--
-- * 'flSortOrder'
--
-- * 'flScope'
--
-- * 'flPageToken'
--
-- * 'flSortField'
--
-- * 'flMaxResults'
--
-- * 'flCallback'
filesList
:: Int64 -- ^ 'flProFileId'
-> FilesList
filesList pFlProFileId_ =
FilesList'
{ _flXgafv = Nothing
, _flUploadProtocol = Nothing
, _flAccessToken = Nothing
, _flUploadType = Nothing
, _flProFileId = _Coerce # pFlProFileId_
, _flSortOrder = FLSODescending
, _flScope = FLSMine
, _flPageToken = Nothing
, _flSortField = FLSFLastModifiedTime
, _flMaxResults = 10
, _flCallback = Nothing
}
-- | V1 error format.
flXgafv :: Lens' FilesList (Maybe Xgafv)
flXgafv = lens _flXgafv (\ s a -> s{_flXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
flUploadProtocol :: Lens' FilesList (Maybe Text)
flUploadProtocol
= lens _flUploadProtocol
(\ s a -> s{_flUploadProtocol = a})
-- | OAuth access token.
flAccessToken :: Lens' FilesList (Maybe Text)
flAccessToken
= lens _flAccessToken
(\ s a -> s{_flAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
flUploadType :: Lens' FilesList (Maybe Text)
flUploadType
= lens _flUploadType (\ s a -> s{_flUploadType = a})
-- | The Campaign Manager 360 user profile ID.
flProFileId :: Lens' FilesList Int64
flProFileId
= lens _flProFileId (\ s a -> s{_flProFileId = a}) .
_Coerce
-- | Order of sorted results.
flSortOrder :: Lens' FilesList FilesListSortOrder
flSortOrder
= lens _flSortOrder (\ s a -> s{_flSortOrder = a})
-- | The scope that defines which results are returned.
flScope :: Lens' FilesList FilesListScope
flScope = lens _flScope (\ s a -> s{_flScope = a})
-- | The value of the nextToken from the previous result page.
flPageToken :: Lens' FilesList (Maybe Text)
flPageToken
= lens _flPageToken (\ s a -> s{_flPageToken = a})
-- | The field by which to sort the list.
flSortField :: Lens' FilesList FilesListSortField
flSortField
= lens _flSortField (\ s a -> s{_flSortField = a})
-- | Maximum number of results to return.
flMaxResults :: Lens' FilesList Int32
flMaxResults
= lens _flMaxResults (\ s a -> s{_flMaxResults = a})
. _Coerce
-- | JSONP
flCallback :: Lens' FilesList (Maybe Text)
flCallback
= lens _flCallback (\ s a -> s{_flCallback = a})
instance GoogleRequest FilesList where
type Rs FilesList = FileList
type Scopes FilesList =
'["https://www.googleapis.com/auth/dfareporting"]
requestClient FilesList'{..}
= go _flProFileId _flXgafv _flUploadProtocol
_flAccessToken
_flUploadType
(Just _flSortOrder)
(Just _flScope)
_flPageToken
(Just _flSortField)
(Just _flMaxResults)
_flCallback
(Just AltJSON)
dFAReportingService
where go
= buildClient (Proxy :: Proxy FilesListResource)
mempty
| brendanhay/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Files/List.hs | mpl-2.0 | 6,262 | 0 | 23 | 1,659 | 1,118 | 642 | 476 | 154 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.Types.Sum
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.IAM.Types.Sum where
import Network.AWS.Prelude
data AssignmentStatusType
= Any
| Assigned
| Unassigned
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText AssignmentStatusType where
parser = takeLowerText >>= \case
"any" -> pure Any
"assigned" -> pure Assigned
"unassigned" -> pure Unassigned
e -> fromTextError $ "Failure parsing AssignmentStatusType from value: '" <> e
<> "'. Accepted values: Any, Assigned, Unassigned"
instance ToText AssignmentStatusType where
toText = \case
Any -> "Any"
Assigned -> "Assigned"
Unassigned -> "Unassigned"
instance Hashable AssignmentStatusType
instance ToByteString AssignmentStatusType
instance ToQuery AssignmentStatusType
instance ToHeader AssignmentStatusType
data ContextKeyTypeEnum
= Binary
| BinaryList
| Boolean
| BooleanList
| Date
| DateList
| IP
| IPList
| Numeric
| NumericList
| String
| StringList
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ContextKeyTypeEnum where
parser = takeLowerText >>= \case
"binary" -> pure Binary
"binarylist" -> pure BinaryList
"boolean" -> pure Boolean
"booleanlist" -> pure BooleanList
"date" -> pure Date
"datelist" -> pure DateList
"ip" -> pure IP
"iplist" -> pure IPList
"numeric" -> pure Numeric
"numericlist" -> pure NumericList
"string" -> pure String
"stringlist" -> pure StringList
e -> fromTextError $ "Failure parsing ContextKeyTypeEnum from value: '" <> e
<> "'. Accepted values: binary, binaryList, boolean, booleanList, date, dateList, ip, ipList, numeric, numericList, string, stringList"
instance ToText ContextKeyTypeEnum where
toText = \case
Binary -> "binary"
BinaryList -> "binaryList"
Boolean -> "boolean"
BooleanList -> "booleanList"
Date -> "date"
DateList -> "dateList"
IP -> "ip"
IPList -> "ipList"
Numeric -> "numeric"
NumericList -> "numericList"
String -> "string"
StringList -> "stringList"
instance Hashable ContextKeyTypeEnum
instance ToByteString ContextKeyTypeEnum
instance ToQuery ContextKeyTypeEnum
instance ToHeader ContextKeyTypeEnum
data EncodingType
= Pem
| SSH
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText EncodingType where
parser = takeLowerText >>= \case
"pem" -> pure Pem
"ssh" -> pure SSH
e -> fromTextError $ "Failure parsing EncodingType from value: '" <> e
<> "'. Accepted values: PEM, SSH"
instance ToText EncodingType where
toText = \case
Pem -> "PEM"
SSH -> "SSH"
instance Hashable EncodingType
instance ToByteString EncodingType
instance ToQuery EncodingType
instance ToHeader EncodingType
data EntityType
= ETAWSManagedPolicy
| ETGroup
| ETLocalManagedPolicy
| ETRole
| ETUser
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText EntityType where
parser = takeLowerText >>= \case
"awsmanagedpolicy" -> pure ETAWSManagedPolicy
"group" -> pure ETGroup
"localmanagedpolicy" -> pure ETLocalManagedPolicy
"role" -> pure ETRole
"user" -> pure ETUser
e -> fromTextError $ "Failure parsing EntityType from value: '" <> e
<> "'. Accepted values: AWSManagedPolicy, Group, LocalManagedPolicy, Role, User"
instance ToText EntityType where
toText = \case
ETAWSManagedPolicy -> "AWSManagedPolicy"
ETGroup -> "Group"
ETLocalManagedPolicy -> "LocalManagedPolicy"
ETRole -> "Role"
ETUser -> "User"
instance Hashable EntityType
instance ToByteString EntityType
instance ToQuery EntityType
instance ToHeader EntityType
data PolicyEvaluationDecisionType
= Allowed
| ExplicitDeny
| ImplicitDeny
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText PolicyEvaluationDecisionType where
parser = takeLowerText >>= \case
"allowed" -> pure Allowed
"explicitdeny" -> pure ExplicitDeny
"implicitdeny" -> pure ImplicitDeny
e -> fromTextError $ "Failure parsing PolicyEvaluationDecisionType from value: '" <> e
<> "'. Accepted values: allowed, explicitDeny, implicitDeny"
instance ToText PolicyEvaluationDecisionType where
toText = \case
Allowed -> "allowed"
ExplicitDeny -> "explicitDeny"
ImplicitDeny -> "implicitDeny"
instance Hashable PolicyEvaluationDecisionType
instance ToByteString PolicyEvaluationDecisionType
instance ToQuery PolicyEvaluationDecisionType
instance ToHeader PolicyEvaluationDecisionType
instance FromXML PolicyEvaluationDecisionType where
parseXML = parseXMLText "PolicyEvaluationDecisionType"
data PolicyScopeType
= AWS
| All
| Local
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText PolicyScopeType where
parser = takeLowerText >>= \case
"aws" -> pure AWS
"all" -> pure All
"local" -> pure Local
e -> fromTextError $ "Failure parsing PolicyScopeType from value: '" <> e
<> "'. Accepted values: AWS, All, Local"
instance ToText PolicyScopeType where
toText = \case
AWS -> "AWS"
All -> "All"
Local -> "Local"
instance Hashable PolicyScopeType
instance ToByteString PolicyScopeType
instance ToQuery PolicyScopeType
instance ToHeader PolicyScopeType
data PolicySourceType
= AWSManaged
| Group
| None
| Role
| User
| UserManaged
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText PolicySourceType where
parser = takeLowerText >>= \case
"aws-managed" -> pure AWSManaged
"group" -> pure Group
"none" -> pure None
"role" -> pure Role
"user" -> pure User
"user-managed" -> pure UserManaged
e -> fromTextError $ "Failure parsing PolicySourceType from value: '" <> e
<> "'. Accepted values: aws-managed, group, none, role, user, user-managed"
instance ToText PolicySourceType where
toText = \case
AWSManaged -> "aws-managed"
Group -> "group"
None -> "none"
Role -> "role"
User -> "user"
UserManaged -> "user-managed"
instance Hashable PolicySourceType
instance ToByteString PolicySourceType
instance ToQuery PolicySourceType
instance ToHeader PolicySourceType
instance FromXML PolicySourceType where
parseXML = parseXMLText "PolicySourceType"
data ReportFormatType =
TextCSV
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ReportFormatType where
parser = takeLowerText >>= \case
"text/csv" -> pure TextCSV
e -> fromTextError $ "Failure parsing ReportFormatType from value: '" <> e
<> "'. Accepted values: text/csv"
instance ToText ReportFormatType where
toText = \case
TextCSV -> "text/csv"
instance Hashable ReportFormatType
instance ToByteString ReportFormatType
instance ToQuery ReportFormatType
instance ToHeader ReportFormatType
instance FromXML ReportFormatType where
parseXML = parseXMLText "ReportFormatType"
data ReportStateType
= Complete
| Inprogress
| Started
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ReportStateType where
parser = takeLowerText >>= \case
"complete" -> pure Complete
"inprogress" -> pure Inprogress
"started" -> pure Started
e -> fromTextError $ "Failure parsing ReportStateType from value: '" <> e
<> "'. Accepted values: COMPLETE, INPROGRESS, STARTED"
instance ToText ReportStateType where
toText = \case
Complete -> "COMPLETE"
Inprogress -> "INPROGRESS"
Started -> "STARTED"
instance Hashable ReportStateType
instance ToByteString ReportStateType
instance ToQuery ReportStateType
instance ToHeader ReportStateType
instance FromXML ReportStateType where
parseXML = parseXMLText "ReportStateType"
data StatusType
= Active
| Inactive
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText StatusType where
parser = takeLowerText >>= \case
"active" -> pure Active
"inactive" -> pure Inactive
e -> fromTextError $ "Failure parsing StatusType from value: '" <> e
<> "'. Accepted values: Active, Inactive"
instance ToText StatusType where
toText = \case
Active -> "Active"
Inactive -> "Inactive"
instance Hashable StatusType
instance ToByteString StatusType
instance ToQuery StatusType
instance ToHeader StatusType
instance FromXML StatusType where
parseXML = parseXMLText "StatusType"
data SummaryKeyType
= AccessKeysPerUserQuota
| AccountAccessKeysPresent
| AccountMFAEnabled
| AccountSigningCertificatesPresent
| AttachedPoliciesPerGroupQuota
| AttachedPoliciesPerRoleQuota
| AttachedPoliciesPerUserQuota
| GroupPolicySizeQuota
| Groups
| GroupsPerUserQuota
| GroupsQuota
| MFADevices
| MFADevicesInUse
| Policies
| PoliciesQuota
| PolicySizeQuota
| PolicyVersionsInUse
| PolicyVersionsInUseQuota
| ServerCertificates
| ServerCertificatesQuota
| SigningCertificatesPerUserQuota
| UserPolicySizeQuota
| Users
| UsersQuota
| VersionsPerPolicyQuota
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText SummaryKeyType where
parser = takeLowerText >>= \case
"accesskeysperuserquota" -> pure AccessKeysPerUserQuota
"accountaccesskeyspresent" -> pure AccountAccessKeysPresent
"accountmfaenabled" -> pure AccountMFAEnabled
"accountsigningcertificatespresent" -> pure AccountSigningCertificatesPresent
"attachedpoliciespergroupquota" -> pure AttachedPoliciesPerGroupQuota
"attachedpoliciesperrolequota" -> pure AttachedPoliciesPerRoleQuota
"attachedpoliciesperuserquota" -> pure AttachedPoliciesPerUserQuota
"grouppolicysizequota" -> pure GroupPolicySizeQuota
"groups" -> pure Groups
"groupsperuserquota" -> pure GroupsPerUserQuota
"groupsquota" -> pure GroupsQuota
"mfadevices" -> pure MFADevices
"mfadevicesinuse" -> pure MFADevicesInUse
"policies" -> pure Policies
"policiesquota" -> pure PoliciesQuota
"policysizequota" -> pure PolicySizeQuota
"policyversionsinuse" -> pure PolicyVersionsInUse
"policyversionsinusequota" -> pure PolicyVersionsInUseQuota
"servercertificates" -> pure ServerCertificates
"servercertificatesquota" -> pure ServerCertificatesQuota
"signingcertificatesperuserquota" -> pure SigningCertificatesPerUserQuota
"userpolicysizequota" -> pure UserPolicySizeQuota
"users" -> pure Users
"usersquota" -> pure UsersQuota
"versionsperpolicyquota" -> pure VersionsPerPolicyQuota
e -> fromTextError $ "Failure parsing SummaryKeyType from value: '" <> e
<> "'. Accepted values: AccessKeysPerUserQuota, AccountAccessKeysPresent, AccountMFAEnabled, AccountSigningCertificatesPresent, AttachedPoliciesPerGroupQuota, AttachedPoliciesPerRoleQuota, AttachedPoliciesPerUserQuota, GroupPolicySizeQuota, Groups, GroupsPerUserQuota, GroupsQuota, MFADevices, MFADevicesInUse, Policies, PoliciesQuota, PolicySizeQuota, PolicyVersionsInUse, PolicyVersionsInUseQuota, ServerCertificates, ServerCertificatesQuota, SigningCertificatesPerUserQuota, UserPolicySizeQuota, Users, UsersQuota, VersionsPerPolicyQuota"
instance ToText SummaryKeyType where
toText = \case
AccessKeysPerUserQuota -> "AccessKeysPerUserQuota"
AccountAccessKeysPresent -> "AccountAccessKeysPresent"
AccountMFAEnabled -> "AccountMFAEnabled"
AccountSigningCertificatesPresent -> "AccountSigningCertificatesPresent"
AttachedPoliciesPerGroupQuota -> "AttachedPoliciesPerGroupQuota"
AttachedPoliciesPerRoleQuota -> "AttachedPoliciesPerRoleQuota"
AttachedPoliciesPerUserQuota -> "AttachedPoliciesPerUserQuota"
GroupPolicySizeQuota -> "GroupPolicySizeQuota"
Groups -> "Groups"
GroupsPerUserQuota -> "GroupsPerUserQuota"
GroupsQuota -> "GroupsQuota"
MFADevices -> "MFADevices"
MFADevicesInUse -> "MFADevicesInUse"
Policies -> "Policies"
PoliciesQuota -> "PoliciesQuota"
PolicySizeQuota -> "PolicySizeQuota"
PolicyVersionsInUse -> "PolicyVersionsInUse"
PolicyVersionsInUseQuota -> "PolicyVersionsInUseQuota"
ServerCertificates -> "ServerCertificates"
ServerCertificatesQuota -> "ServerCertificatesQuota"
SigningCertificatesPerUserQuota -> "SigningCertificatesPerUserQuota"
UserPolicySizeQuota -> "UserPolicySizeQuota"
Users -> "Users"
UsersQuota -> "UsersQuota"
VersionsPerPolicyQuota -> "VersionsPerPolicyQuota"
instance Hashable SummaryKeyType
instance ToByteString SummaryKeyType
instance ToQuery SummaryKeyType
instance ToHeader SummaryKeyType
instance FromXML SummaryKeyType where
parseXML = parseXMLText "SummaryKeyType"
| olorin/amazonka | amazonka-iam/gen/Network/AWS/IAM/Types/Sum.hs | mpl-2.0 | 14,013 | 0 | 12 | 3,199 | 2,604 | 1,307 | 1,297 | 346 | 0 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, TypeSynonymInstances #-}
{-
Copyright (C) 2010, 2011, 2012 Jeroen Ketema and Jakob Grue Simonsen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
-- This module defines a system of notation for the ordinal omega, including
-- computable sequences of length at most omega.
module Omega (
Omega(OmegaElement),
OmegaSequence, constructSequence,
OmegaTermSequence, OmegaStepSequence,
OmegaReduction, constructModulus
) where
import Term
import RuleAndSystem
import SystemOfNotation
import Reduction
import Prelude
import Data.List
-- System of notation for the ordinal omega
data Omega = OmegaElement Integer
instance SystemOfNotation Omega where
ordKind (OmegaElement n)
| n == 0 = ZeroOrdinal
| otherwise = SuccOrdinal
ordPred (OmegaElement n)
| n > 0 = OmegaElement (n - 1)
| otherwise = error "Predeccessor undefined"
ordLimit (OmegaElement _)
= error "Limit function undefined" -- Omega has no limit ordinals
ordLimitPred (OmegaElement _)
= OmegaElement 0
ord2Int (OmegaElement n)
= n
instance UnivalentSystem Omega where
ordLeq (OmegaElement m) (OmegaElement n)
= m <= n
ordZero
= OmegaElement 0
ordSucc (OmegaElement n)
= OmegaElement (n + 1)
-- Computable sequences of length at most omega.
data OmegaSequence t = OmegaSequenceCons [t]
instance ComputableSequence Omega t (OmegaSequence t) where
getElem (OmegaSequenceCons xs) (OmegaElement n)
= genericIndex xs n
getFrom (OmegaSequenceCons xs) (OmegaElement n)
= genericDrop n xs
select (OmegaSequenceCons xs) f alpha
= select' xs 0 alpha
where select' _ _ (_, Nothing) = []
select' ys m (z, Just beta) = head ys' : continuation
where continuation = select' ys' n next_elem
ys' = genericDrop (n - m) ys
next_elem = f (z, beta)
OmegaElement n = beta
hasOmegaDomain _
= True
-- Construct a computable sequence of length at most omega out of a list.
constructSequence :: [t] -> OmegaSequence t
constructSequence = OmegaSequenceCons
-- Reductions of length omega.
type OmegaTermSequence s v = OmegaSequence (Term s v)
type OmegaStepSequence s v r = OmegaSequence (Step s v)
type OmegaReduction s v r
= Reduction s v r (OmegaTermSequence s v) (OmegaStepSequence s v r) Omega
-- Construct a modulus out of a function on natural numbers.
constructModulus :: (Integer -> Integer) -> Modulus Omega
constructModulus f (OmegaElement 0) m
= OmegaElement (f m)
constructModulus _ _ _
= error "Modulus only defined for zero"
| jeroenk/iTRSsImplemented | Omega.hs | agpl-3.0 | 3,376 | 0 | 12 | 835 | 668 | 344 | 324 | 63 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.