code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Scrape (scrapeRippleAddress) where import Control.Applicative import Control.Monad import UnexceptionalIO (fromIO, runUnexceptionalIO) import Control.Exception (fromException) import Control.Error (EitherT, fmapLT, throwT, runEitherT) import Network.URI (URI, uriPath) import Network.Http.Client (withConnection, establishConnection, sendRequest, buildRequest, http, Response, receiveResponse, RequestBuilder, emptyBody, getStatusCode) import qualified Network.Http.Client as HttpStreams import Blaze.ByteString.Builder (Builder) import System.IO.Streams (OutputStream, InputStream) import System.IO.Streams.Attoparsec (parseFromStream, ParseException(..)) import Network.HTTP.Types.Status (Status) import Data.ByteString (ByteString) import Data.Attoparsec.ByteString.Char8 import qualified Data.ByteString.Char8 as BS8 -- eww scrapeRippleAddress :: URI -> IO (Either Error ByteString) scrapeRippleAddress uri = get uri (return ()) extractRippleAddress rippleAlphabet :: [Char] rippleAlphabet = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz" extractRippleAddress :: Parser ByteString extractRippleAddress = do _ <- skipFront Data.Attoparsec.ByteString.Char8.skipWhile (/='r') _ <- Data.Attoparsec.ByteString.Char8.char 'r' c <- Data.Attoparsec.ByteString.Char8.peekChar case c of Just c' -> when (not (inClass rippleAlphabet c')) $ do Data.Attoparsec.ByteString.Char8.skipWhile (/='r') _ <- Data.Attoparsec.ByteString.Char8.char 'r' return () _ -> return () bs <- Data.Attoparsec.ByteString.Char8.takeWhile (inClass rippleAlphabet) return $ BS8.singleton 'r' `BS8.append` bs where skipFront = do Data.Attoparsec.ByteString.Char8.skipWhile (/='R') string (BS8.pack "Ripple Address:") <|> (anyChar >> skipFront) get :: URI -> RequestBuilder () -> Parser a -> IO (Either Error a) get uri req parser = oneShotHTTP HttpStreams.GET uri req emptyBody (responseHandler parser) data Error = ParseError | RequestError Status | OtherError deriving (Show, Eq) responseHandler :: Parser a -> Response -> InputStream ByteString -> IO (Either Error a) responseHandler parser resp i = runUnexceptionalIO $ runEitherT $ do case getStatusCode resp of code | code >= 200 && code < 300 -> return () code -> throwT $ RequestError $ toEnum code fmapLT (handle . fromException) $ fromIO $ parseFromStream parser i where handle (Just (ParseException _)) = ParseError handle _ = OtherError oneShotHTTP :: HttpStreams.Method -> URI -> RequestBuilder () -> (OutputStream Builder -> IO ()) -> (Response -> InputStream ByteString -> IO b) -> IO b oneShotHTTP method uri req body handler = do req' <- buildRequest $ do http method (BS8.pack $ uriPath uri) req withConnection (establishConnection url) $ \conn -> do sendRequest conn req' body receiveResponse conn handler where url = BS8.pack $ show uri -- URI can only have ASCII, so should be safe
singpolyma/RippleUnion-Federation
Scrape.hs
isc
2,900
4
16
401
930
492
438
59
3
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE TupleSections #-} -- | Main monad in which the type checker runs, as well as ancillary -- data definitions. module Language.Futhark.TypeChecker.Monad ( TypeM, runTypeM, askEnv, askImportName, atTopLevel, enteringModule, bindSpaced, qualifyTypeVars, lookupMTy, lookupImport, localEnv, TypeError (..), withIndexLink, unappliedFunctor, unknownVariable, unknownType, underscoreUse, Notes, aNote, MonadTypeChecker (..), checkName, checkAttr, badOnLeft, module Language.Futhark.Warnings, Env (..), TySet, FunSig (..), ImportTable, NameMap, BoundV (..), Mod (..), TypeBinding (..), MTy (..), anySignedType, anyUnsignedType, anyIntType, anyFloatType, anyNumberType, anyPrimType, Namespace (..), intrinsicsNameMap, topLevelNameMap, mkTypeVarName, ) where import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State.Strict import Data.Either import Data.List (find, isPrefixOf) import qualified Data.Map.Strict as M import Data.Maybe import qualified Data.Set as S import qualified Data.Version as Version import Futhark.FreshNames hiding (newName) import qualified Futhark.FreshNames import Futhark.Util.Console import Futhark.Util.Pretty hiding (space) import Language.Futhark import Language.Futhark.Semantic import Language.Futhark.Warnings import qualified Paths_futhark import Prelude hiding (mapM, mod) -- | A note with extra information regarding a type error. newtype Note = Note Doc -- | A collection of 'Note's. newtype Notes = Notes [Note] deriving (Semigroup, Monoid) instance Pretty Note where ppr (Note msg) = "Note:" <+> align msg instance Pretty Notes where ppr (Notes notes) = foldMap (((line <> line) <>) . ppr) notes -- | A single note. aNote :: Pretty a => a -> Notes aNote = Notes . pure . Note . ppr -- | Information about an error during type checking. data TypeError = TypeError SrcLoc Notes Doc instance Pretty TypeError where ppr (TypeError loc notes msg) = text (inRed $ "Error at " <> locStr loc <> ":") </> msg <> ppr notes errorIndexUrl :: Doc errorIndexUrl = version_url <> "error-index.html" where version = Paths_futhark.version base_url = "https://futhark.readthedocs.io/en/" version_url | last (Version.versionBranch version) == 0 = base_url <> "latest/" | otherwise = base_url <> "v" <> text (Version.showVersion version) <> "/" -- | Attach a reference to documentation explaining the error in more detail. withIndexLink :: Doc -> Doc -> Doc withIndexLink href msg = stack [ msg, "\nFor more information, see:", indent 2 (ppr errorIndexUrl <> "#" <> href) ] -- | An unexpected functor appeared! unappliedFunctor :: MonadTypeChecker m => SrcLoc -> m a unappliedFunctor loc = typeError loc mempty "Cannot have parametric module here." -- | An unknown variable was referenced. unknownVariable :: MonadTypeChecker m => Namespace -> QualName Name -> SrcLoc -> m a unknownVariable space name loc = typeError loc mempty $ "Unknown" <+> ppr space <+> pquote (ppr name) -- | An unknown type was referenced. unknownType :: MonadTypeChecker m => SrcLoc -> QualName Name -> m a unknownType loc name = typeError loc mempty $ "Unknown type" <+> ppr name <> "." -- | A name prefixed with an underscore was used. underscoreUse :: MonadTypeChecker m => SrcLoc -> QualName Name -> m a underscoreUse loc name = typeError loc mempty $ "Use of" <+> pquote (ppr name) <> ": variables prefixed with underscore may not be accessed." -- | A mapping from import strings to 'Env's. This is used to resolve -- @import@ declarations. type ImportTable = M.Map String Env data Context = Context { contextEnv :: Env, contextImportTable :: ImportTable, contextImportName :: ImportName, -- | Currently type-checking at the top level? If false, we are -- inside a module. contextAtTopLevel :: Bool } data TypeState = TypeState { stateNameSource :: VNameSource, stateWarnings :: Warnings, stateCounter :: Int } -- | The type checker runs in this monad. newtype TypeM a = TypeM ( ReaderT Context (StateT TypeState (Except (Warnings, TypeError))) a ) deriving ( Monad, Functor, Applicative, MonadReader Context, MonadState TypeState ) instance MonadError TypeError TypeM where throwError e = TypeM $ do ws <- gets stateWarnings throwError (ws, e) catchError (TypeM m) f = TypeM $ m `catchError` f' where f' (_, e) = let TypeM m' = f e in m' -- | Run a 'TypeM' computation. runTypeM :: Env -> ImportTable -> ImportName -> VNameSource -> TypeM a -> (Warnings, Either TypeError (a, VNameSource)) runTypeM env imports fpath src (TypeM m) = do let ctx = Context env imports fpath True s = TypeState src mempty 0 case runExcept $ runStateT (runReaderT m ctx) s of Left (ws, e) -> (ws, Left e) Right (x, TypeState src' ws _) -> (ws, Right (x, src')) -- | Retrieve the current 'Env'. askEnv :: TypeM Env askEnv = asks contextEnv -- | The name of the current file/import. askImportName :: TypeM ImportName askImportName = asks contextImportName -- | Are we type-checking at the top level, or are we inside a nested -- module? atTopLevel :: TypeM Bool atTopLevel = asks contextAtTopLevel -- | We are now going to type-check the body of a module. enteringModule :: TypeM a -> TypeM a enteringModule = local $ \ctx -> ctx {contextAtTopLevel = False} -- | Look up a module type. lookupMTy :: SrcLoc -> QualName Name -> TypeM (QualName VName, MTy) lookupMTy loc qn = do (scope, qn'@(QualName _ name)) <- checkQualNameWithEnv Signature qn loc (qn',) <$> maybe explode return (M.lookup name $ envSigTable scope) where explode = unknownVariable Signature qn loc -- | Look up an import. lookupImport :: SrcLoc -> FilePath -> TypeM (FilePath, Env) lookupImport loc file = do imports <- asks contextImportTable my_path <- asks contextImportName let canonical_import = includeToString $ mkImportFrom my_path file loc case M.lookup canonical_import imports of Nothing -> typeError loc mempty $ "Unknown import" <+> dquotes (text canonical_import) </> "Known:" <+> commasep (map text (M.keys imports)) Just scope -> return (canonical_import, scope) -- | Evaluate a 'TypeM' computation within an extended (/not/ -- replaced) environment. localEnv :: Env -> TypeM a -> TypeM a localEnv env = local $ \ctx -> let env' = env <> contextEnv ctx in ctx {contextEnv = env'} incCounter :: TypeM Int incCounter = do s <- get put s {stateCounter = stateCounter s + 1} return $ stateCounter s -- | Monads that support type checking. The reason we have this -- internal interface is because we use distinct monads for checking -- expressions and declarations. class Monad m => MonadTypeChecker m where warn :: Located loc => loc -> Doc -> m () newName :: VName -> m VName newID :: Name -> m VName newTypeName :: Name -> m VName bindNameMap :: NameMap -> m a -> m a bindVal :: VName -> BoundV -> m a -> m a checkQualName :: Namespace -> QualName Name -> SrcLoc -> m (QualName VName) lookupType :: SrcLoc -> QualName Name -> m (QualName VName, [TypeParam], StructRetType, Liftedness) lookupMod :: SrcLoc -> QualName Name -> m (QualName VName, Mod) lookupVar :: SrcLoc -> QualName Name -> m (QualName VName, PatType) checkNamedDim :: SrcLoc -> QualName Name -> m (QualName VName) checkNamedDim loc v = do (v', t) <- lookupVar loc v case t of Scalar (Prim (Signed Int64)) -> return v' _ -> typeError loc mempty $ "Dimension declaration" <+> ppr v <+> "should be of type i64." typeError :: Located loc => loc -> Notes -> Doc -> m a -- | Elaborate the given name in the given namespace at the given -- location, producing the corresponding unique 'VName'. checkName :: MonadTypeChecker m => Namespace -> Name -> SrcLoc -> m VName checkName space name loc = qualLeaf <$> checkQualName space (qualName name) loc -- | Map source-level names do fresh unique internal names, and -- evaluate a type checker context with the mapping active. bindSpaced :: MonadTypeChecker m => [(Namespace, Name)] -> m a -> m a bindSpaced names body = do names' <- mapM (newID . snd) names let mapping = M.fromList (zip names $ map qualName names') bindNameMap mapping body instance MonadTypeChecker TypeM where warn loc problem = modify $ \s -> s { stateWarnings = stateWarnings s <> singleWarning (srclocOf loc) problem } newName v = do s <- get let (v', src') = Futhark.FreshNames.newName (stateNameSource s) v put $ s {stateNameSource = src'} return v' newID s = newName $ VName s 0 newTypeName name = do i <- incCounter newID $ mkTypeVarName name i bindNameMap m = local $ \ctx -> let env = contextEnv ctx in ctx {contextEnv = env {envNameMap = m <> envNameMap env}} bindVal v t = local $ \ctx -> ctx { contextEnv = (contextEnv ctx) { envVtable = M.insert v t $ envVtable $ contextEnv ctx } } checkQualName space name loc = snd <$> checkQualNameWithEnv space name loc lookupType loc qn = do outer_env <- askEnv (scope, qn'@(QualName qs name)) <- checkQualNameWithEnv Type qn loc case M.lookup name $ envTypeTable scope of Nothing -> unknownType loc qn Just (TypeAbbr l ps (RetType dims def)) -> return (qn', ps, RetType dims $ qualifyTypeVars outer_env mempty qs def, l) lookupMod loc qn = do (scope, qn'@(QualName _ name)) <- checkQualNameWithEnv Term qn loc case M.lookup name $ envModTable scope of Nothing -> unknownVariable Term qn loc Just m -> return (qn', m) lookupVar loc qn = do outer_env <- askEnv (env, qn'@(QualName qs name)) <- checkQualNameWithEnv Term qn loc case M.lookup name $ envVtable env of Nothing -> unknownVariable Term qn loc Just (BoundV _ t) | "_" `isPrefixOf` baseString name -> underscoreUse loc qn | otherwise -> case getType t of Nothing -> typeError loc mempty $ "Attempt to use function" <+> pprName name <+> "as value." Just t' -> return ( qn', fromStruct $ qualifyTypeVars outer_env mempty qs t' ) typeError loc notes s = throwError $ TypeError (srclocOf loc) notes s -- | Extract from a type a first-order type. getType :: TypeBase dim as -> Maybe (TypeBase dim as) getType (Scalar Arrow {}) = Nothing getType t = Just t checkQualNameWithEnv :: Namespace -> QualName Name -> SrcLoc -> TypeM (Env, QualName VName) checkQualNameWithEnv space qn@(QualName quals name) loc = do env <- askEnv descend env quals where descend scope [] | Just name' <- M.lookup (space, name) $ envNameMap scope = return (scope, name') | otherwise = unknownVariable space qn loc descend scope (q : qs) | Just (QualName _ q') <- M.lookup (Term, q) $ envNameMap scope, Just res <- M.lookup q' $ envModTable scope = case res of ModEnv q_scope -> do (scope', QualName qs' name') <- descend q_scope qs return (scope', QualName (q' : qs') name') ModFun {} -> unappliedFunctor loc | otherwise = unknownVariable space qn loc -- | Try to prepend qualifiers to the type names such that they -- represent how to access the type in some scope. qualifyTypeVars :: Env -> [VName] -> [VName] -> TypeBase (DimDecl VName) as -> TypeBase (DimDecl VName) as qualifyTypeVars outer_env orig_except ref_qs = onType (S.fromList orig_except) where onType :: S.Set VName -> TypeBase (DimDecl VName) as -> TypeBase (DimDecl VName) as onType except (Array as u et shape) = Array as u (onScalar except et) (fmap (onDim except) shape) onType except (Scalar t) = Scalar $ onScalar except t onScalar _ (Prim t) = Prim t onScalar except (TypeVar as u tn targs) = TypeVar as u tn' $ map (onTypeArg except) targs where tn' = typeNameFromQualName $ qual except $ qualNameFromTypeName tn onScalar except (Record m) = Record $ M.map (onType except) m onScalar except (Sum m) = Sum $ M.map (map $ onType except) m onScalar except (Arrow as p t1 (RetType dims t2)) = Arrow as p (onType except' t1) $ RetType dims (onType except' t2) where except' = case p of Named p' -> S.insert p' except Unnamed -> except onTypeArg except (TypeArgDim d loc) = TypeArgDim (onDim except d) loc onTypeArg except (TypeArgType t loc) = TypeArgType (onType except t) loc onDim except (NamedDim qn) = NamedDim $ qual except qn onDim _ d = d qual except (QualName orig_qs name) | name `elem` except || reachable orig_qs name outer_env = QualName orig_qs name | otherwise = prependAsNecessary [] ref_qs $ QualName orig_qs name prependAsNecessary qs rem_qs (QualName orig_qs name) | reachable (qs ++ orig_qs) name outer_env = QualName (qs ++ orig_qs) name | otherwise = case rem_qs of q : rem_qs' -> prependAsNecessary (qs ++ [q]) rem_qs' (QualName orig_qs name) [] -> QualName orig_qs name reachable [] name env = name `M.member` envVtable env || isJust (find matches $ M.elems (envTypeTable env)) where matches (TypeAbbr _ _ (RetType _ (Scalar (TypeVar _ _ (TypeName x_qs name') _)))) = null x_qs && name == name' matches _ = False reachable (q : qs') name env | Just (ModEnv env') <- M.lookup q $ envModTable env = reachable qs' name env' | otherwise = False -- | Turn a 'Left' 'TypeError' into an actual error. badOnLeft :: Either TypeError a -> TypeM a badOnLeft = either throwError return -- | All signed integer types. anySignedType :: [PrimType] anySignedType = map Signed [minBound .. maxBound] -- | All unsigned integer types. anyUnsignedType :: [PrimType] anyUnsignedType = map Unsigned [minBound .. maxBound] -- | All integer types. anyIntType :: [PrimType] anyIntType = anySignedType ++ anyUnsignedType -- | All floating-point types. anyFloatType :: [PrimType] anyFloatType = map FloatType [minBound .. maxBound] -- | All number types. anyNumberType :: [PrimType] anyNumberType = anyIntType ++ anyFloatType -- | All primitive types. anyPrimType :: [PrimType] anyPrimType = Bool : anyIntType ++ anyFloatType --- Name handling -- | The 'NameMap' corresponding to the intrinsics module. intrinsicsNameMap :: NameMap intrinsicsNameMap = M.fromList $ map mapping $ M.toList intrinsics where mapping (v, IntrinsicType {}) = ((Type, baseName v), QualName [] v) mapping (v, _) = ((Term, baseName v), QualName [] v) -- | The names that are available in the initial environment. topLevelNameMap :: NameMap topLevelNameMap = M.filterWithKey (\k _ -> available k) intrinsicsNameMap where available :: (Namespace, Name) -> Bool available (Type, _) = True available (Term, v) = v `S.member` (type_names <> binop_names <> fun_names) where type_names = S.fromList $ map (nameFromString . pretty) anyPrimType binop_names = S.fromList $ map (nameFromString . pretty) [minBound .. (maxBound :: BinOp)] fun_names = S.fromList $ map nameFromString ["shape"] available _ = False -- | Construct the name of a new type variable given a base -- description and a tag number (note that this is distinct from -- actually constructing a VName; the tag here is intended for human -- consumption but the machine does not care). mkTypeVarName :: Name -> Int -> Name mkTypeVarName desc i = desc <> nameFromString (mapMaybe subscript (show i)) where subscript = flip lookup $ zip "0123456789" "₀₁₂₃₄₅₆₇₈₉" -- | Type-check an attribute. checkAttr :: MonadTypeChecker m => AttrInfo Name -> m (AttrInfo VName) checkAttr (AttrComp f attrs loc) = AttrComp f <$> mapM checkAttr attrs <*> pure loc checkAttr (AttrAtom (AtomName v) loc) = pure $ AttrAtom (AtomName v) loc checkAttr (AttrAtom (AtomInt x) loc) = pure $ AttrAtom (AtomInt x) loc
HIPERFIT/futhark
src/Language/Futhark/TypeChecker/Monad.hs
isc
16,761
0
19
4,050
5,045
2,590
2,455
395
12
module Parser where import Control.Monad import Data.Char import Expense newtype Parser a = Parser (String -> Int -> Int -> Either (String, Int, Int) (a, String, Int, Int)) uncurry3 :: (a, b, c) -> (a -> b -> c -> d) -> d uncurry3 (x, y, z) f = f x y z runParser :: Parser a -> String -> Int -> Int -> Either (String, Int, Int) (a, String, Int, Int) runParser (Parser p) = p instance Functor Parser where fmap f (Parser p) = Parser $ \i l c -> case p i l c of Left x -> Left x Right (x, r, l', c') -> Right (f x, r, l', c') instance Monad Parser where return v = Parser $ \i l c -> Right (v, i, l, c) fail msg = Parser $ \_ l c -> Left (msg, l, c) p >>= f = Parser $ \i l c -> case runParser p i l c of Left x -> Left x Right (x, r, l', c') -> runParser (f x) r l' c' updateLine :: Int -> Char -> Int updateLine n c = if c == '\n' then n + 1 else n updateCol :: Int -> Char -> Int updateCol n c = if c == '\n' then 1 else n + 1 peek :: Parser Char peek = failOnEOF >> (Parser $ \i@(x:_) l c -> Right (x, i, l, c)) item :: Parser Char item = failOnEOF >> (Parser $ \(x:xs) l c -> Right (x, xs, updateLine l x, updateCol c x)) satisfy :: (Char -> Bool) -> Parser Char satisfy p = do failOnEOF; c <- peek if p c then item else fail "Predicate not satisfied" satisfyString :: (Char -> Bool) -> Parser String satisfyString p = satisfy p >>= (\c -> return [c]) failOnEOF :: Parser () failOnEOF = do e <- eof; when e $ fail "Unexpected end of input" eof :: Parser Bool eof = Parser $ \i l c -> return (if null i then (True, [], l, c) else (False, i, l, c)) satisfyMany :: (Char -> Bool) -> Parser String satisfyMany p = do e <- eof if e then return [] else do c <- peek if not $ p c then return [] else compose where compose = do d <- item; r <- satisfyMany p; return $ d:r satisfyMany1 :: (Char -> Bool) -> Parser String satisfyMany1 p = do c <- satisfy p; r <- satisfyMany p; return $ c:r (<++) :: Show a => Parser a -> Parser a -> Parser a Parser p1 <++ Parser p2 = Parser $ \i l c -> case p1 i l c of Left _ -> p2 i l c Right x -> Right x parseIntAsDouble :: Parser Double parseIntAsDouble = parseInt >>= (\v -> return (fromIntegral v :: Double)) parseInt :: Parser Int parseInt = satisfyMany1 isDigit >>= (\v -> return (read v :: Int)) parseDouble :: Parser Double parseDouble = do d <- satisfyMany1 isDigit _ <- satisfy (== '.') f <- satisfyMany1 isDigit return (read (d ++ "." ++ f) :: Double) parseAmount :: Parser Double parseAmount = parseDouble <++ parseIntAsDouble parseDate :: Parser (Int, Int, Int) parseDate = do t1 <- satisfyString isDigit; t2 <- satisfyString isDigit t3 <- satisfyString isDigit; t4 <- satisfyString isDigit _ <- satisfyString (== '-') t5 <- satisfyString isDigit; t6 <- satisfyString isDigit _ <- satisfyString (== '-') t7 <- satisfyString isDigit; t8 <- satisfyString isDigit let y = read (t1 ++ t2 ++ t3 ++ t4) :: Int m = read (t5 ++ t6) :: Int d = read (t7 ++ t8) :: Int if y < 0 then fail "Invalid year" else if m < 1 || m > 12 then fail "Invalid month" else if d < 1 || d > 31 then fail "Invalid day" else return (y, m, d) parseName :: Parser String parseName = satisfyMany1 (\c -> c /= ',' && (not . isSpace) c) parseTags :: Parser [String] parseTags = parseName >>= (\t -> parseTags' >>= (\ts -> return (t:ts))) where parseTags' = do e <- eof if e then return [] else do p <- peek if p == ',' then item >> parseTags else return [] skipSpaces :: Parser () skipSpaces = void $ satisfyMany isSpace skipSpacesWithoutNewline :: Parser () skipSpacesWithoutNewline = void $ satisfyMany (\c -> isSpace c && c /= '\n') skipSpaces1 :: Parser () skipSpaces1 = void $ satisfyMany1 isSpace parseNote :: Parser String parseNote = satisfyMany (/= '\n') parseExpense :: Parser Expense parseExpense = do amount' <- parseAmount ; skipSpaces1 date' <- parseDate ; skipSpaces1 person' <- parseName ; skipSpaces1 shop' <- parseName ; skipSpaces1 tags' <- parseTags ; skipSpacesWithoutNewline note' <- parseNote return Expense { amount = amount', person = person', shop = shop', date = date' , tags = tags', note = note' } parseManyExpenses :: Parser [Expense] parseManyExpenses = eof >>= (\e -> if e then return [] else do ex <- parseExpense; skipSpaces exs <- parseManyExpenses return $ ex:exs)
fredmorcos/attic
projects/pet/archive/pet_haskell_old_2/Parser.hs
isc
5,024
0
14
1,661
2,031
1,052
979
111
4
{-# LANGUAGE OverloadedStrings #-} module Web.Views.DiamondButton where import Data.Text import Text.Blaze.Html5 ((!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A diamondBtn :: H.Attribute -> Text -> H.Html diamondBtn attribute label = H.a ! attribute ! A.class_ "l-square h-m-border m-border r315 black-border f f-row f-center fi-center b-up" $ H.div ! A.class_ "m-square s-arrow f f-row f-center" $ H.div ! A.class_ "f f-col f-center r45" $ H.span ! A.class_ "center" ! A.style "font-size: 1rem;" $ H.toHtml label
tomleb/portfolio
src/Web/Views/DiamondButton.hs
mit
626
0
15
142
150
83
67
12
1
{- CIS-194 (Spring 2013) Source: http://www.cis.upenn.edu/~cis194/spring13/hw/01-intro.pdf -} {-# OPTIONS_GHC -Wall #-} module LogAnalysis where import Log -- Exercise 1 -- Parse a String into a LogMessage parseMessage :: String -> LogMessage parseMessage = parseMessageHelper . words parseMessageHelper :: [String] -> LogMessage parseMessageHelper m = case m of ("I":x:xs) -> LogMessage Info (stringToTS x) (unwords xs) ("W":x:xs) -> LogMessage Warning (stringToTS x) (unwords xs) ("E":c:x:xs) -> LogMessage (Error (read c::Int )) (stringToTS x) (unwords xs) _ -> Unknown (unwords m) -- Converts a string into a TimeStamp stringToTS :: String -> TimeStamp stringToTS str = read str :: TimeStamp parse :: String -> [LogMessage] parse = map parseMessage . lines -- Exercise 2 insert :: LogMessage -> MessageTree -> MessageTree insert (Unknown _) tree = tree insert lm Leaf = Node Leaf lm Leaf insert lm (Node left msg right) = if tsForLog lm < tsForLog msg then Node (insert lm left) msg right else Node left msg (insert lm right) tsForLog :: LogMessage -> TimeStamp tsForLog (Unknown _) = error "Should not happen" tsForLog (LogMessage _ ts _) = ts -- Exercise 3 -- Builds a message tree containing the messages in the list build :: [LogMessage] -> MessageTree {- Start with an empty tree, and 'accumulate' the nodes into the tree-} -- build = foldl (\acc x -> insert x acc) Leaf -- build = foldl (flip insert) Leaf build = foldr insert Leaf -- Exercise 4 inOrder :: MessageTree -> [LogMessage] inOrder Leaf = [] inOrder (Node left msg right) = inOrder left ++ [msg] ++ inOrder right -- Exercise 5 whatWentWrong :: [LogMessage] -> [String] whatWentWrong = map stringFromError . filter isSevereError . inOrder . build stringFromError :: LogMessage -> String stringFromError lm = case lm of (LogMessage _ _ msg) -> msg (Unknown _) -> "" isSevereError :: LogMessage -> Bool isSevereError lm = case lm of (LogMessage (Error num) _ _) -> num >= 0 _ -> False -- Exercise 6 -- I've used this to sort all messages by timestamp -- testParse (inOrder . build . parse) 10000 "error.log"
umairsd/course-haskell-cis194
hw02/LogAnalysis.hs
mit
2,292
0
12
561
631
331
300
40
4
module TestLexer where import Lexer lexTest str = do let ts = alexScanTokens str print $ show ts lt01 = lexTest "myvar = 12 + 13" lt02 = lexTest "myvar = 12 + " lt03 = lexTest "mayvar ^"
blippy/halc
test/TestLexer.hs
mit
199
0
10
51
61
30
31
8
1
{-# LANGUAGE ForeignFunctionInterface #-} module Clingo.Raw.Statistics ( statisticsRoot, statisticsType, -- * Array Access statisticsArraySize, statisticsArrayAt, -- * Map Access statisticsMapSize, statisticsMapSubkeyName, statisticsMapAt, -- * Value Access statisticsValueGet ) where import Control.Monad.IO.Class import Foreign import Foreign.C import Clingo.Raw.Enums import Clingo.Raw.Types foreign import ccall "clingo.h clingo_statistics_root" statisticsRootFFI :: Statistics -> Ptr Word64 -> IO CBool foreign import ccall "clingo.h clingo_statistics_type" statisticsTypeFFI :: Statistics -> Word64 -> Ptr StatisticsType -> IO CBool foreign import ccall "clingo.h clingo_statistics_array_size" statisticsArraySizeFFI :: Statistics -> Word64 -> Ptr Word64 -> IO CBool foreign import ccall "clingo.h clingo_statistics_array_at" statisticsArrayAtFFI :: Statistics -> Word64 -> CSize -> Ptr Word64 -> IO CBool foreign import ccall "clingo.h clingo_statistics_map_size" statisticsMapSizeFFI :: Statistics -> Word64 -> Ptr CSize -> IO CBool foreign import ccall "clingo.h clingo_statistics_map_subkey_name" statisticsMapSubkeyNameFFI :: Statistics -> Word64 -> CSize -> Ptr CString -> IO CBool foreign import ccall "clingo.h clingo_statistics_map_at" statisticsMapAtFFI :: Statistics -> Word64 -> CString -> Ptr Word64 -> IO CBool foreign import ccall "clingo.h clingo_statistics_value_get" statisticsValueGetFFI :: Statistics -> Word64 -> Ptr CDouble -> IO CBool statisticsRoot :: MonadIO m => Statistics -> Ptr Word64 -> m CBool statisticsRoot a b = liftIO $ statisticsRootFFI a b statisticsType :: MonadIO m => Statistics -> Word64 -> Ptr StatisticsType -> m CBool statisticsType a b c = liftIO $ statisticsTypeFFI a b c statisticsArraySize :: MonadIO m => Statistics -> Word64 -> Ptr Word64 -> m CBool statisticsArraySize a b c = liftIO $ statisticsArraySizeFFI a b c statisticsArrayAt :: MonadIO m => Statistics -> Word64 -> CSize -> Ptr Word64 -> m CBool statisticsArrayAt a b c d = liftIO $ statisticsArrayAtFFI a b c d statisticsMapSize :: MonadIO m => Statistics -> Word64 -> Ptr CSize -> m CBool statisticsMapSize a b c = liftIO $ statisticsMapSizeFFI a b c statisticsMapSubkeyName :: MonadIO m => Statistics -> Word64 -> CSize -> Ptr CString -> m CBool statisticsMapSubkeyName a b c d = liftIO $ statisticsMapSubkeyNameFFI a b c d statisticsMapAt :: MonadIO m => Statistics -> Word64 -> CString -> Ptr Word64 -> m CBool statisticsMapAt a b c d = liftIO $ statisticsMapAtFFI a b c d statisticsValueGet :: MonadIO m => Statistics -> Word64 -> Ptr CDouble -> m CBool statisticsValueGet a b c = liftIO $ statisticsValueGetFFI a b c
tsahyt/clingo-haskell
src/Clingo/Raw/Statistics.hs
mit
2,929
0
10
669
752
376
376
57
1
import System clz :: Integral a => a -> [a] clz i | i == 1 = [1] | even i = i:clz (div i 2) | otherwise = i:clz (3*i+1) lenclz i=length $ clz i answer i= maximum [(lenclz i,i)|i<-[1000000,999999..i]] main = do args <- getArgs print $ answer $ read (head args)
yuto-matsum/contest-util-hs
src/Euler/014.hs
mit
287
0
10
81
184
90
94
10
1
{-# htermination (fromRationalFloat :: Ratio Integer -> Float) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Float = Float MyInt MyInt ; data Integer = Integer MyInt ; data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ratio a = CnPc a a; rationalToFloat :: Ratio Integer -> Float; rationalToFloat (CnPc (Integer x) (Integer y)) = Float x y; primRationalToFloat :: Ratio Integer -> Float; primRationalToFloat = rationalToFloat; fromRationalFloat :: Ratio Integer -> Float fromRationalFloat = primRationalToFloat;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/fromRational_2.hs
mit
605
0
9
120
184
105
79
14
1
{-# LANGUAGE UnicodeSyntax #-} module Main ( main ) where import Data.Peano ( PeanoNat ) import Test.QuickCheck ( (==>), Property, quickCheck ) -- From: -- https://downloads.haskell.org/~ghc/7.8.4/docs/html/libraries/base-4.7.0.2/Prelude.html#v:signum prop_signum ∷ PeanoNat → Bool prop_signum x = abs x * signum x == x -- In non-negative integers @div@ and @quot@ should be have the same -- behaviour. prop_div_quot ∷ PeanoNat → PeanoNat → Property prop_div_quot n d = n >= 0 && d > 0 ==> n `div` d == n `quot` d main ∷ IO () main = do quickCheck prop_signum quickCheck prop_div_quot
asr/peano
test/Main.hs
mit
611
0
11
106
155
86
69
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Devil.Config (loadConfig) where import Control.Applicative import Control.Monad import qualified Data.Map.Strict as M import Data.Yaml import Devil.Types instance FromJSON Config where parseJSON (Object v) = Config <$> v .: "path" <*> v .: "enabled" <*> fmap (maybe M.empty id) (v .:? "config") parseJSON _ = mzero instance FromJSON DaemonGlobal where parseJSON (Object v) = DaemonGlobal <$> v .: "name" <*> fmap (maybe M.empty id) (v .:? "config") parseJSON _ = mzero instance FromJSON DaemonLocal where parseJSON (Object v) = DaemonLocal <$> v .: "entry_point" parseJSON _ = mzero loadConfig :: FilePath -> IO (Either ParseException Config) loadConfig = decodeFileEither
EXio4/devil
src/Devil/Config.hs
mit
863
0
10
251
240
127
113
24
1
-- Prize Draw -- http://www.codewars.com/kata/5616868c81a0f281e500005c/ module Codewars.G964.Rank where import Data.List (sortBy) import Data.Char (toUpper, ord) import Data.List.Split (split, dropDelims, oneOf) rank :: String -> [Int] -> Int -> String rank "" _ _ = "No participants" rank st we n = if length pAndR < n then "Not enough participants" else fst . (!!(n-1)) . sortBy cmp $ pAndR where pAndR = zipWith (\w name -> (name, w * (length name + (sum . map (\c -> (ord . toUpper $ c) - ord 'A' + 1) $ name)))) we . split (dropDelims $ oneOf ",") $ st cmp (name1, rank1) (name2, rank2) = case compare rank2 rank1 of EQ -> compare name1 name2 o1 -> o1
gafiatulin/codewars
src/6 kyu/Rank.hs
mit
702
0
26
162
289
158
131
11
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Toaster.Http.Core where import Toaster.Http.Prelude import Data.ByteString import qualified Data.ByteString.Char8 as C8 import Data.Maybe import Data.Pool import Database.PostgreSQL.Simple import Database.Migrate import Database.Migrate.Migration.FileStandard import System.Posix.Env data Hole = Hole connectInfo :: ConnectInfo connectInfo = ConnectInfo { connectHost = "localhost" , connectPort = 5432 , connectUser = "toaster" , connectPassword = "password" , connectDatabase = "toasterdb" } mkpool :: IO (Pool Connection) mkpool = createPool (connect connectInfo) -- open action close -- close action 1 -- stripes 20 -- max keep alive (s) 10 -- max connections migrations :: [Migration] migrations = [ migration "20140324" "initial" ] runmigrate :: Pool Connection -> IO () runmigrate pool = withResource pool $ \c -> withTransaction c $ migrate "toaster" c "config/db" migrations
nhibberd/toaster
src/Toaster/Http/Core.hs
mit
1,337
0
8
504
227
134
93
36
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Package -- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GNU-GPL -- -- Maintainer : <maintainer at leksah.org> -- Stability : provisional -- Portability : portable -- -- -- | The packages methods of ide. -- --------------------------------------------------------------------------------- module IDE.Package ( packageConfig , packageConfig' , buildPackage , packageDoc , packageDoc' , packageClean , packageClean' , packageCopy , packageCopy' , packageRun , packageRunJavaScript , activatePackage , deactivatePackage , packageInstallDependencies , packageRegister , packageRegister' , packageTest , packageTest' , packageBench , packageBench' , packageSdist , packageOpenDoc , getPackageDescriptionAndPath , getEmptyModuleTemplate , getModuleTemplate , ModuleLocation(..) , addModuleToPackageDescr , delModuleFromPackageDescr , backgroundBuildToggled , runUnitTestsToggled , makeModeToggled , debugStart , printBindResultFlag , breakOnErrorFlag , breakOnExceptionFlag , printEvldWithShowFlag , tryDebug , tryDebugQuiet , executeDebugCommand , choosePackageFile , idePackageFromPath , refreshPackage ) where import Distribution.Package hiding (depends,packageId) import Distribution.PackageDescription import Distribution.PackageDescription.Parse import Distribution.PackageDescription.Configuration import Distribution.Verbosity import System.FilePath import Control.Concurrent import System.Directory (canonicalizePath, setCurrentDirectory, doesFileExist, getDirectoryContents, doesDirectoryExist) import Prelude hiding (catch) import Data.Char (isSpace) import Data.Maybe (mapMaybe, listToMaybe, fromMaybe, isNothing, isJust, fromJust, catMaybes) import Control.Exception (SomeException(..), catch) import IDE.Core.State import IDE.Utils.GUIUtils import IDE.Pane.Log import IDE.Pane.PackageEditor import IDE.Pane.SourceBuffer import IDE.Pane.PackageFlags (writeFlags, readFlags) import Distribution.Text (display) import IDE.Utils.FileUtils(getConfigFilePathForLoad) import IDE.LogRef import Distribution.ModuleName (ModuleName(..)) import Data.List (isInfixOf, nub, foldl', delete, find) import IDE.Utils.Tool (ToolOutput(..), runTool, newGhci, ToolState(..), toolline, ProcessHandle, executeGhciCommand) import qualified Data.Set as Set (fromList) import qualified Data.Map as Map (empty, fromList) import System.Exit (ExitCode(..)) import Control.Applicative ((<$>), (<*>)) import qualified Data.Conduit as C (Sink, ZipSink(..), getZipSink) import qualified Data.Conduit.List as CL (foldM, fold, consume) import Data.Conduit (($$)) import Control.Monad.Trans.Reader (ask) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Trans.Class (lift) import Control.Monad (void, when, unless, liftM, forM, forM_) import Distribution.PackageDescription.PrettyPrint (writeGenericPackageDescription) import Debug.Trace (trace) import IDE.Pane.WebKit.Documentation (getDocumentation, loadDoc, reloadDoc) import IDE.Pane.WebKit.Output (loadOutputUri, getOutputPane) import System.Log.Logger (debugM) import System.Process.Vado (getMountPoint, vado, readSettings) import qualified Data.Text as T (lines, isPrefixOf, stripPrefix, replace, unwords, takeWhile, pack, unpack, isInfixOf) import IDE.Utils.ExternalTool (runExternalTool', runExternalTool, isRunning, interruptBuild) import Text.PrinterParser (writeFields) import Data.Text (Text) import Data.Monoid ((<>)) import qualified Data.Text.IO as T (readFile) import qualified Text.Printf as S (printf) import Text.Printf (PrintfType) import IDE.Metainfo.Provider (updateSystemInfo) import GI.GLib.Functions (timeoutAdd) import GI.GLib.Constants (pattern PRIORITY_DEFAULT) import GI.Gtk.Objects.MessageDialog (setMessageDialogText, constructMessageDialogButtons, setMessageDialogMessageType, MessageDialog(..)) import GI.Gtk.Objects.Dialog (constructDialogUseHeaderBar) import GI.Gtk.Enums (WindowPosition(..), ResponseType(..), ButtonsType(..), MessageType(..)) import GI.Gtk.Objects.Window (setWindowWindowPosition, windowSetTransientFor) import Graphics.UI.Editor.Parameters (dialogRun', dialogSetDefaultResponse', dialogAddButton') import Data.GI.Base (set, new') import GI.Gtk.Objects.Widget (widgetDestroy) printf :: PrintfType r => Text -> r printf = S.printf . T.unpack -- | Get the last item sinkLast = CL.fold (\_ a -> Just a) Nothing moduleInfo :: (a -> BuildInfo) -> (a -> [ModuleName]) -> a -> [(ModuleName, BuildInfo)] moduleInfo bi mods a = map (\m -> (m, buildInfo)) $ mods a where buildInfo = bi a myLibModules pd = case library pd of Nothing -> [] Just l -> moduleInfo libBuildInfo libModules l myExeModules pd = concatMap (moduleInfo buildInfo exeModules) (executables pd) myTestModules pd = concatMap (moduleInfo testBuildInfo (otherModules . testBuildInfo)) (testSuites pd) myBenchmarkModules pd = concatMap (moduleInfo benchmarkBuildInfo (otherModules . benchmarkBuildInfo)) (benchmarks pd) activatePackage :: Maybe FilePath -> Maybe IDEPackage -> Maybe Text -> IDEM () activatePackage mbPath mbPack mbExe = do liftIO $ debugM "leksah" "activatePackage" oldActivePack <- readIDE activePack modifyIDE_ (\ide -> ide{activePack = mbPack, activeExe = mbExe}) case mbPath of Just p -> liftIO $ setCurrentDirectory (dropFileName p) Nothing -> return () when (isJust mbPack || isJust oldActivePack) $ do triggerEventIDE (Sensitivity [(SensitivityProjectActive,isJust mbPack)]) return () mbWs <- readIDE workspace let wsStr = case mbWs of Nothing -> "" Just ws -> wsName ws txt = case (mbPath, mbPack) of (_, Just pack) -> wsStr <> " > " <> packageIdentifierToString (ipdPackageId pack) (Just path, _) -> wsStr <> " > " <> T.pack (takeFileName path) _ -> wsStr <> ":" triggerEventIDE (StatusbarChanged [CompartmentPackage txt]) return () deactivatePackage :: IDEAction deactivatePackage = activatePackage Nothing Nothing Nothing interruptSaveAndRun :: MonadIDE m => IDEAction -> m () interruptSaveAndRun action = do ideR <- liftIDE ask alreadyRunning <- isRunning if alreadyRunning then do liftIO $ debugM "leksah" "interruptSaveAndRun" interruptBuild timeoutAdd PRIORITY_DEFAULT 200 (do reflectIDE (do interruptSaveAndRun action return False) ideR return False) return () else liftIDE run where run = do prefs <- readIDE prefs when (saveAllBeforeBuild prefs) . liftIDE . void $ fileSaveAll belongsToWorkspace' action packageConfig :: PackageAction packageConfig = do package <- ask interruptSaveAndRun $ packageConfig' package (\ _ -> return ()) packageConfig' :: IDEPackage -> (Bool -> IDEAction) -> IDEAction packageConfig' package continuation = do prefs <- readIDE prefs let dir = ipdPackageDir package useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" if useStack then do ideMessage Normal (__ "Leksah is not running \"cabal configure\" because a stack.yaml file was found.") continuation True else do logLaunch <- getDefaultLogLaunch showDefaultLogLaunch' runExternalTool' (__ "Configuring") (cabalCommand prefs) ("configure" : ipdConfigFlags package) dir $ do mbLastOutput <- C.getZipSink $ const <$> C.ZipSink sinkLast <*> C.ZipSink (logOutput logLaunch) lift $ do mbPack <- idePackageFromPath (logOutput logLaunch) (ipdCabalFile package) case mbPack of Just pack -> do changePackage pack triggerEventIDE $ WorkspaceChanged False True continuation (mbLastOutput == Just (ToolExit ExitSuccess)) return () Nothing -> do postAsyncIDE $ ideMessage Normal (__ "Can't read package file") continuation False return() runCabalBuild :: Bool -> Bool -> Bool -> IDEPackage -> Bool -> (Bool -> IDEAction) -> IDEAction runCabalBuild backgroundBuild jumpToWarnings withoutLinking package shallConfigure continuation = do prefs <- readIDE prefs let dir = ipdPackageDir package useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" -- if we use stack, with tests enabled, we build the tests without running them let stackFlagsForTests = if useStack then if "--enable-tests" `elem` ipdConfigFlags package then ["--test", "--no-run-tests"] else [] else [] -- if we use stack, with benchmarks enabled, we build the benchmarks without running them let stackFlagsForBenchmarks = if useStack then if "--enable-benchmarks" `elem` ipdConfigFlags package then ["--bench", "--no-run-benchmarks"] else [] else [] let stackFlags = stackFlagsForTests ++ stackFlagsForBenchmarks let args = ["build"] -- stack needs the package name to actually print the output info ++ (if useStack then [ipdPackageName package] else []) ++ ["--with-ld=false" | not useStack && backgroundBuild && withoutLinking] ++ stackFlags ++ ipdBuildFlags package runExternalTool' (__ "Building") (if useStack then "stack" else cabalCommand prefs) args dir $ do (mbLastOutput, isConfigErr, _) <- C.getZipSink $ (,,) <$> C.ZipSink sinkLast <*> C.ZipSink isConfigError <*> (C.ZipSink $ logOutputForBuild package backgroundBuild jumpToWarnings) lift $ do errs <- readIDE errorRefs if shallConfigure && isConfigErr then packageConfig' package (\ b -> when b $ runCabalBuild backgroundBuild jumpToWarnings withoutLinking package False continuation) else do continuation (mbLastOutput == Just (ToolExit ExitSuccess)) return () isConfigError :: Monad m => C.Sink ToolOutput m Bool isConfigError = CL.foldM (\a b -> return $ a || isCErr b) False where isCErr (ToolError str) = str1 `T.isInfixOf` str || str2 `T.isInfixOf` str || str3 `T.isInfixOf` str isCErr _ = False str1 = __ "Run the 'configure' command first" str2 = __ "please re-configure" str3 = __ "cannot satisfy -package-id" buildPackage :: Bool -> Bool -> Bool -> IDEPackage -> (Bool -> IDEAction) -> IDEAction buildPackage backgroundBuild jumpToWarnings withoutLinking package continuation = catchIDE (do ideR <- ask prefs <- readIDE prefs maybeDebug <- readIDE debugState case maybeDebug of Nothing -> do alreadyRunning <- isRunning if alreadyRunning then do liftIO $ debugM "leksah" "buildPackage interruptBuild" interruptBuild unless backgroundBuild $ do timeoutAdd PRIORITY_DEFAULT 100 (do reflectIDE (do buildPackage backgroundBuild jumpToWarnings withoutLinking package continuation return False) ideR return False) return () else do when (saveAllBeforeBuild prefs) . liftIDE . void $ fileSaveAll belongsToWorkspace' runCabalBuild backgroundBuild jumpToWarnings withoutLinking package True $ \f -> do when f $ do mbURI <- readIDE autoURI case mbURI of Just uri -> postSyncIDE . loadOutputUri $ T.unpack uri Nothing -> return () continuation f Just debug@(_, ghci) -> do -- TODO check debug package matches active package ready <- liftIO $ isEmptyMVar (currentToolCommand ghci) when ready $ do let dir = ipdPackageDir package when (saveAllBeforeBuild prefs) (do fileSaveAll belongsToWorkspace'; return ()) (`runDebug` debug) . executeDebugCommand ":reload" $ do errs <- logOutputForBuild package backgroundBuild jumpToWarnings unless (any isError errs) . lift $ do cmd <- readIDE autoCommand postSyncIDE cmd continuation True ) (\(e :: SomeException) -> sysMessage Normal (T.pack $ show e)) packageDoc :: PackageAction packageDoc = do package <- ask interruptSaveAndRun $ packageDoc' False True package (\ _ -> return ()) packageDoc' :: Bool -> Bool -> IDEPackage -> (Bool -> IDEAction) -> IDEAction packageDoc' backgroundBuild jumpToWarnings package continuation = do prefs <- readIDE prefs catchIDE (do let dir = ipdPackageDir package useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" runExternalTool' (__ "Documenting") (if useStack then "stack" else cabalCommand prefs) ("haddock" : ipdHaddockFlags package) dir $ do mbLastOutput <- C.getZipSink $ const <$> C.ZipSink sinkLast <*> (C.ZipSink $ logOutputForBuild package backgroundBuild jumpToWarnings) lift $ postAsyncIDE reloadDoc lift $ continuation (mbLastOutput == Just (ToolExit ExitSuccess))) (\(e :: SomeException) -> print e) packageClean :: PackageAction packageClean = do package <- ask interruptSaveAndRun $ packageClean' package (\ _ -> return ()) packageClean' :: IDEPackage -> (Bool -> IDEAction) -> IDEAction packageClean' package continuation = do prefs <- readIDE prefs logLaunch <- getDefaultLogLaunch showDefaultLogLaunch' let dir = ipdPackageDir package useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" runExternalTool' (__ "Cleaning") (if useStack then "stack" else cabalCommand prefs) ["clean"] dir $ do mbLastOutput <- C.getZipSink $ const <$> C.ZipSink sinkLast <*> C.ZipSink (logOutput logLaunch) lift $ continuation (mbLastOutput == Just (ToolExit ExitSuccess)) packageCopy :: PackageAction packageCopy = do package <- ask interruptSaveAndRun $ do logLaunch <- getDefaultLogLaunch showDefaultLogLaunch' catchIDE (do prefs <- readIDE prefs window <- getMainWindow mbDir <- liftIO $ chooseDir window (__ "Select the target directory") Nothing case mbDir of Nothing -> return () Just fp -> do let dir = ipdPackageDir package runExternalTool' (__ "Copying") (cabalCommand prefs) ["copy", "--destdir=" <> T.pack fp] dir (logOutput logLaunch)) (\(e :: SomeException) -> print e) packageInstallDependencies :: PackageAction packageInstallDependencies = do package <- ask ideR <- liftIDE ask interruptSaveAndRun $ do logLaunch <- getDefaultLogLaunch showDefaultLogLaunch' catchIDE (do prefs <- readIDE prefs let dir = ipdPackageDir package runExternalTool' (__ "Installing") (cabalCommand prefs) ( (if useCabalDev prefs then ["install-deps"] else ["install","--only-dependencies"]) ++ ipdConfigFlags package ++ ipdInstallFlags package) dir $ do logOutput logLaunch lift $ postSyncIDE updateSystemInfo) (\(e :: SomeException) -> print e) packageCopy' :: IDEPackage -> (Bool -> IDEAction) -> IDEAction packageCopy' package continuation = do prefs <- readIDE prefs logLaunch <- getDefaultLogLaunch showDefaultLogLaunch' catchIDE (do let dir = ipdPackageDir package useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" runExternalTool' (__ "Installing") (if useStack then "stack" else "echo" {-cabalCommand prefs-}) ((if useStack then "install" : ipdBuildFlags package else ["TODO run cabal new-install"]) ++ ipdInstallFlags package) dir $ do mbLastOutput <- C.getZipSink $ (const <$> C.ZipSink sinkLast) <*> C.ZipSink (logOutput logLaunch) lift $ continuation (mbLastOutput == Just (ToolExit ExitSuccess))) (\(e :: SomeException) -> print e) packageRun :: PackageAction packageRun = ask >>= (interruptSaveAndRun . packageRun' True) packageRun' :: Bool -> IDEPackage -> IDEAction packageRun' removeGhcjsFlagIfPresent package = if removeGhcjsFlagIfPresent && "--ghcjs" `elem` ipdConfigFlags package then do window <- liftIDE getMainWindow md <- new' MessageDialog [ constructDialogUseHeaderBar 0, constructMessageDialogButtons ButtonsTypeCancel] setMessageDialogMessageType md MessageTypeQuestion setMessageDialogText md $ __ "Package is configured to use GHCJS. Would you like to remove --ghcjs from the configure flags and rebuild?" windowSetTransientFor md (Just window) dialogAddButton' md (__ "Use _GHC") (AnotherResponseType 1) dialogSetDefaultResponse' md (AnotherResponseType 1) setWindowWindowPosition md WindowPositionCenterOnParent resp <- dialogRun' md widgetDestroy md case resp of AnotherResponseType 1 -> do let packWithNewFlags = package { ipdConfigFlags = filter (/="--ghcjs") $ ipdConfigFlags package } changePackage packWithNewFlags liftIO $ writeFlags (dropExtension (ipdCabalFile packWithNewFlags) ++ leksahFlagFileExtension) packWithNewFlags packageConfig' packWithNewFlags $ \ ok -> when ok $ packageRun' False packWithNewFlags _ -> return () else liftIDE $ catchIDE (do ideR <- ask maybeDebug <- readIDE debugState pd <- liftIO $ fmap flattenPackageDescription (readPackageDescription normal (ipdCabalFile package)) mbExe <- readIDE activeExe let exe = exeToRun mbExe $ executables pd let defaultLogName = T.pack . display . pkgName $ ipdPackageId package logName = fromMaybe defaultLogName . listToMaybe $ map (T.pack . exeName) exe (logLaunch,logName) <- buildLogLaunchByName logName showLog case maybeDebug of Nothing -> do prefs <- readIDE prefs let dir = ipdPackageDir package useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" IDE.Package.runPackage (addLogLaunchData logName logLaunch) (T.pack $ printf (__ "Running %s") (T.unpack logName)) (if useStack then "stack" else cabalCommand prefs) (concat [[if useStack then "exec" else "run"] , ipdBuildFlags package , map (T.pack . exeName) exe , ["--"] , ipdExeFlags package]) dir (logOutput logLaunch) Just debug -> -- TODO check debug package matches active package runDebug (do case exe of [Executable name mainFilePath _] -> executeDebugCommand (":module *" <> T.pack (map (\c -> if c == '/' then '.' else c) (takeWhile (/= '.') mainFilePath))) (logOutput logLaunch) _ -> return () executeDebugCommand (":main " <> T.unwords (ipdExeFlags package)) (logOutput logLaunch)) debug) (\(e :: SomeException) -> print e) -- | Is the given executable the active one? isActiveExe :: Text -> Executable -> Bool isActiveExe selected (Executable name _ _) = selected == T.pack name -- | get executable to run -- no exe activated, take first one exeToRun :: Maybe Text -> [Executable] -> [Executable] exeToRun Nothing (exe:_) = [exe] exeToRun Nothing _ = [] exeToRun (Just selected) exes = take 1 $ filter (isActiveExe selected) exes packageRunJavaScript :: PackageAction packageRunJavaScript = ask >>= (interruptSaveAndRun . packageRunJavaScript' True) packageRunJavaScript' :: Bool -> IDEPackage -> IDEAction packageRunJavaScript' addFlagIfMissing package = if addFlagIfMissing && ("--ghcjs" `notElem` ipdConfigFlags package) then do window <- liftIDE getMainWindow md <- new' MessageDialog [ constructDialogUseHeaderBar 0, constructMessageDialogButtons ButtonsTypeCancel] setMessageDialogMessageType md MessageTypeQuestion setMessageDialogText md $ __ "Package is not configured to use GHCJS. Would you like to add --ghcjs to the configure flags and rebuild?" windowSetTransientFor md (Just window) dialogAddButton' md (__ "Use _GHCJS") (AnotherResponseType 1) dialogSetDefaultResponse' md (AnotherResponseType 1) setWindowWindowPosition md WindowPositionCenterOnParent resp <- dialogRun' md widgetDestroy md case resp of AnotherResponseType 1 -> do let packWithNewFlags = package { ipdConfigFlags = "--ghcjs" : ipdConfigFlags package } changePackage packWithNewFlags liftIO $ writeFlags (dropExtension (ipdCabalFile packWithNewFlags) ++ leksahFlagFileExtension) packWithNewFlags packageConfig' packWithNewFlags $ \ ok -> when ok $ packageRunJavaScript' False packWithNewFlags _ -> return () else liftIDE $ buildPackage False False True package $ \ ok -> when ok $ liftIDE $ catchIDE (do ideR <- ask maybeDebug <- readIDE debugState pd <- liftIO $ fmap flattenPackageDescription (readPackageDescription normal (ipdCabalFile package)) mbExe <- readIDE activeExe let exe = exeToRun mbExe $ executables pd let defaultLogName = T.pack . display . pkgName $ ipdPackageId package logName = fromMaybe defaultLogName . listToMaybe $ map (T.pack . exeName) exe (logLaunch,logName) <- buildLogLaunchByName logName let dir = ipdPackageDir package prefs <- readIDE prefs case exe ++ executables pd of (Executable name _ _ : _) -> liftIDE $ do let path = "dist/build" </> name </> name <.> "jsexe" </> "index.html" dir = ipdPackageDir package postAsyncIDE $ do loadOutputUri ("file:///" ++ dir </> path) getOutputPane Nothing >>= \ p -> displayPane p False `catchIDE` (\(e :: SomeException) -> print e) _ -> return ()) (\(e :: SomeException) -> print e) packageRegister :: PackageAction packageRegister = do package <- ask interruptSaveAndRun $ packageRegister' package (\ _ -> return ()) packageRegister' :: IDEPackage -> (Bool -> IDEAction) -> IDEAction packageRegister' package continuation = if ipdHasLibs package then do logLaunch <- getDefaultLogLaunch showDefaultLogLaunch' catchIDE (do prefs <- readIDE prefs let dir = ipdPackageDir package useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" if useStack then continuation True else runExternalTool' (__ "Registering") (cabalCommand prefs) ("register" : ipdRegisterFlags package) dir $ do mbLastOutput <- C.getZipSink $ (const <$> C.ZipSink sinkLast) <*> C.ZipSink (logOutput logLaunch) lift $ continuation (mbLastOutput == Just (ToolExit ExitSuccess))) (\(e :: SomeException) -> print e) else continuation True packageTest :: PackageAction packageTest = do package <- ask interruptSaveAndRun $ packageTest' False True package True (\ _ -> return ()) packageTest' :: Bool -> Bool -> IDEPackage -> Bool -> (Bool -> IDEAction) -> IDEAction packageTest' backgroundBuild jumpToWarnings package shallConfigure continuation = do let dir = ipdPackageDir package useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" if "--enable-tests" `elem` ipdConfigFlags package then do logLaunch <- getDefaultLogLaunch showDefaultLogLaunch' catchIDE (do prefs <- readIDE prefs removeTestLogRefs dir let cmd=if useStack then "stack" else cabalCommand prefs let args=if useStack then ["test"] else ["test", "--with-ghc=leksahtrue"] runExternalTool' (__ "Testing") cmd (args ++ ipdBuildFlags package ++ ipdTestFlags package) dir $ do (mbLastOutput, isConfigErr, _) <- C.getZipSink $ (,,) <$> C.ZipSink sinkLast <*> C.ZipSink isConfigError <*> (C.ZipSink $ logOutputForBuild package backgroundBuild jumpToWarnings) lift $ do errs <- readIDE errorRefs if shallConfigure && isConfigErr then packageConfig' package (\ b -> when b $ packageTest' backgroundBuild jumpToWarnings package shallConfigure continuation) else do continuation (mbLastOutput == Just (ToolExit ExitSuccess)) return ()) (\(e :: SomeException) -> print e) else continuation True -- | Run benchmarks as foreground action for current package packageBench :: PackageAction packageBench = do package <- ask interruptSaveAndRun $ packageBench' False True package True (\ _ -> return ()) -- | Run benchmarks packageBench' :: Bool -> Bool -> IDEPackage -> Bool -> (Bool -> IDEAction) -> IDEAction packageBench' backgroundBuild jumpToWarnings package shallConfigure continuation = do let dir = ipdPackageDir package useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" if "--enable-benchmarks" `elem` ipdConfigFlags package then do logLaunch <- getDefaultLogLaunch showDefaultLogLaunch' catchIDE (do prefs <- readIDE prefs let cmd=if useStack then "stack" else cabalCommand prefs let args=if useStack then ["bench"] else ["bench", "--with-ghc=leksahtrue"] runExternalTool' (__ "Benchmarking") cmd (args ++ ipdBuildFlags package ++ ipdBenchmarkFlags package) dir $ do (mbLastOutput, isConfigErr, _) <- C.getZipSink $ (,,) <$> C.ZipSink sinkLast <*> C.ZipSink isConfigError <*> (C.ZipSink $ logOutputForBuild package backgroundBuild jumpToWarnings) lift $ do errs <- readIDE errorRefs if shallConfigure && isConfigErr then packageConfig' package (\ b -> when b $ packageBench' backgroundBuild jumpToWarnings package shallConfigure continuation) else do continuation (mbLastOutput == Just (ToolExit ExitSuccess)) return ()) (\(e :: SomeException) -> print e) else continuation True packageSdist :: PackageAction packageSdist = do package <- ask interruptSaveAndRun $ do logLaunch <- getDefaultLogLaunch showDefaultLogLaunch' catchIDE (do prefs <- readIDE prefs let dir = ipdPackageDir package runExternalTool' (__ "Source Dist") (cabalCommand prefs) ("sdist" : ipdSdistFlags package) dir (logOutput logLaunch)) (\(e :: SomeException) -> print e) -- | Open generated documentation for package packageOpenDoc :: PackageAction packageOpenDoc = do package <- ask let dir = ipdPackageDir package useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" distDir <- if useStack then do --ask stack where its dist directory is mvar <- liftIO newEmptyMVar runExternalTool' "" "stack" ["path"] dir $ do output <- CL.consume liftIO . putMVar mvar $ head $ catMaybes $ map getDistOutput output liftIO $ takeMVar mvar else return "dist" liftIDE $ do prefs <- readIDE prefs let path = dir </> distDir </> "doc/html" </> display (pkgName (ipdPackageId package)) </> "index.html" loadDoc . T.pack $ "file://" ++ path getDocumentation Nothing >>= \ p -> displayPane p False `catchIDE` (\(e :: SomeException) -> print e) where -- get dist directory from stack path output getDistOutput (ToolOutput o) | Just t<-T.stripPrefix "dist-dir:" o = Just $ dropWhile isSpace $ T.unpack t getDistOutput _ = Nothing runPackage :: (ProcessHandle -> IDEAction) -> Text -> FilePath -> [Text] -> FilePath -> C.Sink ToolOutput IDEM () -> IDEAction runPackage = runExternalTool (return True) -- TODO here one could check if package to be run is building/configuring/etc atm -- --------------------------------------------------------------------- -- | * Utility functions/procedures, that have to do with packages -- getPackageDescriptionAndPath :: IDEM (Maybe (PackageDescription,FilePath)) getPackageDescriptionAndPath = do active <- readIDE activePack case active of Nothing -> do ideMessage Normal (__ "No active package") return Nothing Just p -> do ideR <- ask reifyIDE (\ideR -> catch (do pd <- readPackageDescription normal (ipdCabalFile p) return (Just (flattenPackageDescription pd,ipdCabalFile p))) (\(e :: SomeException) -> do reflectIDE (ideMessage Normal (__ "Can't load package " <> T.pack (show e))) ideR return Nothing)) getEmptyModuleTemplate :: PackageDescription -> Text -> IO Text getEmptyModuleTemplate pd modName = getModuleTemplate "module" pd modName "" "" getModuleTemplate :: FilePath -> PackageDescription -> Text -> Text -> Text -> IO Text getModuleTemplate templateName pd modName exports body = catch (do dataDir <- getDataDir filePath <- getConfigFilePathForLoad (templateName <> leksahTemplateFileExtension) Nothing dataDir template <- T.readFile filePath return (foldl' (\ a (from, to) -> T.replace from to a) template [ ("@License@" , (T.pack . display . license) pd) , ("@Maintainer@" , T.pack $ maintainer pd) , ("@Stability@" , T.pack $ stability pd) , ("@Portability@" , "") , ("@Copyright@" , T.pack $ copyright pd) , ("@ModuleName@" , modName) , ("@ModuleExports@", exports) , ("@ModuleBody@" , body)])) (\ (e :: SomeException) -> do sysMessage Normal . T.pack $ printf (__ "Couldn't read template file: %s") (show e) return "") data ModuleLocation = LibExposedMod | LibOtherMod | ExeOrTestMod Text addModuleToPackageDescr :: ModuleName -> [ModuleLocation] -> PackageAction addModuleToPackageDescr moduleName locations = do p <- ask liftIDE $ reifyIDE (\ideR -> catch (do gpd <- readPackageDescription normal (ipdCabalFile p) let npd = trace (show gpd) foldr addModule gpd locations writeGenericPackageDescription (ipdCabalFile p) npd) (\(e :: SomeException) -> do reflectIDE (ideMessage Normal (__ "Can't update package " <> T.pack (show e))) ideR return ())) where addModule LibExposedMod gpd@GenericPackageDescription{condLibrary = Just lib} = gpd {condLibrary = Just (addModToLib moduleName lib)} addModule LibOtherMod gpd@GenericPackageDescription{condLibrary = Just lib} = gpd {condLibrary = Just (addModToBuildInfoLib moduleName lib)} addModule (ExeOrTestMod name') gpd = let name = T.unpack name' in gpd { condExecutables = map (addModToBuildInfoExe name moduleName) (condExecutables gpd) , condTestSuites = map (addModToBuildInfoTest name moduleName) (condTestSuites gpd) } addModule _ x = x addModToLib :: ModuleName -> CondTree ConfVar [Dependency] Library -> CondTree ConfVar [Dependency] Library addModToLib modName ct@CondNode{condTreeData = lib} = ct{condTreeData = lib{exposedModules = modName `inOrderAdd` exposedModules lib}} addModToBuildInfoLib :: ModuleName -> CondTree ConfVar [Dependency] Library -> CondTree ConfVar [Dependency] Library addModToBuildInfoLib modName ct@CondNode{condTreeData = lib} = ct{condTreeData = lib{libBuildInfo = (libBuildInfo lib){otherModules = modName `inOrderAdd` otherModules (libBuildInfo lib)}}} addModToBuildInfoExe :: String -> ModuleName -> (String, CondTree ConfVar [Dependency] Executable) -> (String, CondTree ConfVar [Dependency] Executable) addModToBuildInfoExe name modName (str,ct@CondNode{condTreeData = exe}) | str == name = (str, ct{condTreeData = exe{buildInfo = (buildInfo exe){otherModules = modName `inOrderAdd` otherModules (buildInfo exe)}}}) addModToBuildInfoExe name _ x = x addModToBuildInfoTest :: String -> ModuleName -> (String, CondTree ConfVar [Dependency] TestSuite) -> (String, CondTree ConfVar [Dependency] TestSuite) addModToBuildInfoTest name modName (str,ct@CondNode{condTreeData = test}) | str == name = (str, ct{condTreeData = test{testBuildInfo = (testBuildInfo test){otherModules = modName `inOrderAdd` otherModules (testBuildInfo test)}}}) addModToBuildInfoTest _ _ x = x inOrderAdd :: Ord a => a -> [a] -> [a] inOrderAdd a list = let (before, after) = span (< a) list in before ++ [a] ++ after -------------------------------------------------------------------------- delModuleFromPackageDescr :: ModuleName -> PackageAction delModuleFromPackageDescr moduleName = do p <- ask liftIDE $ reifyIDE (\ideR -> catch (do gpd <- readPackageDescription normal (ipdCabalFile p) let isExposedAndJust = isExposedModule moduleName (condLibrary gpd) let npd = if isExposedAndJust then gpd{ condLibrary = Just (delModFromLib moduleName (fromJust (condLibrary gpd))), condExecutables = map (delModFromBuildInfoExe moduleName) (condExecutables gpd)} else gpd{ condLibrary = case condLibrary gpd of Nothing -> Nothing Just lib -> Just (delModFromBuildInfoLib moduleName (fromJust (condLibrary gpd))), condExecutables = map (delModFromBuildInfoExe moduleName) (condExecutables gpd)} writeGenericPackageDescription (ipdCabalFile p) npd) (\(e :: SomeException) -> do reflectIDE (ideMessage Normal (__ "Can't update package " <> T.pack (show e))) ideR return ())) delModFromLib :: ModuleName -> CondTree ConfVar [Dependency] Library -> CondTree ConfVar [Dependency] Library delModFromLib modName ct@CondNode{condTreeData = lib} = ct{condTreeData = lib{exposedModules = delete modName (exposedModules lib)}} delModFromBuildInfoLib :: ModuleName -> CondTree ConfVar [Dependency] Library -> CondTree ConfVar [Dependency] Library delModFromBuildInfoLib modName ct@CondNode{condTreeData = lib} = ct{condTreeData = lib{libBuildInfo = (libBuildInfo lib){otherModules = delete modName (otherModules (libBuildInfo lib))}}} delModFromBuildInfoExe :: ModuleName -> (String, CondTree ConfVar [Dependency] Executable) -> (String, CondTree ConfVar [Dependency] Executable) delModFromBuildInfoExe modName (str,ct@CondNode{condTreeData = exe}) = (str, ct{condTreeData = exe{buildInfo = (buildInfo exe){otherModules = delete modName (otherModules (buildInfo exe))}}}) isExposedModule :: ModuleName -> Maybe (CondTree ConfVar [Dependency] Library) -> Bool isExposedModule mn Nothing = False isExposedModule mn (Just CondNode{condTreeData = lib}) = mn `elem` exposedModules lib backgroundBuildToggled :: IDEAction backgroundBuildToggled = do toggled <- getBackgroundBuildToggled modifyIDE_ (\ide -> ide{prefs = (prefs ide){backgroundBuild= toggled}}) runUnitTestsToggled :: IDEAction runUnitTestsToggled = do toggled <- getRunUnitTests modifyIDE_ (\ide -> ide{prefs = (prefs ide){runUnitTests= toggled}}) makeModeToggled :: IDEAction makeModeToggled = do toggled <- getMakeModeToggled modifyIDE_ (\ide -> ide{prefs = (prefs ide){makeMode= toggled}}) -- --------------------------------------------------------------------- -- | * Debug code that needs to use the package -- interactiveFlag :: Text -> Bool -> Text interactiveFlag name f = (if f then "-f" else "-fno-") <> name printEvldWithShowFlag :: Bool -> Text printEvldWithShowFlag = interactiveFlag "print-evld-with-show" breakOnExceptionFlag :: Bool -> Text breakOnExceptionFlag = interactiveFlag "break-on-exception" breakOnErrorFlag :: Bool -> Text breakOnErrorFlag = interactiveFlag "break-on-error" printBindResultFlag :: Bool -> Text printBindResultFlag = interactiveFlag "print-bind-result" interactiveFlags :: Prefs -> [Text] interactiveFlags prefs = printEvldWithShowFlag (printEvldWithShow prefs) : breakOnExceptionFlag (breakOnException prefs) : breakOnErrorFlag (breakOnError prefs) : [printBindResultFlag $ printBindResult prefs] debugStart :: PackageAction debugStart = do package <- ask liftIDE $ catchIDE (do ideRef <- ask prefs' <- readIDE prefs maybeDebug <- readIDE debugState case maybeDebug of Nothing -> do let dir = ipdPackageDir package mbExe <- readIDE activeExe ghci <- reifyIDE $ \ideR -> newGhci dir mbExe (interactiveFlags prefs') $ reflectIDEI (void (logOutputForBuild package True False)) ideR modifyIDE_ (\ide -> ide {debugState = Just (package, ghci)}) triggerEventIDE (Sensitivity [(SensitivityInterpreting, True)]) setDebugToggled True -- Fork a thread to wait for the output from the process to close liftIO $ forkIO $ do readMVar (outputClosed ghci) (`reflectIDE` ideRef) . postSyncIDE $ do setDebugToggled False modifyIDE_ (\ide -> ide {debugState = Nothing, autoCommand = return ()}) triggerEventIDE (Sensitivity [(SensitivityInterpreting, False)]) -- Kick of a build if one is not already due modifiedPacks <- fileCheckAll belongsToPackages' let modified = not (null modifiedPacks) prefs <- readIDE prefs when (not modified && backgroundBuild prefs) $ do -- So although none of the pakages are modified, -- they may have been modified in ghci mode. -- Lets build to make sure the binaries are up to date mbPackage <- readIDE activePack case mbPackage of Just package -> runCabalBuild True False False package True (\ _ -> return ()) Nothing -> return () return () _ -> do sysMessage Normal (__ "Debugger already running") return ()) (\(e :: SomeException) -> print e) tryDebug :: DebugAction -> PackageAction tryDebug f = do maybeDebug <- liftIDE $ readIDE debugState case maybeDebug of Just debug -> -- TODO check debug package matches active package liftIDE $ runDebug f debug _ -> do window <- liftIDE getMainWindow md <- new' MessageDialog [ constructDialogUseHeaderBar 0, constructMessageDialogButtons ButtonsTypeCancel] setMessageDialogMessageType md MessageTypeQuestion setMessageDialogText md $ __ "GHCi debugger is not running." windowSetTransientFor md (Just window) dialogAddButton' md (__ "_Start GHCi") (AnotherResponseType 1) dialogSetDefaultResponse' md (AnotherResponseType 1) setWindowWindowPosition md WindowPositionCenterOnParent resp <- dialogRun' md widgetDestroy md case resp of AnotherResponseType 1 -> do debugStart maybeDebug <- liftIDE $ readIDE debugState case maybeDebug of Just debug -> liftIDE $ postAsyncIDE $ runDebug f debug _ -> return () _ -> return () tryDebugQuiet :: DebugAction -> PackageAction tryDebugQuiet f = do maybeDebug <- liftIDE $ readIDE debugState case maybeDebug of Just debug -> -- TODO check debug package matches active package liftIDE $ runDebug f debug _ -> return () executeDebugCommand :: Text -> C.Sink ToolOutput IDEM () -> DebugAction executeDebugCommand command handler = do (_, ghci) <- ask lift $ do ideR <- ask postAsyncIDE $ do triggerEventIDE (StatusbarChanged [CompartmentState command, CompartmentBuild True]) return () liftIO . executeGhciCommand ghci command $ reflectIDEI (do lift . postSyncIDE $ do triggerEventIDE (StatusbarChanged [CompartmentState "", CompartmentBuild False]) return () handler) ideR -- Includes non buildable allBuildInfo' :: PackageDescription -> [BuildInfo] allBuildInfo' pkg_descr = [ libBuildInfo lib | Just lib <- [library pkg_descr] ] ++ [ buildInfo exe | exe <- executables pkg_descr ] ++ [ testBuildInfo tst | tst <- testSuites pkg_descr ] ++ [ benchmarkBuildInfo tst | tst <- benchmarks pkg_descr ] testMainPath (TestSuiteExeV10 _ f) = [f] testMainPath _ = [] idePackageFromPath' :: FilePath -> IDEM (Maybe IDEPackage) idePackageFromPath' ipdCabalFile = do mbPackageD <- reifyIDE (\ideR -> catch (do pd <- readPackageDescription normal ipdCabalFile return (Just (flattenPackageDescription pd))) (\ (e :: SomeException) -> do reflectIDE (ideMessage Normal (__ "Can't activate package " <> T.pack (show e))) ideR return Nothing)) case mbPackageD of Nothing -> return Nothing Just packageD -> do let ipdModules = Map.fromList $ myLibModules packageD ++ myExeModules packageD ++ myTestModules packageD ++ myBenchmarkModules packageD ipdMain = [ (modulePath exe, buildInfo exe, False) | exe <- executables packageD ] ++ [ (f, bi, True) | TestSuite _ (TestSuiteExeV10 _ f) bi _ <- testSuites packageD ] ++ [ (f, bi, True) | Benchmark _ (BenchmarkExeV10 _ f) bi _ <- benchmarks packageD ] ipdExtraSrcs = Set.fromList $ extraSrcFiles packageD ipdSrcDirs = case nub $ concatMap hsSourceDirs (allBuildInfo' packageD) of [] -> [".","src"] l -> l ipdExes = [ T.pack $ exeName e | e <- executables packageD , buildable (buildInfo e) ] ipdExtensions = nub $ concatMap oldExtensions (allBuildInfo' packageD) ipdTests = [ T.pack $ testName t | t <- testSuites packageD , buildable (testBuildInfo t) ] ipdBenchmarks = [ T.pack $ benchmarkName b | b <- benchmarks packageD , buildable (benchmarkBuildInfo b) ] ipdPackageId = package packageD ipdDepends = buildDepends packageD ipdHasLibs = hasLibs packageD ipdConfigFlags = ["--enable-tests"] ipdBuildFlags = [] ipdTestFlags = [] ipdBenchmarkFlags = [] ipdHaddockFlags = [] ipdExeFlags = [] ipdInstallFlags = [] ipdRegisterFlags = [] ipdUnregisterFlags = [] ipdSdistFlags = [] ipdSandboxSources = [] packp = IDEPackage {..} pfile = dropExtension ipdCabalFile pack <- do flagFileExists <- liftIO $ doesFileExist (pfile ++ leksahFlagFileExtension) if flagFileExists then liftIO $ readFlags (pfile ++ leksahFlagFileExtension) packp else return packp return (Just pack) extractStackPackageList :: Text -> [String] extractStackPackageList = filter (/= ".") . map (stripQuotes . T.unpack . (\x -> fromMaybe x $ T.stripPrefix "location: " x)) . mapMaybe (T.stripPrefix "- ") . takeWhile ("- " `T.isPrefixOf`) . drop 1 . dropWhile (/= "packages:") . T.lines where stripQuotes ('\'':rest) | take 1 (reverse rest) == "\'" = init rest stripQuotes x = x idePackageFromPath :: C.Sink ToolOutput IDEM () -> FilePath -> IDEM (Maybe IDEPackage) idePackageFromPath log filePath = do mbRootPackage <- idePackageFromPath' filePath case mbRootPackage of Nothing -> return Nothing Just rootPackage -> do mvar <- liftIO newEmptyMVar let dir = takeDirectory filePath useStack <- liftIO . doesFileExist $ dir </> "stack.yaml" paths <- if useStack then liftIO $ map (dir </>) . extractStackPackageList <$> T.readFile (dir </> "stack.yaml") else do runExternalTool' "" "cabal" ["sandbox", "list-sources"] dir $ do output <- CL.consume liftIO . putMVar mvar $ case take 1 $ reverse output of [ToolExit ExitSuccess] -> map (T.unpack . toolline) . takeWhile (/= ToolOutput "") . drop 1 $ dropWhile (/= ToolOutput "") output _ -> [] liftIO $ takeMVar mvar sandboxSources <- catMaybes <$> forM paths (\path -> do exists <- liftIO (doesDirectoryExist path) if exists then do cpath <- liftIO $ canonicalizePath path contents <- liftIO $ getDirectoryContents cpath let mbCabalFile = find ((== ".cabal") . takeExtension) contents when (isNothing mbCabalFile) $ ideMessage Normal ("Could not find cabal file of the add-source dependency at " <> T.pack cpath) return (fmap (path </>) mbCabalFile) else do ideMessage Normal ("Path of add-source dependency does not exist: " <> T.pack path) return Nothing) s <- liftM catMaybes . mapM idePackageFromPath' $ nub sandboxSources return . Just $ rootPackage {ipdSandboxSources = s} refreshPackage :: C.Sink ToolOutput IDEM () -> PackageM (Maybe IDEPackage) refreshPackage log = do package <- ask liftIDE $ do mbUpdatedPack <- idePackageFromPath log (ipdCabalFile package) case mbUpdatedPack of Just updatedPack -> do changePackage updatedPack triggerEventIDE $ WorkspaceChanged False True return mbUpdatedPack Nothing -> do postAsyncIDE $ ideMessage Normal (__ "Can't read package file") return Nothing
JPMoresmau/leksah
src/IDE/Package.hs
gpl-2.0
51,608
1
34
16,981
12,932
6,501
6,431
967
8
module SongMaker.Format.Aeson ( JsonStream , liftJson) where import GHC.Generics import Data.Aeson import SongMaker.Convert.Stream import SongMaker.Common import SongMaker.Common.Song newtype JsonStream = JS Stream liftJson :: Stream -> JsonStream liftJson = JS instance IsStream JsonStream where toStream (JS s) = s fromStream = liftJson instance ToJSON Song where toEncoding = genericToEncoding defaultOptions instance FromJSON Song instance ToJSON SongNumbering where toEncoding = genericToEncoding defaultOptions instance FromJSON SongNumbering instance ToJSON VerseType where toEncoding = genericToEncoding defaultOptions instance FromJSON VerseType instance ToJSON Verse where toEncoding = genericToEncoding defaultOptions instance FromJSON Verse
firefrorefiddle/songmaker
src/SongMaker/Format/Aeson.hs
gpl-2.0
785
0
8
118
183
98
85
26
1
module Ch4 where import Data.Char (digitToInt, isDigit,isUpper) --example count the number of word in a string that satisfy a predicate p numElmSatisfy :: (a->Bool)-> [a] -> Int numElmSatisfy p = (length . (filter p)) --numWordsSatisfy :: (a->Bool)-> [a] -> Int numWordsSatisfy p = (length . (filter p) . words) numWordsStartsUpper = let p = (isUpper . head) in numWordsSatisfy p --function composition (.) in Prelude compose :: (b->c) -> (a->b) -> a -> c compose f g a = f (g a) --does not produce the null element at the end of the list also implementable as myTails'' = init . myTails myTails' :: [a] -> [[a]] myTails' ys@(_:xs) = ys : myTails' xs myTails' _ = [] myTails :: [a] -> [[a]] myTails [] = [[]] myTails xs = let tal = (tail xs)in [xs]++ (myTails tal) {- How many of the following Prelude functions can you rewrite using list folds? For those functions where you can use either foldl' or foldr, which is more appropriate in each case? -} --unlines------------------------------------------------------- myUnlines :: [String] -> String myUnlines = foldr (\x acc -> x++"\n"++acc) "" --words ------------------------------------------------------- myWords :: String -> [String] myWords = foldr step [] where step x acc@(y:ys) = if (x=='\n') then ([]:acc) else ((x:y):ys) step x acc = [[x]] --cycle ------------------------------------------------------- infList :: [Int] infList=repeat 1 myCycle :: [a] -> [a] myCycle [] = error "Empty lists" myCycle xs = xs ++ (myCycle xs) myCycle_foldr :: [a] -> [a] myCycle_foldr [] = error "Empty Lists" myCycle_foldr xs = foldr (\_ acc -> xs++acc) [] (infList) --[1..] --any ------------------------------------------------------- my_any :: (a->Bool) -> [a] -> Bool my_any _ [] = False my_any p (x:xs) | p x = True | otherwise = my_any p xs --let p = (even) in quickCheck (\s ->any p s == my_any_fold p s) my_any_fold :: (a->Bool) -> [a] -> Bool my_any_fold p = foldr (\x acc-> acc || p x) False myGroupBy_fold :: (a -> a -> Bool) -> [a] -> [[a]] myGroupBy_fold p = foldr step [] where step x [] = [[x]] step x l@(aa@(a:_):ls) = if (p x a) then ((x:aa)):ls else [x]:l --let p = (==) in quickCheck (\s ->myGroupBy p s == groupBy p s) --this to check that the function axtually is correct! myGroupBy :: (a-> a-> Bool) -> [a] -> [[a]] myGroupBy p l = myGroupBy' p [] l where myGroupBy' p acc [] = acc myGroupBy' p [] (x:xs) = myGroupBy' p ([[x]]) xs myGroupBy' p aa@(a:as) (x:xs) = let newAcc = if (p (head a) x) then ((x:a):as) else [x]:aa in myGroupBy' p newAcc xs --write ytour own definition of takeWhile first using explicit recursion then using foldr myTakeWhile_rec :: (a -> Bool) -> [a] -> [a] myTakeWhile_rec p l= myTakeWhile_rec' p [] l where myTakeWhile_rec' p acc [] = acc myTakeWhile_rec' p acc (x:xs) = if(p x) then myTakeWhile_rec' p (acc++[x]) xs else acc myTakeWhile_foldl :: (a -> Bool) -> [a] -> [a] myTakeWhile_foldl p l = snd $ foldl step (True,[]) l where step (True,acc) x = if (p x) then (True,acc++[x]) else (False,acc) step (False,acc) _ = (False,acc) takeWhile_foldr :: (a -> Bool) -> [a] -> [a] takeWhile_foldr p = foldr (\x xs -> if p x then x:xs else []) [] concat_foldr :: [[a]] ->[a] concat_foldr = foldr (++) [] --synonim for String type ErrorMessage = String --wrapper for different asIntfold asInt :: String -> Either ErrorMessage Int --asInt :: String -> Int asInt l@(x:xs) |x=='-' = let n=foldFunction xs in case n of (Left x) -> (Left x) (Right x) -> (Right (negate x)) |otherwise = foldFunction l where foldFunction = asInt_either asInt_either :: String -> Either ErrorMessage Int asInt_either = foldl step (Right 0) where step(Left a) _ = Left a step (Right acc) x = let next = acc*10+ (digitToInt x) in if (isDigit x) then (Right next) else (Left "Invalid Char") asIntFold :: String -> Int asIntFold = foldl step 0 where step acc x = acc*10+ (digitToInt x) asIntFold_error :: String -> Int asIntFold_error = foldl step 0 where step acc x = let next = acc*10+ (digitToInt x) in if (isDigit x) then next else error "Invalid char"
knotman90/haskell-tutorial
code/realWorldHaskell_ch4.hs
gpl-2.0
4,241
33
15
922
1,662
922
740
81
4
module Mescaline.Analysis.Meap ( Meap , analyser ) where import Control.Arrow (first) import Mescaline.Analysis.Types -- import qualified Mescaline.Application.Logger as Log import Mescaline.Analysis.Meap.Chain as Chain import qualified Mescaline.Analysis.Meap.Extractor as Extractor import Mescaline.Analysis.Meap.Process (ClassPath, defaultOutputHandler, makeClassPath) import qualified Mescaline.Analysis.Meap.Segmenter as Segmenter import qualified Sound.Analysis.Meapsoft as Meap meapFeaturePrefix :: String meapFeaturePrefix = "com.meapsoft." meapFeatures :: [(String, Int)] meapFeatures = [ -- ( "AvgChroma" , 12 ) -- , ( "AvgChromaScalar" , 1 ) ( "AvgChunkPower" , 1 ) , ( "AvgFreqSimple" , 1 ) -- , ( "AvgMelSpec" , 40 ) , ( "AvgMFCC" , 13 ) -- , ( "AvgPitch" , 1 ) -- , ( "AvgSpecCentroid" , 1 ) -- , ( "AvgSpecFlatness" , 1 ) -- , ( "AvgTonalCentroid" , 6 ) -- , ( "ChunkLength" , 1 ) -- , ( "ChunkStartTime" , 1 ) -- , ( "Entropy" , 1 ) -- , ( "RMSAmplitude" , 1 ) -- , ( "SpectralStability" , 1 ) ] meapOptions :: ClassPath -> Chain.Options meapOptions classPath = Chain.defaultOptions { segmenter = Segmenter.defaultOptions { Segmenter.classPath = classPath , Segmenter.outputHandler = outputHandler , Segmenter.segmentation = Segmenter.Onset , Segmenter.smoothingWindow = 0.01 } , extractor = Extractor.defaultOptions { Extractor.classPath = classPath , Extractor.outputHandler = outputHandler , Extractor.windowSize = 1024 , Extractor.hopSize = 512 , Extractor.features = map fst meapFeatures } } where -- outputHandler = OutputHandler (Log.noticeM "Database") (Log.errorM "Database") outputHandler = defaultOutputHandler convUnit :: (Double, Double) -> Unit convUnit = uncurry Unit convDescriptor :: Meap.Feature -> Descriptor convDescriptor f = Descriptor (meapFeaturePrefix ++ (Meap.feature_name f)) (Meap.feature_degree f) convFeature :: Meap.Feature -> [Double] -> Feature convFeature f l = Feature (convDescriptor f) v where v = take (Meap.feature_degree f) $ drop (Meap.feature_column f) l meapFrames :: Meap.MEAP -> [[Double]] meapFrames meap = map (Meap.frame_l meap) [0..Meap.n_frames meap - 1] convMeap :: Meap.MEAP -> [(Unit, [Feature])] convMeap meap = zip us (map (\v -> map (flip convFeature v) fs) (meapFrames meap)) where fs = Meap.features meap us = map convUnit (Meap.segments_l meap) data Meap = Meap FilePath analyser :: FilePath -> Meap analyser = Meap instance Analyser Meap where -- | List of audio file extensions Meap can handle at the moment. fileExtensions = const ["aif", "aiff", "wav"] analyse (Meap libDir) path = do putStrLn "Meap analysis ..." r <- flip Chain.run path . meapOptions =<< makeClassPath libDir case r of Left e -> fail e Right meap -> do let a = convMeap meap newAnalysis path a
kaoskorobase/mescaline
lib/mescaline-database/Mescaline/Analysis/Meap.hs
gpl-3.0
3,243
0
16
902
727
411
316
60
1
module Tile (nextWin, prevWin, removeWin, addWin) where import Debug import Dir import Layout import State import Types import X11 import Graphics.X11 nextWin, prevWin :: TileRef -> X11State () nextWin = rotateWin popFront pushBack prevWin = rotateWin popBack pushFront rotateWin :: (DQ Window -> (Maybe Window, DQ Window)) -> (DQ Window -> Window -> DQ Window) -> TileRef -> X11State () rotateWin pop push tr = do modifyTileWindows f tr wo <- getWorld let win = first $ getTileWindows wo tr case win of Nothing -> return () Just win -> do getDisplay >>= liftIO . flip raiseWindow win updateX11Focus where f q = case pop q of (Nothing, _) -> q (Just x, q') -> push q' x removeWin :: TileRef -> X11State (Maybe Window) removeWin tr = do wo <- getWorld let win = first $ getTileWindows wo tr debug "Remove window:" dprint win modifyTileWindows (snd . popFront) tr return win addWin :: TileRef -> Window -> X11State () addWin tr win = do debug "Add window:" dprint win dprint tr modifyTileWindows (flip pushFront win) tr lift $ lift $ layoutWindow tr win
ktvoelker/argon
src/Tile.hs
gpl-3.0
1,139
0
13
271
440
212
228
43
3
s = map (\x -> 1 / x^2) [1, 2..] s' = sum (take 1000000 s)
graninas/Haskell-Algorithms
Tests/InfSum.hs
gpl-3.0
61
2
9
18
56
26
30
2
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} -- | -- Module : Network.AWS.Internal.HTTP -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : provisional -- Portability : non-portable (GHC extensions) -- module Network.AWS.Internal.HTTP ( retrier , waiter ) where import Control.Arrow (first) import Control.Monad import Control.Monad.Catch import Control.Monad.Reader import Control.Monad.Trans.Resource import Control.Retry import Data.List (intersperse) import Data.Monoid import Data.Proxy import Data.Time import Network.AWS.Env import Network.AWS.Internal.Logger import Network.AWS.Prelude import Network.AWS.Waiter import Network.HTTP.Conduit hiding (Proxy, Request, Response) import Prelude retrier :: ( MonadCatch m , MonadResource m , MonadReader r m , HasEnv r , AWSRequest a ) => a -> m (Either Error (Response a)) retrier x = do e <- view environment rq <- configured x retrying (policy rq) (check e rq) (perform e rq) where policy rq = retryStream rq <> retryService (_rqService rq) check e rq n (Left r) | Just p <- r ^? transportErr, p = msg e "http_error" n >> return True | Just m <- r ^? serviceErr = msg e m n >> return True where transportErr = _TransportError . to (_envRetryCheck e n) serviceErr = _ServiceError . to rc . _Just rc = rq ^. rqService . serviceRetry . retryCheck check _ _ _ _ = return False msg :: MonadIO m => Env -> Text -> Int -> m () msg e m n = logDebug (_envLogger e) . mconcat . intersperse " " $ [ "[Retry " <> build m <> "]" , "after" , build (n + 1) , "attempts." ] waiter :: ( MonadCatch m , MonadResource m , MonadReader r m , HasEnv r , AWSRequest a ) => Wait a -> a -> m (Maybe Error) waiter w@Wait{..} x = do e@Env{..} <- view environment rq <- configured x retrying policy (check _envLogger) (result rq <$> perform e rq) >>= exit where policy = limitRetries _waitAttempts <> constantDelay (microseconds _waitDelay) check e n (a, _) = msg e n a >> return (retry a) where retry AcceptSuccess = False retry AcceptFailure = False retry AcceptRetry = True result rq = first (fromMaybe AcceptRetry . accept w rq) . join (,) exit (AcceptSuccess, _) = return Nothing exit (_, Left e) = return (Just e) exit (_, _) = return Nothing msg l n a = logDebug l . mconcat . intersperse " " $ [ "[Await " <> build _waitName <> "]" , build a , "after" , build (n + 1) , "attempts." ] -- | The 'Service' is configured + unwrapped at this point. perform :: (MonadCatch m, MonadResource m, AWSRequest a) => Env -> Request a -> m (Either Error (Response a)) perform Env{..} x = catches go handlers where go = do t <- liftIO getCurrentTime Signed m rq <- withAuth _envAuth $ \a -> return $! rqSign x a _envRegion t logTrace _envLogger m -- trace:Signing:Meta logDebug _envLogger rq -- debug:ClientRequest rs <- liftResourceT (http rq _envManager) logDebug _envLogger rs -- debug:ClientResponse Right <$> response _envLogger (_rqService x) (p x) rs handlers = [ Handler $ err , Handler $ err . TransportError ] where err e = logError _envLogger e >> return (Left e) p :: Request a -> Proxy a p = const Proxy configured :: (MonadReader r m, HasEnv r, AWSRequest a) => a -> m (Request a) configured (request -> x) = do o <- view envOverride return $! x & rqService %~ appEndo (getDual o) retryStream :: Request a -> RetryPolicy retryStream x = RetryPolicy (const $ listToMaybe [0 | not p]) where !p = isStreaming (_rqBody x) retryService :: Service -> RetryPolicy retryService s = limitRetries _retryAttempts <> RetryPolicy delay where delay n | n > 0 = Just $ truncate (grow * 1000000) | otherwise = Nothing where grow = _retryBase * (fromIntegral _retryGrowth ^^ (n - 1)) Exponential{..} = _svcRetry s
olorin/amazonka
amazonka/src/Network/AWS/Internal/HTTP.hs
mpl-2.0
4,960
0
16
1,725
1,485
748
737
-1
-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.PlacementStrategies.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets one placement strategy by ID. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.placementStrategies.get@. module Network.Google.Resource.DFAReporting.PlacementStrategies.Get ( -- * REST Resource PlacementStrategiesGetResource -- * Creating a Request , placementStrategiesGet , PlacementStrategiesGet -- * Request Lenses , psgXgafv , psgUploadProtocol , psgAccessToken , psgUploadType , psgProFileId , psgId , psgCallback ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.placementStrategies.get@ method which the -- 'PlacementStrategiesGet' request conforms to. type PlacementStrategiesGetResource = "dfareporting" :> "v3.5" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "placementStrategies" :> Capture "id" (Textual Int64) :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] PlacementStrategy -- | Gets one placement strategy by ID. -- -- /See:/ 'placementStrategiesGet' smart constructor. data PlacementStrategiesGet = PlacementStrategiesGet' { _psgXgafv :: !(Maybe Xgafv) , _psgUploadProtocol :: !(Maybe Text) , _psgAccessToken :: !(Maybe Text) , _psgUploadType :: !(Maybe Text) , _psgProFileId :: !(Textual Int64) , _psgId :: !(Textual Int64) , _psgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PlacementStrategiesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psgXgafv' -- -- * 'psgUploadProtocol' -- -- * 'psgAccessToken' -- -- * 'psgUploadType' -- -- * 'psgProFileId' -- -- * 'psgId' -- -- * 'psgCallback' placementStrategiesGet :: Int64 -- ^ 'psgProFileId' -> Int64 -- ^ 'psgId' -> PlacementStrategiesGet placementStrategiesGet pPsgProFileId_ pPsgId_ = PlacementStrategiesGet' { _psgXgafv = Nothing , _psgUploadProtocol = Nothing , _psgAccessToken = Nothing , _psgUploadType = Nothing , _psgProFileId = _Coerce # pPsgProFileId_ , _psgId = _Coerce # pPsgId_ , _psgCallback = Nothing } -- | V1 error format. psgXgafv :: Lens' PlacementStrategiesGet (Maybe Xgafv) psgXgafv = lens _psgXgafv (\ s a -> s{_psgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). psgUploadProtocol :: Lens' PlacementStrategiesGet (Maybe Text) psgUploadProtocol = lens _psgUploadProtocol (\ s a -> s{_psgUploadProtocol = a}) -- | OAuth access token. psgAccessToken :: Lens' PlacementStrategiesGet (Maybe Text) psgAccessToken = lens _psgAccessToken (\ s a -> s{_psgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). psgUploadType :: Lens' PlacementStrategiesGet (Maybe Text) psgUploadType = lens _psgUploadType (\ s a -> s{_psgUploadType = a}) -- | User profile ID associated with this request. psgProFileId :: Lens' PlacementStrategiesGet Int64 psgProFileId = lens _psgProFileId (\ s a -> s{_psgProFileId = a}) . _Coerce -- | Placement strategy ID. psgId :: Lens' PlacementStrategiesGet Int64 psgId = lens _psgId (\ s a -> s{_psgId = a}) . _Coerce -- | JSONP psgCallback :: Lens' PlacementStrategiesGet (Maybe Text) psgCallback = lens _psgCallback (\ s a -> s{_psgCallback = a}) instance GoogleRequest PlacementStrategiesGet where type Rs PlacementStrategiesGet = PlacementStrategy type Scopes PlacementStrategiesGet = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient PlacementStrategiesGet'{..} = go _psgProFileId _psgId _psgXgafv _psgUploadProtocol _psgAccessToken _psgUploadType _psgCallback (Just AltJSON) dFAReportingService where go = buildClient (Proxy :: Proxy PlacementStrategiesGetResource) mempty
brendanhay/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/PlacementStrategies/Get.hs
mpl-2.0
5,232
0
19
1,256
821
474
347
117
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.Dataflow.Projects.Jobs.WorkItems.ReportStatus -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Reports the status of dataflow WorkItems leased by a worker. -- -- /See:/ <https://cloud.google.com/dataflow Dataflow API Reference> for @dataflow.projects.jobs.workItems.reportStatus@. module Network.Google.Resource.Dataflow.Projects.Jobs.WorkItems.ReportStatus ( -- * REST Resource ProjectsJobsWorkItemsReportStatusResource -- * Creating a Request , projectsJobsWorkItemsReportStatus , ProjectsJobsWorkItemsReportStatus -- * Request Lenses , pjwirsXgafv , pjwirsJobId , pjwirsUploadProtocol , pjwirsAccessToken , pjwirsUploadType , pjwirsPayload , pjwirsProjectId , pjwirsCallback ) where import Network.Google.Dataflow.Types import Network.Google.Prelude -- | A resource alias for @dataflow.projects.jobs.workItems.reportStatus@ method which the -- 'ProjectsJobsWorkItemsReportStatus' request conforms to. type ProjectsJobsWorkItemsReportStatusResource = "v1b3" :> "projects" :> Capture "projectId" Text :> "jobs" :> Capture "jobId" Text :> "workItems:reportStatus" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ReportWorkItemStatusRequest :> Post '[JSON] ReportWorkItemStatusResponse -- | Reports the status of dataflow WorkItems leased by a worker. -- -- /See:/ 'projectsJobsWorkItemsReportStatus' smart constructor. data ProjectsJobsWorkItemsReportStatus = ProjectsJobsWorkItemsReportStatus' { _pjwirsXgafv :: !(Maybe Xgafv) , _pjwirsJobId :: !Text , _pjwirsUploadProtocol :: !(Maybe Text) , _pjwirsAccessToken :: !(Maybe Text) , _pjwirsUploadType :: !(Maybe Text) , _pjwirsPayload :: !ReportWorkItemStatusRequest , _pjwirsProjectId :: !Text , _pjwirsCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsJobsWorkItemsReportStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pjwirsXgafv' -- -- * 'pjwirsJobId' -- -- * 'pjwirsUploadProtocol' -- -- * 'pjwirsAccessToken' -- -- * 'pjwirsUploadType' -- -- * 'pjwirsPayload' -- -- * 'pjwirsProjectId' -- -- * 'pjwirsCallback' projectsJobsWorkItemsReportStatus :: Text -- ^ 'pjwirsJobId' -> ReportWorkItemStatusRequest -- ^ 'pjwirsPayload' -> Text -- ^ 'pjwirsProjectId' -> ProjectsJobsWorkItemsReportStatus projectsJobsWorkItemsReportStatus pPjwirsJobId_ pPjwirsPayload_ pPjwirsProjectId_ = ProjectsJobsWorkItemsReportStatus' { _pjwirsXgafv = Nothing , _pjwirsJobId = pPjwirsJobId_ , _pjwirsUploadProtocol = Nothing , _pjwirsAccessToken = Nothing , _pjwirsUploadType = Nothing , _pjwirsPayload = pPjwirsPayload_ , _pjwirsProjectId = pPjwirsProjectId_ , _pjwirsCallback = Nothing } -- | V1 error format. pjwirsXgafv :: Lens' ProjectsJobsWorkItemsReportStatus (Maybe Xgafv) pjwirsXgafv = lens _pjwirsXgafv (\ s a -> s{_pjwirsXgafv = a}) -- | The job which the WorkItem is part of. pjwirsJobId :: Lens' ProjectsJobsWorkItemsReportStatus Text pjwirsJobId = lens _pjwirsJobId (\ s a -> s{_pjwirsJobId = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pjwirsUploadProtocol :: Lens' ProjectsJobsWorkItemsReportStatus (Maybe Text) pjwirsUploadProtocol = lens _pjwirsUploadProtocol (\ s a -> s{_pjwirsUploadProtocol = a}) -- | OAuth access token. pjwirsAccessToken :: Lens' ProjectsJobsWorkItemsReportStatus (Maybe Text) pjwirsAccessToken = lens _pjwirsAccessToken (\ s a -> s{_pjwirsAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pjwirsUploadType :: Lens' ProjectsJobsWorkItemsReportStatus (Maybe Text) pjwirsUploadType = lens _pjwirsUploadType (\ s a -> s{_pjwirsUploadType = a}) -- | Multipart request metadata. pjwirsPayload :: Lens' ProjectsJobsWorkItemsReportStatus ReportWorkItemStatusRequest pjwirsPayload = lens _pjwirsPayload (\ s a -> s{_pjwirsPayload = a}) -- | The project which owns the WorkItem\'s job. pjwirsProjectId :: Lens' ProjectsJobsWorkItemsReportStatus Text pjwirsProjectId = lens _pjwirsProjectId (\ s a -> s{_pjwirsProjectId = a}) -- | JSONP pjwirsCallback :: Lens' ProjectsJobsWorkItemsReportStatus (Maybe Text) pjwirsCallback = lens _pjwirsCallback (\ s a -> s{_pjwirsCallback = a}) instance GoogleRequest ProjectsJobsWorkItemsReportStatus where type Rs ProjectsJobsWorkItemsReportStatus = ReportWorkItemStatusResponse type Scopes ProjectsJobsWorkItemsReportStatus = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/userinfo.email"] requestClient ProjectsJobsWorkItemsReportStatus'{..} = go _pjwirsProjectId _pjwirsJobId _pjwirsXgafv _pjwirsUploadProtocol _pjwirsAccessToken _pjwirsUploadType _pjwirsCallback (Just AltJSON) _pjwirsPayload dataflowService where go = buildClient (Proxy :: Proxy ProjectsJobsWorkItemsReportStatusResource) mempty
brendanhay/gogol
gogol-dataflow/gen/Network/Google/Resource/Dataflow/Projects/Jobs/WorkItems/ReportStatus.hs
mpl-2.0
6,507
0
20
1,485
872
508
364
137
1
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} {-| This is the entry point for this web server application. It supports easily switching between interpreting source and running statically compiled code. In either mode, the generated program should be run from the root of the project tree. When it is run, it locates its templates, static content, and source files in development mode, relative to the current working directory. When compiled with the development flag, only changes to the libraries, your cabal file, or this file should require a recompile to be picked up. Everything else is interpreted at runtime. There are a few consequences of this. First, this is much slower. Running the interpreter takes a significant chunk of time (a couple tenths of a second on the author's machine, at this time), regardless of the simplicity of the loaded code. In order to recompile and re-load server state as infrequently as possible, the source directories are watched for updates, as are any extra directories specified below. Second, the generated server binary is MUCH larger, since it links in the GHC API (via the hint library). Third, and the reason you would ever want to actually compile with development mode, is that it enables a faster development cycle. You can simply edit a file, save your changes, and hit reload to see your changes reflected immediately. When this is compiled without the development flag, all the actions are statically compiled in. This results in faster execution, a smaller binary size, and having to recompile the server for any code change. -} module Main where #ifdef DEVELOPMENT import Snap.Extension.Loader.Devel import Snap.Http.Server (quickHttpServe) #else import Snap.Extension.Server #endif import Application import Site main :: IO () #ifdef DEVELOPMENT main = do -- All source directories will be watched for updates -- automatically. If any extra directories should be watched for -- updates, include them here. snap <- $(let extraWatcheDirs = ["resources/templates"] in loadSnapTH 'applicationInitializer 'site extraWatcheDirs) quickHttpServe snap #else main = quickHttpServe applicationInitializer site #endif
wjt/flitwemmmmm
src/Main.hs
agpl-3.0
2,276
0
14
438
95
58
37
8
1
{-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE OverloadedStrings #-} module MatsuiCoJp.ScraperSpec (spec) where import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.IO as TL import MatsuiCoJp.Scraper import Test.Hspec -- -- "ホーム" -> "お知らせ" のページ -- test01HomeAnnounce = "https%3A%2F%2Fwww.deal.matsui.co.jp%2Fservlet%2FITS%2Fhome%2FAnnounce.utf8.html" test01HomeAnnounce' = FraHomeAnnounce { announceDeriverTime = "2017年12月18日 23:25 現在" , announceLastLoginTime = "前回ログイン:2017年12月18日 23:25" , announces = [ "**** ****様 へのご連絡" , "本日の注文 4件、約定 1件" , "その他お客様宛のメッセージはありません。" , "会員様へのご連絡" , "【投資信託】「コモンズ30ファンド」や「AI(人工知能)活用型世界株ファンド」等24銘柄の取扱いを開始します" , "立会外分売受付中(~12/19 08:30まで)" , "【投資信託】投信工房に自動リバランス機能等を追加します(12/23~)" , "「週刊 株式相場レポート」を更新しました(12/15)" , "【一日信用取引】プレミアム空売り銘柄を追加します(12/18取引分~)" , "【重要】12月末決算・分割銘柄を保有(取引)するお客様へ" , "【一日信用取引】プレミアム空売り銘柄を追加します(12/15取引分~)" , "【一日信用取引】プレミアム空売り銘柄の建玉上限変更について" , "年末年始の営業時間のお知らせ(2017-2018)" , "12月の株主優待銘柄のご案内!" , "10万円超のお取引であたる優待応援カタログギフトキャンペーン" , "【好評につき期間延長】一日信用取引 金利引下げキャンペーン" , "【期間延長】『iシェアーズETF』買付手数料実質無料キャンペーン" , "【ご案内】つみたてNISAの申込を受付中です" , "ご家族・ご友人紹介プログラムを実施中です" , " " , "株式銘柄情報" , "メッセージ7件" ] } -- -- "株式取引" -> "現物売" のページ -- -- 保有株式1つの場合 test01StkHavingList = "https%3A%2F%2Fwww.deal.matsui.co.jp%2Fservlet%2FITS%2Fstock%2FStkHavingList.utf8.01.html" test01StkSell = FraStkSell { evaluation = 561.0 , profit = -6.0 , stocks = [ HoldStock { sellOrderUrl = Just "/servlet/ITS/stock/StkSellOrder;" , code = 9399 , caption = "新華ホールディングス・リミテッド" , count = 3 , purchasePrice = 189.0 , price = 187.0 } ] } -- 保有株式なしの場合 test02StkHavingList = "https%3A%2F%2Fwww.deal.matsui.co.jp%2Fservlet%2FITS%2Fstock%2FStkHavingList.utf8.02.html" test02StkSell = FraStkSell { evaluation = 0.0 , profit = 0.0 , stocks = [] } -- -- 資産状況 -> 余力情報のページ -- test01AstSpare = "https%3A%2F%2Fwww.deal.matsui.co.jp%2Fservlet%2FITS%2Fasset%2FMoneyToSpare.utf8.html" test01AstSpare' = FraAstSpare { moneySpare = 402 , cashBalance = 1482 , depositInc = 0 , depositDec = 0 , bindingFee = 0 , bindingTax = 0 , freeCash = 1482 } -- -- Hspecテスト -- spec :: Spec spec = do -- describe "scrapingFraHomeAnnounce" $ it "test 01" $ do html <- TL.readFile ("test/MatsuiCoJp/" ++ test01HomeAnnounce) scrapingFraHomeAnnounce [html] >>= shouldBe test01HomeAnnounce' -- describe "scrapingFraStkSell" $ do it "test 01" $ do html <- TL.readFile ("test/MatsuiCoJp/" ++ test01StkHavingList) scrapingFraStkSell [html] >>= shouldBe test01StkSell -- it "test 02" $ do html <- TL.readFile ("test/MatsuiCoJp/" ++ test02StkHavingList) scrapingFraStkSell [html] >>= shouldBe test02StkSell -- describe "scrapingFraAstSpare" $ it "test 01" $ do html <- TL.readFile ("test/MatsuiCoJp/" ++ test01AstSpare) scrapingFraAstSpare [html] >>= shouldBe test01AstSpare'
ak1211/tractor
test/MatsuiCoJp/ScraperSpec.hs
agpl-3.0
4,180
0
16
702
532
310
222
77
1
module System.IO.PhysFS.Internal (PhysFS_FileStruct, PhysFS_File, PhysHandle(PH), PhysIOMode(..), rawOpen) where import Data.Typeable import Foreign.Ptr (Ptr) import Foreign.C (CString, withCString) data PhysFS_FileStruct deriving Typeable type PhysFS_File = Ptr PhysFS_FileStruct newtype PhysHandle = PH PhysFS_File -- |This is just like 'System.IO.IOMode', but lacking @ReadWriteMode@ as PhysicsFS does not support that mode. data PhysIOMode = PhysAppendMode | PhysReadMode | PhysWriteMode foreign import ccall "physfs.h PHYSFS_openAppend" physfsOpenAppend :: CString -> IO PhysFS_File foreign import ccall "physfs.h PHYSFS_openRead" physfsOpenRead :: CString -> IO PhysFS_File foreign import ccall "physfs.h PHYSFS_openWrite" physfsOpenWrite :: CString -> IO PhysFS_File rawOpen :: FilePath -> PhysIOMode -> IO (PhysFS_File, String) rawOpen fp mode = let (open,msg) = case mode of PhysAppendMode -> (physfsOpenAppend, "PHYSFS_openAppend") PhysReadMode -> (physfsOpenRead , "PHYSFS_openRead" ) PhysWriteMode -> (physfsOpenWrite , "PHYSFS_openWrite" ) in do h <- withCString fp open return (h, msg)
d3tucker/physfs
src/System/IO/PhysFS/Internal.hs
lgpl-3.0
1,208
0
12
241
269
153
116
-1
-1
module Data.Sequence (module X) where import "containers" Data.Sequence as X
wdanilo/container
src/Data/Sequence.hs
apache-2.0
78
0
4
11
20
14
6
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveGeneric #-} {-# LANGUAGE GADTs #-} -- | DNA monad and actor creation and communication primitives. -- -- Actors track list of nodes they own and monitor their immediate -- children. We also have to impose important limitation: children -- cannot outlive their parents. It's quite reasonable to allow it -- but at the same time it could lead to processes which hangs -- around forever because no one will request their result. We need -- some kind of distributed garbage collection to reap such -- processes. -- -- When spawned process\/group of processes returns handle for -- obtaining result of their computation. It could be serialized and -- send to other processes. module DNA.DNA ( -- * DNA monad DNA(..) , runDNA , rank , groupSize , getMonitor , logMessage , duration -- * Actors , Actor(..) , actor , CollectActor(..) , collectActor , Mapper(..) , mapper -- ** Shell actors , Shell(..) , Val , Grp , eval , evalClosure , startActor , startCollector , startGroup , startGroupN , startCollectorGroup , startCollectorGroupMR , startMappers -- * CAD & Co , CAD(..) , makeCAD , Location(..) , availableNodes , select , selectMany -- * Connecting actors , broadcast , sendParam , broadcastParamSlice , connect -- ** Promises , Promise , Group , await , gather , delay , delayGroup -- * Starting actors , runActor , runCollectActor , runACP , runMasterACP , __remoteTable , runACP__static ) where import Control.Applicative import Control.Monad import Control.Monad.Trans.Reader import Control.Monad.IO.Class import Control.Distributed.Static (closureApply) import Control.Distributed.Process import Control.Distributed.Process.Closure import Control.Distributed.Process.Serializable (Serializable) import Data.Binary (Binary) import Data.Typeable (Typeable) import GHC.Generics (Generic) import DNA.Types import DNA.Controller hiding (__remoteTable) import DNA.Logging ---------------------------------------------------------------- -- DNA monad ---------------------------------------------------------------- -- | Monad for defining DNA programs. Actors could spawn other -- actors. One important limitation is that actors cannot outlive -- their parent. Otherwise we could have processes whose results -- will be never requested and no way to reap such deadlocked -- processes. -- -- Every actor owns set of nodes on which it could spawn other actors. -- Upon completion this set of nodes is returned to parent actor. newtype DNA a = DNA (ReaderT (ACP,Rank,GroupSize) Process a) deriving (Functor,Applicative,Monad,MonadIO,MonadProcess) -- | Execute DNA program runDNA :: ACP -> Rank -> GroupSize -> DNA a -> Process a runDNA mon r grp (DNA dna) = flip runReaderT (mon,r,grp) dna -- | Get rank of process in group rank :: DNA Int rank = do (_,Rank n,_) <- DNA ask return n -- | Get size of process group groupSize :: DNA Int groupSize = do (_,_,GroupSize n) <- DNA ask return n -- | Get monitor process getMonitor :: DNA ACP getMonitor = do (acp,_,_) <- DNA ask return acp -- | Send message to actor's controller sendACP :: (Binary a, Typeable a) => a -> DNA () sendACP a = do ACP pid <- getMonitor liftP $ send pid a -- | Put message into log file logMessage :: String -> DNA () logMessage = taggedMessage "MSG" ---------------------------------------------------------------- -- Data types for actors ---------------------------------------------------------------- -- | Actor which receive messages of type @a@ and produce result of -- type @b@. It's phantom-typed and could only be constructed by -- 'actor' which ensures that types are indeed correct. data Actor a b where Actor :: (Serializable a, Serializable b) => (a -> DNA b) -> Actor a b deriving (Typeable) -- | Smart constructor for actors. Here we receive parameters and -- output channel for an actor actor :: (Serializable a, Serializable b) => (a -> DNA b) -> Actor a b actor = Actor -- | Actor which collects multiple inputs from other actors data CollectActor a b where CollectActor :: (Serializable a, Serializable b) => (s -> a -> DNA s) -> DNA s -> (s -> DNA b) -> CollectActor a b deriving (Typeable) -- | Smart constructor for collector actors. collectActor :: (Serializable a, Serializable b, Serializable s) => (s -> a -> DNA s) -> DNA s -> (s -> DNA b) -> CollectActor a b collectActor = CollectActor -- | Mapper actor. Essentially unfoldr data Mapper a b where Mapper :: (Serializable a, Serializable b, Serializable s) => (a -> DNA s) -> (s -> DNA (Maybe (s,b))) -> (Int -> b -> Int) -> Mapper a b deriving (Typeable) mapper :: (Serializable a, Serializable b, Serializable s) => (a -> DNA s) -> (s -> DNA (Maybe (s, b))) -> (Int -> b -> Int) -> Mapper a b mapper = Mapper ---------------------------------------------------------------- -- CAD ---------------------------------------------------------------- -- | Make CAD from list of nodes. At the moment w don't use any -- information about nodes. makeCAD :: [a] -> CAD a makeCAD [] = error "DNA.CAD.makeCAD: empty list of nodes" makeCAD (x:xs) = CAD x [CAD a [] | a <- xs] -- | Number of available nodes availableNodes :: DNA Int availableNodes = do sendACP ReqNumNodes liftP expect -- | Allocate N nodes to single actor select :: Location -- ^ Should actor be executed on local node or on remote one -> Res -- ^ How many nodes allocate to actor. Local node is not -- counted here. -> DNA Resources select loc n = do sendACP $ ReqResources loc n liftP expect -- | Allocate N nodes for group of actors. Each will have only single -- node selectMany :: Res -- ^ How many nodes allocate to the group -> ResGroup -- ^ How to allocate resources for individual processes in -- group -> [GrpFlag] -- ^ Additional flags which influence resource allocation -> DNA [Resources] selectMany n g f = do sendACP $ ReqResourcesGrp n g f liftP expect ---------------------------------------------------------------- -- Connect actors ---------------------------------------------------------------- -- | Send parameter to the actor sendParam :: Serializable a => a -> Shell (Val a) b -> DNA () sendParam a (Shell _ recv _) = case recv of RecvVal ch -> liftP $ sendChan ch a RecvBroadcast grp -> case grp of RecvGrp p -> liftP $ forM_ p $ \ch -> sendChan ch a -- | Broadcast same parameter to all actors in group broadcast :: Shell (Scatter a) b -> Shell (Val a) b broadcast (Shell a r s) = Shell a (RecvBroadcast r) s -- | Send parameter to the group of actors. A slicing function can -- modify the data sent to each node. broadcastParamSlice :: Serializable a => (Int -> [a]) -> Shell (Scatter a) b -> DNA () broadcastParamSlice slice (Shell _ (RecvGrp chans) _) = do zipWithM_ (\a ch -> liftP $ sendChan ch a) (slice (length chans)) chans -- | Connect output of one shell process to input of another. connect :: Serializable b => Shell a (tag b) -> Shell (tag b) c -> DNA () connect (Shell childA _ sendEnd) (Shell childB recvEnd _) = do case (sendEnd,recvEnd) of -- Val (SendVal chDst, RecvVal chB) -> do -- FIXME: Do we want to allow unsafe send here? liftP $ sendChan chDst $ SendRemote [chB] sendACP $ ReqConnect childA childB [] (SendVal chDst, RecvBroadcast (RecvGrp chans)) -> do liftP $ sendChan chDst $ SendRemote chans sendACP $ ReqConnect childA childB [] -- Grp (SendGrp chDst, RecvReduce chReduce) -> do let chB = map snd chReduce liftP $ forM_ chDst $ \ch -> sendChan ch $ SendRemote chB sendACP $ ReqConnect childA childB [chN | (chN,_) <- chReduce ] -- MR (SendMR chDst, RecvMR chans) -> do let chB = map snd chans liftP $ forM_ chDst $ \ch -> sendChan ch chB sendACP $ ReqConnect childA childB [chN | (chN,_) <- chans] -- IMPOSSIBLE -- -- GHC cannot understand that pattern match is exhaustive _ -> error "Impossible: pattern match is not exhaustive" ---------------------------------------------------------------- -- Promises ---------------------------------------------------------------- newtype Promise a = Promise (ReceivePort a) data Group a = Group (ReceivePort a) (ReceivePort Int) await :: Serializable a => Promise a -> DNA a await (Promise ch) = liftP $ receiveChan ch gather :: Serializable a => Group a -> (b -> a -> b) -> b -> DNA b gather g f = gatherM g (\b a -> return (f b a)) gatherM :: Serializable a => Group a -> (b -> a -> DNA b) -> b -> DNA b gatherM (Group chA chN) f x0 = do let loop n tot !b | n >= tot && tot >= 0= do return b loop n tot !b = do r <- liftP $ receiveWait [ matchChan chA (return . Right) , matchChan chN (return . Left) ] case r of Right a -> loop (n + 1) tot =<< f b a Left k -> loop n k b loop 0 (-1) x0 destFromLoc :: Location -> SendPort a -> Dest a destFromLoc Local = SendLocally destFromLoc Remote = SendRemote . (:[]) -- | Create promise for single actor. It allows to receive data from -- it later. delay :: Serializable b => Location -> Shell a (Val b) -> DNA (Promise b) delay loc (Shell child _ src) = do myACP <- getMonitor (chSend,chRecv) <- liftP newChan let param :: Serializable b => SendEnd (Val b) -> SendPort b -> Process () param (SendVal ch) p = sendChan ch $ destFromLoc loc p liftP $ param src chSend sendACP $ ReqConnect child (SingleActor myACP) [] return $ Promise chRecv -- | Create promise from group of processes which allows to collect -- data from them later. delayGroup :: Serializable b => Shell a (Grp b) -> DNA (Group b) delayGroup (Shell child _ src) = do myACP <- getMonitor (sendB,recvB) <- liftP newChan (sendN,recvN) <- liftP newChan let param :: Serializable b => SendEnd (Grp b) -> SendPort b -> Process () param (SendGrp chans) chB = forM_ chans $ \ch -> sendChan ch (SendRemote [chB]) liftP $ param src sendB sendACP $ ReqConnect child (SingleActor myACP) [sendN] return $ Group recvB recvN ---------------------------------------------------------------- -- Running actors -- -- We use relatively complicated algorithm for spawning actors. To -- spawn shell (not connected anywhere) actor we send message to our -- ACP which in turn spawns ACP for shell actor. -- ---------------------------------------------------------------- -- | Start execution of standard actor. runActor :: Actor a b -> Process () runActor (Actor action) = do -- Obtain parameters (acp,ParamActor parent rnk grp) <- expect -- Create channels for communication (chSendParam,chRecvParam) <- newChan (chSendDst, chRecvDst ) <- newChan -- Send shell process back let shell = Shell (SingleActor acp) (RecvVal chSendParam) (SendVal chSendDst ) send parent (acp, wrapMessage shell) -- Now we can start execution and send back data a <- receiveChan chRecvParam !b <- runDNA acp rnk grp (action a) sendToDestChan chRecvDst b -- | Run actor for group of processes which allow more than 1 task per -- actor. runActorManyRanks :: Actor a b -> Process () runActorManyRanks (Actor action) = do -- Obtain parameters (acp,ParamActor parent _ grp) <- expect -- Create channels for communication (chSendParam,chRecvParam) <- newChan (chSendDst, chRecvDst ) <- newChan (chSendRnk, chRecvRnk ) <- newChan -- Send shell process back let shell = Shell (SingleActor acp) (RecvVal chSendParam) (SendVal chSendDst ) -- Communicate back to ACP send parent (acp, chSendRnk, wrapMessage shell) a <- receiveChan chRecvParam -- Now we can start execution and send back data dst <- receiveChan chRecvDst let loop = do send parent (acp,chSendRnk) mrnk <- receiveChan chRecvRnk case mrnk of Nothing -> return () Just rnk -> do !b <- runDNA acp rnk grp (action a) sendToDest dst b send parent (acp,DoneTask) loop loop -- | Start execution of collector actor runCollectActor :: CollectActor a b -> Process () runCollectActor (CollectActor step start fini) = do -- Obtain parameters (acp,ParamActor parent rnk grp) <- expect -- Create channels for communication (chSendParam,chRecvParam) <- newChan (chSendDst, chRecvDst ) <- newChan (chSendN, chRecvN ) <- newChan -- Send shell process description back let shell = Shell (SingleActor acp) (RecvReduce [(chSendN,chSendParam)]) (SendVal chSendDst) send parent (acp, wrapMessage shell) -- Start execution of an actor !b <- runDNA acp rnk grp $ do s0 <- start s <- gatherM (Group chRecvParam chRecvN) step s0 fini s sendToDestChan chRecvDst b -- | Start execution of collector actor runCollectActorMR :: CollectActor a b -> Process () runCollectActorMR (CollectActor step start fini) = do -- Obtain parameters (acp,ParamActor parent rnk grp) <- expect -- Create channels for communication (chSendParam,chRecvParam) <- newChan (chSendDst, chRecvDst ) <- newChan (chSendN, chRecvN ) <- newChan -- Send shell process description back let shell = Shell (SingleActor acp) (RecvMR [(chSendN,chSendParam)]) (SendVal chSendDst) send parent (acp, wrapMessage shell) -- Start execution of an actor let loop n tot !b | n >= tot && tot >= 0 = return b | otherwise = do r <- liftP $ receiveWait [ matchChan chRecvParam (return . Right) , matchChan chRecvN (return . Left) ] case r of Right (Just a) -> loop n tot =<< step b a Right Nothing -> loop (n+1) tot b Left k -> loop n k b b <- runDNA acp rnk grp $ fini =<< loop 0 (-1) =<< start sendToDestChan chRecvDst b runMapperActor :: Mapper a b -> Process () runMapperActor (Mapper start step shuffle) = do -- Obtain parameters (acp,ParamActor parent rnk grp) <- expect -- Create channels for communication (chSendParam,chRecvParam) <- newChan (chSendDst, chRecvDst ) <- newChan -- Send shell process description back let shell = Shell (SingleActor acp) (RecvVal chSendParam) (SendMR [chSendDst]) send parent (acp, wrapMessage shell) -- Get initial parameters for unfolding a <- receiveChan chRecvParam s0 <- runDNA acp rnk grp $ start a -- Get destination dst <- receiveChan chRecvDst -- Unfoldr loop let n = length dst let loop s = do ms <- runDNA acp rnk grp $ step s case ms of Nothing -> return () Just (s',b) -> do let i = shuffle n b sendChan (dst !! i) (Just b) loop s' loop s0 forM_ dst $ \ch -> sendChan ch Nothing -- | Start execution of DNA program runDnaProgram :: DNA () -> Process () runDnaProgram action = do -- Obtain parameters (acp,ParamActor _ rnk grp) <- expect runDNA acp rnk grp action -- Send value to the destination sendToDestChan :: (Serializable a) => ReceivePort (Dest a) -> a -> Process () sendToDestChan chDst a = do dst <- receiveChan chDst sendToDest dst a -- Send value to the destination sendToDest :: (Serializable a) => Dest a -> a -> Process () sendToDest dst a = case dst of SendLocally ch -> unsafeSendChan ch a SendRemote chs -> forM_ chs $ \c -> sendChan c a -- | Start execution of actor controller process (ACP). Takes triple -- of actor closure, actor's rank and PID of process to send shell -- back. -- -- NOTE: again because of TH limitation we have to pass all -- parameters AND closure of this function as messages because -- we cannot create closure of our function ourselves. runACP :: Process () runACP = do taggedMessage "ACP" "Starting ACP" -- Get parameters for ACP and actor ParamACP self act resources actorP <- expect -- Start actor process nid <- getSelfNode me <- getSelfPid -- FIXME: understand how do we want to monitor state of child -- process? Do we want to just die unconditionally or maybe -- we want to do something. (pid,_) <- spawnSupervised nid act send pid (ACP me, actorP) -- Start listening on events startAcpLoop self pid resources -- FIXME: duplication runMasterACP :: ParamACP () -> DNA () -> Process () runMasterACP (ParamACP self () resources actorP) act = do taggedMessage "ACP" "Starting master ACP" -- Start actor process me <- getSelfPid -- FIXME: understand how do we want to monitor state of child -- process? Do we want to just die unconditionally or maybe -- we want to do something. pid <- spawnLocal (link me >> runDnaProgram act) _ <- monitor pid send pid (ACP me,actorP) -- Start listening on events startAcpLoop self pid resources remotable [ 'runActor , 'runActorManyRanks , 'runCollectActorMR , 'runCollectActor , 'runMapperActor , 'runACP ] ---------------------------------------------------------------- -- Shell actors ---------------------------------------------------------------- -- | Evaluate actor without forking off enother thread eval :: (Serializable a, Serializable b) => Actor a b -> a -> DNA b eval (Actor act) a = do logMessage "executing: eval" act a -- | Evaluate actor without forking off enother thread evalClosure :: (Serializable a, Serializable b) => Closure (Actor a b) -> a -> DNA b evalClosure clos a = do logMessage "executing: evalClosure" Actor act <- liftP $ unClosure clos act a -- | Start single actor startActor :: (Serializable a, Serializable b) => Resources -> Closure (Actor a b) -> DNA (Shell (Val a) (Val b)) startActor res child = do ACP acp <- getMonitor (shellS,shellR) <- liftP newChan let clos = $(mkStaticClosure 'runActor) `closureApply` child liftP $ send acp $ ReqSpawnShell clos shellS res msg <- unwrapMessage =<< liftP (receiveChan shellR) case msg of Nothing -> error "Bad shell message" Just s -> return s -- | Start single collector actor startCollector :: (Serializable a, Serializable b) => Resources -> Closure (CollectActor a b) -> DNA (Shell (Grp a) (Val b)) startCollector res child = do (shellS,shellR) <- liftP newChan let clos = $(mkStaticClosure 'runCollectActor) `closureApply` child sendACP $ ReqSpawnShell clos shellS res msg <- unwrapMessage =<< liftP (receiveChan shellR) case msg of Nothing -> error "Bad shell message" Just s -> return s -- | Start group of processes startGroup :: (Serializable a, Serializable b) => [Resources] -> GroupType -> Closure (Actor a b) -> DNA (Shell (Scatter a) (Grp b)) startGroup res groupTy child = do (shellS,shellR) <- liftP newChan let clos = $(mkStaticClosure 'runActor) `closureApply` child sendACP $ ReqSpawnGroup clos shellS res groupTy (gid,mbox) <- liftP (receiveChan shellR) msgs <- mapM unwrapMessage mbox case sequence msgs of Nothing -> error "Bad shell message" Just s -> return $ assembleShellGroup gid s assembleShellGroup :: GroupID -> [Shell (Val a) (Val b)] -> Shell (Scatter a) (Grp b) assembleShellGroup gid shells = Shell (ActorGroup gid) (RecvGrp $ map getRecv shells) (SendGrp $ map getSend shells) where getRecv :: Shell (Val a) b -> SendPort a getRecv (Shell _ (RecvVal ch) _) = ch getRecv _ = error "assembleShellGroup: unexpected type of shell process" getSend :: Shell a (Val b) -> SendPort (Dest b) getSend (Shell _ _ (SendVal ch)) = ch -- | Start group of processes where we have more tasks then processes. startGroupN :: (Serializable a, Serializable b) => [Resources] -- ^ Resources for actors -> GroupType -- ^ How individual failures should be handled -> Int -- ^ Number of tasks to run -> Closure (Actor a b) -> DNA (Shell (Val a) (Grp b)) startGroupN res groupTy nTasks child = do (shellS,shellR) <- liftP newChan let clos = $(mkStaticClosure 'runActorManyRanks) `closureApply` child sendACP $ ReqSpawnGroupN clos shellS res nTasks groupTy (gid,mbox) <- liftP (receiveChan shellR) msgs <- mapM unwrapMessage mbox case sequence msgs of Nothing -> error "Bad shell message" Just s -> return $ broadcast $ assembleShellGroup gid s -- | Start group of collector processes startCollectorGroup :: (Serializable a, Serializable b) => [Resources] -> GroupType -> Closure (CollectActor a b) -> DNA (Shell (Grp a) (Grp b)) startCollectorGroup res groupTy child = do (shellS,shellR) <- liftP newChan let clos = $(mkStaticClosure 'runCollectActor) `closureApply` child sendACP $ ReqSpawnGroup clos shellS res groupTy (gid,mbox) <- liftP (receiveChan shellR) msgs <- mapM unwrapMessage mbox case sequence msgs of Nothing -> error "Bad shell message" Just s -> return $ assembleShellGroupCollect gid s assembleShellGroupCollect :: GroupID -> [Shell (Grp a) (Val b)] -> Shell (Grp a) (Grp b) assembleShellGroupCollect gid shells = Shell (ActorGroup gid) (RecvReduce $ getRecv =<< shells) (SendGrp $ map getSend shells) where getRecv :: Shell (Grp a) b -> [(SendPort Int, SendPort a)] getRecv (Shell _ (RecvReduce ch) _) = ch getSend :: Shell a (Val b) -> SendPort (Dest b) getSend (Shell _ _ (SendVal ch)) = ch -- | Start group of collector processes startCollectorGroupMR :: (Serializable a, Serializable b) => [Resources] -> GroupType -> Closure (CollectActor a b) -> DNA (Shell (MR a) (Grp b)) startCollectorGroupMR res groupTy child = do (shellS,shellR) <- liftP newChan let clos = $(mkStaticClosure 'runCollectActorMR) `closureApply` child sendACP $ ReqSpawnGroup clos shellS res groupTy (gid,mbox) <- liftP (receiveChan shellR) msgs <- mapM unwrapMessage mbox case sequence msgs of Nothing -> error "Bad shell message" Just s -> return $ assembleShellGroupCollectMR gid s assembleShellGroupCollectMR :: GroupID -> [Shell (MR a) (Val b)] -> Shell (MR a) (Grp b) assembleShellGroupCollectMR gid shells = Shell (ActorGroup gid) (RecvMR $ getRecv =<< shells) (SendGrp $ map getSend shells) where getRecv :: Shell (MR a) b -> [(SendPort Int, SendPort (Maybe a))] getRecv (Shell _ (RecvMR ch) _) = ch getSend :: Shell a (Val b) -> SendPort (Dest b) getSend (Shell _ _ (SendVal ch)) = ch -- | Start group of mapper processes startMappers :: (Serializable a, Serializable b) => [Resources] -> GroupType -> Closure (Mapper a b) -> DNA (Shell (Scatter a) (MR b)) startMappers res groupTy child = do (shellS,shellR) <- liftP newChan let clos = $(mkStaticClosure 'runMapperActor) `closureApply` child sendACP $ ReqSpawnGroup clos shellS res groupTy (gid,mbox) <- liftP (receiveChan shellR) msgs <- mapM unwrapMessage mbox case sequence msgs of Nothing -> error "Bad shell message" Just s -> return $ assembleShellMapper gid s assembleShellMapper :: GroupID -> [Shell (Val a) (MR b)] -> Shell (Scatter a) (MR b) assembleShellMapper gid shells = Shell (ActorGroup gid) (RecvGrp $ map getRecv shells) (SendMR $ getSend =<< shells) where getRecv :: Shell (Val a) b -> SendPort a getRecv (Shell _ (RecvVal ch) _) = ch getRecv _ = error "assembleShellGroup: unexpected type of shell process" getSend :: Shell a (MR b) -> [SendPort [SendPort (Maybe b)]] getSend (Shell _ _ (SendMR ch)) = ch
SKA-ScienceDataProcessor/RC
MS2/lib/DNA/DNA.hs
apache-2.0
25,287
0
20
6,873
7,164
3,604
3,560
496
5
{-# LANGUAGE PackageImports #-} {-# LANGUAGE NoImplicitPrelude #-} {- Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} -------------------------------------------------------------------------------- -- | The standard set of functions and variables available to all programs. -- -- You may use any of these functions and variables without defining them. module Prelude ( module Internal.Exports, -- * Numbers module Internal.Num, -- * Text module Internal.Text, -- * General purpose functions module Internal.Prelude, IO, ) where import Internal.CodeWorld import Internal.Color import Internal.Event import Internal.Exports import Internal.Num import Internal.Picture import Internal.Prelude hiding (randomsFrom) import Internal.Text hiding (fromCWText, toCWText) import "base" Prelude (IO)
google/codeworld
codeworld-base/src/Prelude.hs
apache-2.0
1,388
0
5
240
108
73
35
17
0
{-# LANGUAGE FlexibleContexts #-} module Main where import Control.Applicative import Control.Lens import Text.PrettyPrint.ANSI.Leijen hiding ((<$>)) import Text.Trifecta import Language.C.Parser import Language.C.Data.Position import Language.C.Data.Node import qualified Language.C.Pretty as CPretty import Language.Gamma import Language.Gamma.Parser.Commented cAST s = (() <$) <$> parseC s nopos main :: IO () main = do putStrLn "hi" src <- getContents run src run :: String -> IO () run src = do case parseString (runCommented $ some pDecl <* eof) mempty src of (Failure err) -> print err (Success stmts) -> mapM_ doStmt stmts where doStmt stmt = do putStrLn "Statement:" print (pretty stmt) putStrLn ("AST: " ++ show stmt) case (runTyp builtinBindings (inferTypes stmt)) of Left tyErr -> putStrLn ("Type Error: " ++ show tyErr) Right typed -> do putStr "Type: " print (pretty (typed ^. annotation._2)) print typed case (runGen (codegen typed)) of Left genErr -> putStrLn ("Gen Error: " ++ show genErr) Right (r, _) -> putStrLn "Gen:" >> print (CPretty.pretty (undefNode <$ r))
agrif/gammac
src/Main.hs
apache-2.0
1,330
0
22
408
425
215
210
-1
-1
-- This is the example used in the main .cabal file. {-# LANGUAGE OverloadedStrings #-} -- Print all MAC addresses with an active client lease module Main where import Data.Ip import Data.Mac import qualified Data.Text.IO as T import System.Win32.DHCP main :: IO () main = do api <- loadDHCP clients <- enumClients api context let macs = map (showMac ":" . clientHardwareAddress) clients mapM_ T.putStrLn macs where Right subnet = readIp "192.168.1.0" context = Context "192.168.1.5" subnet
mikesteele81/Win32-dhcp-server
examples/cabal.hs
bsd-3-clause
521
0
13
107
124
65
59
14
1
{-# LANGUAGE DeriveDataTypeable #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module IS.B01 where import Control.DeepSeq (NFData(rnf)) import Common import Data.Data import qualified Data.IxSet as I import Data.IxSet ((@=), (@>=)) type IS = I.IxSet C01 newtype D1 = D1 Int deriving (Eq, Ord, Typeable) newtype D2 = D2 Int deriving (Eq, Ord , Typeable) newtype D3 = D3 Int deriving (Eq, Ord, Typeable) instance NFData D1 where rnf (D1 x) = rnf x instance NFData D2 where rnf (D2 x) = rnf x instance NFData D3 where rnf (D3 x) = rnf x instance I.Indexable C01 where empty = I.ixSet [ I.ixFun $ \(C01 oo _ _) -> [D1 oo] , I.ixFun $ \(C01 _ om _) -> [D2 om] , I.ixFun $ \(C01 _ _ mm) -> map D3 mm ] empty :: IS empty = I.empty size :: IS -> Int size = I.size insert :: C01 -> IS -> IS insert = I.insert insertLookup :: Int -> Int -> Int -> IS -> [C01] insertLookup d1 d2 d3 s = I.toList (new @= D1 d1) ++ I.toList (new @= D2 d2) ++ I.toList (new @= D3 d3) where new = I.insert (C01 d1 d2 [d3]) s lookupOOEQ :: Int -> IS -> [C01] lookupOOEQ x s = I.toList (s @= D1 x) lookupOOGE :: Int -> IS -> [C01] lookupOOGE x s = I.toList (s @>= D1 x) lookupOMEQ :: Int -> IS -> [C01] lookupOMEQ x s = I.toList (s @= D2 x) lookupOMGE :: Int -> IS -> [C01] lookupOMGE x s = I.toList (s @>= D2 x) lookupMMEQ :: Int -> IS -> [C01] lookupMMEQ x s = I.toList (s @= D3 x) force :: IS -> () force (I.IxSet ll) = seq (go ll) () where go [] = () go (I.Ix m _:xs) = m `seq` go xs
Palmik/data-store
benchmarks/src/IS/B01.hs
bsd-3-clause
1,538
0
11
392
775
410
365
49
2
{-# LANGUAGE GADTs, ScopedTypeVariables, DataKinds, FlexibleContexts, Rank2Types, ConstraintKinds, TypeFamilies, MultiParamTypeClasses, FlexibleInstances, NoMonomorphismRestriction, RecursiveDo, InstanceSigs, OverloadedStrings #-} {-# language OverloadedStrings #-} {-# language OverloadedLists #-} module UI.Lib where import Prelude hiding ((.),id, lookup) import Control.Monad (void,forM,forM_) import Control.Lens (view,(.~),(&)) import Data.GADT.Compare import Data.Dependent.Map hiding (delete)-- (DMap,DSum( (:=>) ),singleton, lookup,fromList) import Data.Text(Text,pack) import Data.Time.Clock import Control.Concurrent import Control.Monad.Trans import Control.Monad import System.Random --import Data.Either --import Control.Monad.Identity import qualified Data.Map as M --import Data.Map (Map) import Data.Semigroup import Control.Category import Data.Dependent.Map (DMap,DSum((:=>)), singleton) import qualified Data.Dependent.Map as DMap import Data.GADT.Compare (GCompare) import Reflex hiding (combineDyn) import qualified Reflex as Reflex import Reflex.Dom hiding (combineDyn) import GHC.Exts import Control.Monad.Identity (Identity) import qualified GHCJS.DOM.EventM as J import Data.IORef import Control.Monad.Trans import Data.Either import Control.Monad.Reader import Control.Monad.Identity import HList ------- reflex missings -------------- type Morph t m a = Dynamic t (m a) -> m (Event t a) mapMorph :: (MonadHold t m, Reflex t) => Morph t m (Event t b) -> (a -> m (Event t b)) -> Dynamic t a -> m (Event t b) mapMorph dyn f d = dyn (f <$> d) >>= joinE joinE :: (Reflex t, MonadHold t f) => Event t (Event t a) -> f (Event t a) joinE = fmap switch . hold never pick :: (GCompare k, Reflex t) => k a -> Event t (DMap k Identity) -> Event t a pick x r = select (fan r) x -- shouldn't we share fan r ? gateWith f = attachWithMaybe $ \allow a -> if f allow then Just a else Nothing pair x = leftmost . (: [x]) sselect = flip select ------------- Spider synonims type ES = Event Spider type DS = Dynamic Spider type BS = Behavior Spider -------------- Dom + spider synonyms type MS = MonadWidget Spider type Message a = DMap a Identity type Cable a = ES (Message a) -- specialized mapMorph for the Dom host domMorph :: MonadWidget t m => (a -> m (Event t b)) -- widget rewriter -> Dynamic t a -- driver for rewritings -> m (Event t b) -- signal the happened rewriting domMorph = mapMorph dyn -------------- create a Cable ---------- mergeDSums :: GCompare a => [DSum a ES] -> Cable a mergeDSums = merge . DMap.fromList wire' :: (GCompare k) => k v -> ES v -> Cable k wire' x = merge . singleton x wire (k :=> v) = wire' k v ------------- Lib ------------------------------------- -- | delay an Event by the amount of time specified in its value and random -- pick from chances -- -- polymorphic 2-keys type DSum data EitherG r l a where RightG :: EitherG l r r LeftG :: EitherG l r l instance GEq (EitherG r l) where RightG `geq` RightG = Just Refl LeftG `geq` LeftG = Just Refl _ `geq` _ = Nothing instance GCompare (EitherG r l) where RightG `gcompare` LeftG = GLT LeftG `gcompare` RightG = GGT RightG `gcompare` RightG = GEQ LeftG `gcompare` LeftG = GEQ -- onEithersG :: (r -> r') -> (l -> l') -> DSum (EitherG l r) f -> DSum (EitherG l' r') f onEithersG :: (r -> r') -> (l -> l') -> (forall f. Functor f => DSum (EitherG l r) f -> DSum (EitherG l' r') f) onEithersG fr fl (RightG :=> x) = RightG :=> ( fr <$> x) onEithersG fr fl (LeftG :=> x) = LeftG :=> (fl <$> x) -- eithersG :: (r -> r') -> (l -> l') -> DSum (EitherG l r) ES -> DSum (EitherG l' r') ES -- eithersG = onEithersG rightG b = wire (RightG :=> b) leftG b = wire (LeftG :=> b) instance GCompare k => IsList (DMap k f) where type Item (DMap k f) = DSum k f fromList = Data.Dependent.Map.fromList toList = Data.Dependent.Map.toList ------------------------------------------- righting e = (\(Right x) -> x) <$> ffilter isRight e lefting e = (\(Left x) -> x) <$> ffilter isLeft e ---------------------------------------- class HasInput m a where getInput :: m (DS (Maybe a)) class HasIcons m a where getIcon :: a -> m (ES ()) icon :: (MS m, MonadReader (DS r) m, In Bool r) => [Text] -> Text -> m (ES ()) icon xs t =divClass "icon-box" $ do (r,_) <- divClass "icon" $ elAttr' "i" [("class",foldl (\y x -> y <> " fa-" <> x ) "fa" xs)] $ return () asks (fmap see) >>= domMorph (\q -> if q then divClass "hints" (text t) >> return never else return never ) return $ domEvent Click r composeIcon :: (MonadReader (DS r) m, In Bool r, MS m) => m (ES a) -> m (ES a) -> m (ES a) composeIcon x y = fmap leftmost . divClass "compose" . sequence $ [ divClass "compose-x" x, divClass "compose-plus" (icon ["plus","2x"] "or") >> return never, divClass "compose-y" y ] data Iconified = Iconified | Disclosed floater x = do t <- asks (fmap see) elDynAttr "div" ((\t -> M.singleton "class" (if t then "combo-containerHints" else "combo-container")) <$> t ) . divClass "combo-buttons" $ x check c f = if c then f else return never
paolino/book-a-visit
client/UI/Lib.hs
bsd-3-clause
5,205
0
18
1,064
1,834
988
846
101
2
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} module Hop.Apps.Juno.JsonTypes where import Control.Applicative import Control.Monad (mzero) import Data.Aeson as JSON import Data.Aeson.Types (Options(..),parseMaybe) import Data.Char (isSpace) import Data.Ratio import qualified Data.Text as T import Data.Text.Encoding as E import Data.Text (Text) import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Lazy.Char8 as BLC import GHC.Generics import Text.Read (readMaybe) import Juno.Types (CommandStatus(..),CommandResult(..),RequestId(..)) newtype JRational = JRational { jratio :: Ratio Integer } deriving (Eq, Generic, Show) -- Typeclass for Rational to encode and decode to and from JRational -> (10%1) -- instead of the Aeson Rational Typeclass {"numerator":n, "denominator":d} -- -- JSON.decode $ BLC.pack "\"10%1\"" :: Maybe JRational instance FromJSON JRational where parseJSON = JSON.withText "Rational n%d" $ \obj -> do nums <- mapM parseNum $ numStrs obj parseRational nums where numStrs s = T.unpack <$> T.splitOn "%" s parseNum str = case readMaybe str of Nothing -> fail $ "found notanum: " ++ str Just num -> return num parseRational nums = case nums of [x, y] -> return $ JRational (x % y) _ -> fail "found the wrong number of args to a rational! Should be in form n%d." instance ToJSON JRational where toJSON (JRational r) = String $ (T.pack . removeSpaces . show) r where removeSpaces str = filter (not . isSpace) str {-# INLINE toJSON #-} removeUnderscore :: String -> String removeUnderscore = drop 1 data Digest = Digest { _hash :: Text, _key :: Text } deriving (Eq, Generic, Show) instance ToJSON Digest where toJSON = genericToJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } instance FromJSON Digest where parseJSON = genericParseJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } newtype AccountPayload = AccountPayload { _account :: Text } deriving (Eq, Generic, Show) instance ToJSON AccountPayload where toJSON = genericToJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } instance FromJSON AccountPayload where parseJSON = genericParseJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } data CreateAccountRequest = CreateAccountRequest { _payload :: AccountPayload, _digest :: Digest } deriving (Eq, Generic, Show) instance ToJSON CreateAccountRequest where toJSON = genericToJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } instance FromJSON CreateAccountRequest where parseJSON = genericParseJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } data CommandResponse = CommandResponse { _status :: Text , _cmdid :: Text , _message :: Text } deriving (Eq, Generic, Show) instance ToJSON CommandResponse where toJSON = genericToJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } instance FromJSON CommandResponse where parseJSON = genericParseJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } commandResponseSuccess :: Text -> Text -> CommandResponse commandResponseSuccess cid msg = CommandResponse "Success" cid msg commandResponseFailure :: Text -> Text -> CommandResponse commandResponseFailure cid msg = CommandResponse "Failure" cid msg -- | AccountAdjust adding/substracting money from and existing account -- { "payload": { "account": "TSLA", "amount": 100%1 }, "digest": { "hash": "myhash", "key": "string" } } data AccountAdjustPayload = AccountAdjustPayload { _adjustAccount :: Text , _adjustAmount :: JRational } deriving (Eq, Generic, Show) instance ToJSON AccountAdjustPayload where toJSON (AccountAdjustPayload account amount) = object ["account" .= account , "amount" .= amount] instance FromJSON AccountAdjustPayload where parseJSON (Object v) = AccountAdjustPayload <$> v .: "account" <*> v .: "amount" parseJSON _ = mzero data AccountAdjustRequest = AccountAdjustRequest { _adjustAccountPayload :: AccountAdjustPayload, _adjustAccountDigest :: Digest } deriving (Eq, Generic, Show) instance ToJSON AccountAdjustRequest where toJSON (AccountAdjustRequest payload' digest') = object ["payload" .= payload' , "digest" .= digest'] instance FromJSON AccountAdjustRequest where parseJSON (Object v) = AccountAdjustRequest <$> v .: "payload" <*> v .: "digest" parseJSON _ = mzero -- | Polling for commands newtype PollPayload = PollPayload { _cmdids :: [Text] } deriving (Eq, Generic, Show) instance ToJSON PollPayload where toJSON = genericToJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } instance FromJSON PollPayload where parseJSON = genericParseJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } data PollPayloadRequest = PollPayloadRequest { _pollPayload :: PollPayload, _pollDigest :: Digest } deriving (Eq, Generic, Show) instance ToJSON PollPayloadRequest where toJSON (PollPayloadRequest payload' digest') = object ["payload" .= payload' , "digest" .= digest'] instance FromJSON PollPayloadRequest where parseJSON (Object v) = PollPayloadRequest <$> v .: "payload" <*> v .: "digest" parseJSON _ = mzero -- { -- "results": [ -- { -- "status": "PENDING", -- "cmdid": "string", -- "logidx": "string", -- "message": "string", -- "payload": {} -- } -- ] -- } data PollResult = PollResult { _pollStatus :: Text , _pollCmdId :: Text , _logidx :: Int , _pollMessage :: Text , _pollResPayload :: Text } deriving (Eq, Generic, Show, FromJSON) instance ToJSON PollResult where toJSON (PollResult status cmdid logidx msg payload') = object [ "status" .= status , "cmdid" .= cmdid , "logidx" .= logidx , "message" .= msg , "payload" .= payload' ] -- TODO: logindex, payload after Query/Observe Accounts is added. cmdStatus2PollResult :: RequestId -> CommandStatus -> PollResult cmdStatus2PollResult (RequestId rid) CmdSubmitted = PollResult{_pollStatus = "PENDING", _pollCmdId = toText rid, _logidx = -1, _pollMessage = "", _pollResPayload = ""} cmdStatus2PollResult (RequestId rid) CmdAccepted = PollResult{_pollStatus = "PENDING", _pollCmdId = toText rid, _logidx = -1, _pollMessage = "", _pollResPayload = ""} cmdStatus2PollResult (RequestId rid) (CmdApplied (CommandResult res) _) = PollResult{_pollStatus = "ACCEPTED", _pollCmdId = toText rid, _logidx = -1, _pollMessage = "", _pollResPayload = decodeUtf8 res} cmdStatusError :: PollResult cmdStatusError = PollResult { _pollStatus = "ERROR" , _pollCmdId = "errorID" , _logidx = -1 , _pollMessage = "nothing to say" , _pollResPayload = "no payload" } toText :: Show a => a -> Text toText = T.pack . show newtype PollResponse = PollResponse { _results :: [PollResult] } deriving (Eq, Generic, Show) instance ToJSON PollResponse where toJSON = genericToJSON $ defaultOptions { fieldLabelModifier = removeUnderscore } -- { -- "payload": { -- "filter": "string" -- }, -- "digest": { -- "hash": "string", -- "key": "string" -- } data QueryJson = QueryJson { _queryAcct :: Maybe Text , _queryTx :: Maybe Integer , _querySender :: Maybe Text , _queryReceiver :: Maybe Text } deriving (Eq, Generic, Show) instance ToJSON QueryJson where toJSON (QueryJson acct tx sender receiver) = object [ "account" .= Just acct , "tx" .= Just tx , "sender" .= Just sender , "receiver" .= Just receiver ] instance FromJSON QueryJson where parseJSON (Object v) = QueryJson <$> v .: "account" <*> v .: "tx" <*> v .: "sender" <*> v .: "receiver" parseJSON _ = mzero newtype LedgerQueryBody = LedgerQueryBody { _filter :: QueryJson } deriving (Show, Generic, Eq) instance ToJSON LedgerQueryBody where toJSON (LedgerQueryBody fil) = object ["filter" .= fil] instance FromJSON LedgerQueryBody where parseJSON (Object v) = LedgerQueryBody <$> v .: "filter" parseJSON _ = mzero data LedgerQueryRequest = LedgerQueryRequest { payload :: LedgerQueryBody, digest :: Digest } deriving (Show, Generic, Eq) instance ToJSON LedgerQueryRequest where toJSON (LedgerQueryRequest payload' digest') = object ["payload" .= payload', "digest" .= digest'] instance FromJSON LedgerQueryRequest where parseJSON (Object v) = LedgerQueryRequest <$> v .: "payload" <*> v .: "digest" parseJSON _ = mzero -- Transact -- -- "payload": { -- "code": "string", -- "data": {} -- }, -- "digest": { -- "hash": "string", -- "key": "string" -- } -- {"data":"","code":"transfer(000->100->101->102->103->003, 100%1)"} data TransactBody = TransactBody { _txCode :: Text, _txData :: Text } deriving (Show, Eq) instance ToJSON TransactBody where toJSON (TransactBody code txData) = object ["code" .= code, "data" .= txData] instance FromJSON TransactBody where parseJSON (Object v) = TransactBody <$> v .: "code" <*> v .: "data" parseJSON _ = mzero data TransactRequest = TransactRequest { _txPayload :: TransactBody , _txDigest :: Digest } deriving (Show, Eq) instance ToJSON TransactRequest where toJSON (TransactRequest payload' digest') = object ["payload" .= payload' , "digest" .= digest'] instance FromJSON TransactRequest where parseJSON (Object v) = TransactRequest <$> v .: "payload" <*> v .: "digest" parseJSON _ = mzero -- { -- "payload": { -- "cmds": ["string"] -- }, -- "digest": { -- "hash": "string", -- "key": "string" -- } newtype CommandBatch = CommandBatch { _batchCmds :: [Text] } deriving (Eq,Show,Ord) instance ToJSON CommandBatch where toJSON (CommandBatch cmds) = object ["cmds" .= cmds] instance FromJSON CommandBatch where parseJSON (Object v) = CommandBatch <$> v .: "cmds" parseJSON _ = mzero data CommandBatchRequest = CommandBatchRequest { cmdBatchpayload :: CommandBatch, cmdBatchdigest :: Digest } deriving (Show, Generic, Eq) instance ToJSON CommandBatchRequest where toJSON (CommandBatchRequest payload' digest') = object ["payload" .= payload' , "digest" .= digest'] instance FromJSON CommandBatchRequest where parseJSON (Object v) = CommandBatchRequest <$> v .: "payload" <*> v .: "digest" parseJSON _ = mzero mJsonBsToCommand :: BLC.ByteString -> Maybe BSC.ByteString mJsonBsToCommand bs = JSON.decode bs >>= \v -> (mAdjustAccount <$> tryParse v) <|> (mAdjustCreateAcct <$> tryParse v) <|> (mtransact <$> tryParse v) where tryParse v = parseMaybe parseJSON v mAdjustAccount (AccountAdjustPayload acct amt) = let JRational r = amt in BSC.pack $ "AdjustAccount " ++ T.unpack acct ++ " " ++ show r mAdjustCreateAcct (AccountPayload acct) = BSC.pack $ "CreateAccount " ++ T.unpack acct mtransact (TransactBody code _) = BSC.pack $ T.unpack code --
haroldcarr/juno
z-no-longer-used/src/Hop/Apps/Juno/JsonTypes.hs
bsd-3-clause
12,334
0
14
3,408
2,851
1,572
1,279
228
1
-- vim:set foldenable foldmethod=marker foldcolumn=2: {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE UnicodeSyntax #-} {-# OPTIONS_GHC -Wall -fno-warn-missing-signatures #-} module GoodData.REST.Types.Basic where import Data.Aeson ( parseJSON, FromJSON, toJSON, ToJSON, Value ) import Data.Data ( Data(..), Typeable, Typeable1, mkNoRepType, gcast1 ) import Data.Text ( Text ) import Prelude hiding ( id, (.) ) import Util.JSON newtype BOOLEAN = -- {{{ BOOLEAN { fromBOOLEAN ∷ Bool } deriving ( Show, Read, Eq, Ord, Enum, Bounded, Data, Typeable ) instance FromJSON BOOLEAN where parseJSON x = (BOOLEAN . toEnum) `fmap` parseJSON x instance ToJSON BOOLEAN where toJSON = toJSON . fromEnum . fromBOOLEAN instance Json BOOLEAN where grammar = liftAeson -- }}} newtype INT = -- {{{ INT { fromINT ∷ Int } deriving ( Show, Read, Eq, Ord, Enum, Bounded, Num, Integral, Real, Data, Typeable ) isoINT = $(deriveIsos ''INT) instance Json INT where grammar = isoINT . liftAeson -- }}} type DATETIME = STRING -- FIXME type PROFILEURI = URISTRING type STRING = Text type TAGS = STRING type UNIMPLEMENTED = Value type URISTRING = String data URI a = -- {{{ URIType a ⇒ URI URISTRING (Maybe a) type URIType a = ( Json a, Typeable a, Data a, Eq a, Ord a, Show a, Read a ) deriving instance Show (URI a) deriving instance URIType a ⇒ Read (URI a) deriving instance Eq (URI a) deriving instance Ord (URI a) deriving instance Typeable1 URI instance ( Typeable a, Data a ) ⇒ Data (URI a) where toConstr _ = error "toConstr" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "GoodData.REST.Types.Basic.URI" dataCast1 x = gcast1 x isoURI = Iso f g where f (x :- t) = Just (URI x Nothing :- t) g (URI x _ :- t) = Just (x :- t) instance URIType a ⇒ Json (URI a) where grammar = isoURI . grammar -- }}}
liskin/gooddata-haskell
GoodData/REST/Types/Basic.hs
bsd-3-clause
2,147
0
10
436
666
370
296
-1
-1
module Environment ( IOThrowsError, Env, nullEnv, liftThrows, runIOThrows, isBound, getVar, setVar, defineVar, bindVars, ) where import Data.IORef import LispVal import Control.Monad.Except type Env = IORef [(String, IORef LispVal)] nullEnv :: IO Env nullEnv = newIORef [] type IOThrowsError = ExceptT LispError IO liftThrows :: ThrowsError a -> IOThrowsError a liftThrows (Left err) = throwError err liftThrows (Right val) = return val runIOThrows :: IOThrowsError String -> IO String runIOThrows action = runExceptT (trapError action) >>= return . extractValue isBound :: Env -> String -> IO Bool isBound envRef var = readIORef envRef >>= return . maybe False (const True) . lookup var getVar :: Env -> String -> IOThrowsError LispVal getVar envRef var = do env <- liftIO $ readIORef envRef maybe (throwError $ UnboundVar "Getting an unbound variable" var) (liftIO . readIORef) (lookup var env) setVar :: Env -> String -> LispVal -> IOThrowsError LispVal setVar envRef var value = do env <- liftIO $ readIORef envRef maybe (throwError $ UnboundVar "Setting an unbound variable" var) (liftIO . (flip writeIORef value)) (lookup var env) return value defineVar :: Env -> String -> LispVal -> IOThrowsError LispVal defineVar envRef var value = do alreadyDefined <- liftIO $ isBound envRef var if alreadyDefined then setVar envRef var value >> return value else liftIO $ do valueRef <- newIORef value env <- readIORef envRef writeIORef envRef ((var, valueRef) : env) return value bindVars :: Env -> [(String, LispVal)] -> IO Env bindVars envRef bindings = readIORef envRef >>= extendEnv bindings >>= newIORef where extendEnv bindings env = liftM (++ env) (mapM addBinding bindings) addBinding (var, value) = do ref <- newIORef value return (var, ref)
mhcurylo/scheme-haskell-tutorial
src/Environment.hs
bsd-3-clause
2,147
0
14
672
657
328
329
52
2
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-| This module allows you to use the auth snaplet with your user database stored in a groundhog database. When you run your application with this snaplet, a config file will be copied into the the @snaplets/groundhog-auth@ directory. This file contains all of the configurable options for the snaplet and allows you to change them without recompiling your application. To use this snaplet in your application enable the session, groundhog, and auth snaplets as follows: > data App = App > { ... -- your own application state here > , _sess :: Snaplet SessionManager > , _db :: Pool Postgresql > , _auth :: Snaplet (AuthManager App) > } Then in your initializer you'll have something like this: > conf <- getSnapletUserConfig > let cfg = subconfig "postgres" conf > connstr <- liftIO $ getConnectionString cfg > ghPool <- liftIO $ withPostgresqlPool (toS connstr) 3 return > liftIO $ runNoLoggingT (withConn (runDbPersist migrateDB) ghPool) > > a <- nestSnaplet "auth" auth $ initGroundhogAuth sess ghPool If you have not already created the database table for users, it will automatically be created for you the first time you run your application. -} module Server.GroundhogAuth ( initGroundhogAuth , getConnectionString ) where ------------------------------------------------------------------------------ import Prelude import Control.Applicative import qualified Control.Exception as E import Control.Monad.Trans.Control import Control.Monad.Logger import Control.Monad.Trans import Data.ByteString (ByteString) import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Builder as TB import qualified Data.Text.Lazy.Builder.Int as TB import qualified Data.Text.Lazy.Builder.RealFloat as TB import qualified Data.Configurator as C import qualified Data.Configurator.Types as C import Data.Monoid ((<>)) import Data.Pool import Data.Ratio (numerator, denominator) import Data.Readable import qualified Data.Text as T import qualified Data.Text.Encoding as T import Database.Groundhog import Database.Groundhog.Core import Database.Groundhog.Generic import Database.Groundhog.Postgresql import Database.Groundhog.TH import Snap import Snap.Snaplet.Auth import Snap.Snaplet.Session import Web.ClientSession (getKey) --import Paths_snaplet_groundhog_simple ------------------------------------------------------------------------------ instance NeverNull UserId instance NeverNull Password instance PersistField UserId where persistName _ = "UserId" toPersistValues (UserId bs) = primToPersistValue bs fromPersistValues pvs = do (a,vs) <- primFromPersistValue pvs return (UserId a, vs) dbType _ _ = DbTypePrimitive DbString False Nothing Nothing instance PrimitivePersistField UserId where toPrimitivePersistValue (UserId a) = toPrimitivePersistValue a fromPrimitivePersistValue v = UserId $ fromPrimitivePersistValue v instance PersistField Password where persistName _ = "HashedPassword" toPersistValues pw = case pw of Encrypted bs -> primToPersistValue $ T.decodeUtf8 bs ClearText _ -> error "Attempted to write ClearText password to the database" fromPersistValues pvs = do (a,vs) <- primFromPersistValue pvs return (Encrypted $ T.encodeUtf8 a, vs) dbType _ _ = DbTypePrimitive DbString False Nothing Nothing mkPersist (defaultCodegenConfig { namingStyle = lowerCaseSuffixNamingStyle }) [groundhog| - entity: AuthUser dbName: snap_auth_user constructors: - name: AuthUser fields: - name: userId - name: userLogin - name: userEmail - name: userPassword - name: userActivatedAt - name: userSuspendedAt - name: userRememberToken - name: userLoginCount - name: userFailedLoginCount - name: userLockedOutUntil - name: userCurrentLoginAt - name: userLastLoginAt - name: userCurrentLoginIp - name: userLastLoginIp - name: userCreatedAt - name: userUpdatedAt - name: userResetToken - name: userResetRequestedAt - name: userRoles converter: showReadConverter - name: userMeta converter: showReadConverter |] data GroundhogAuthManager = GroundhogAuthManager { gamPool :: Pool Postgresql } ------------------------------------------------------------------------------ -- | Initializer for the groundhog backend to the auth snaplet. -- initGroundhogAuth :: SnapletLens b SessionManager -- ^ Lens to the session snaplet -> Pool Postgresql -- ^ The groundhog snaplet -> SnapletInit b (AuthManager b) initGroundhogAuth sess pool = makeSnaplet "groundhog-auth" desc datadir $ do authSettings :: AuthSettings <- authSettingsFromConfig key <- liftIO $ getKey (asSiteKey authSettings) let manager = GroundhogAuthManager pool -- let migrateDB = runMigration $ migrate (undefined :: AuthUser) -- liftIO $ runNoLoggingT (withPostgresqlPool (runDbPersist migrateDB) pool) -- liftIO $ withPostgresqlPool authSettings pool _ rng <- liftIO mkRNG return $ AuthManager { backend = manager , session = sess , activeUser = Nothing , minPasswdLen = asMinPasswdLen authSettings , rememberCookieName = asRememberCookieName authSettings , rememberCookieDomain = Nothing , rememberPeriod = asRememberPeriod authSettings , siteKey = key , lockout = asLockout authSettings , randomNumberGenerator = rng } where desc = "A Groundhog backend for user authentication" datadir = Nothing --Just $ liftM (++"/resources/auth") getDataDir onFailure :: Monad m => E.SomeException -> m (Either AuthFailure a) onFailure e = return $ Left $ AuthError $ show e setUid :: DefaultKey AuthUser -> AuthUser -> AuthUser setUid k u = u { userId = Just $ UserId $ T.pack $ show $ keyToInt k } runGH :: (MonadBaseControl IO m, MonadIO m) => Pool Postgresql -> DbPersist Postgresql (NoLoggingT m) a -> m a runGH pool action = undefined -- runNoLoggingT (withConn (runDbPersist action) pool) ------------------------------------------------------------------------------ -- | instance IAuthBackend GroundhogAuthManager where save GroundhogAuthManager{..} u@AuthUser{..} = do case fromText . unUid =<< userId of Nothing -> do k <- runGH gamPool $ insert u return $ Right $ setUid k u Just uid -> do let go = runGH gamPool $ do replace (intToKey uid) u >> return (Right u) E.catch go onFailure lookupByUserId GroundhogAuthManager{..} uid = do case fromText (unUid uid) of Nothing -> return Nothing Just keyInt -> do let key = intToKey keyInt mu <- runGH gamPool $ get key return $ setUid key <$> mu lookupByLogin GroundhogAuthManager{..} login = do res <- runGH gamPool $ project (AutoKeyField, AuthUserConstructor) (UserLoginField ==. login) case res of [] -> return Nothing (k,u):_ -> return $ Just $ setUid k u lookupByRememberToken GroundhogAuthManager{..} token = do res <- runGH gamPool $ project (AutoKeyField, AuthUserConstructor) (UserRememberTokenField ==. Just token) case res of [] -> return Nothing (k,u):_ -> return $ Just $ setUid k u destroy GroundhogAuthManager{..} AuthUser{..} = do runGH gamPool $ delete (UserLoginField ==. userLogin) pg :: proxy Postgresql pg = undefined ------------------------------------------------------------------------------- keyToInt :: (PrimitivePersistField (Key a b)) => Key a b -> Int keyToInt = keyToIntegral ------------------------------------------------------------------------------- -- | Convert 'Key' to any integral type. keyToIntegral :: (PrimitivePersistField i, PrimitivePersistField (Key a b)) => Key a b -> i keyToIntegral = fromPrimitivePersistValue . toPrimitivePersistValue ------------------------------------------------------------------------------- -- | Type specialized input for type inference convenience. intToKey :: (PrimitivePersistField (Key a b)) => Int -> Key a b intToKey = integralToKey ------------------------------------------------------------------------------- -- | Convert any integral type to 'Key' integralToKey :: (PrimitivePersistField i, PrimitivePersistField (Key a b)) => i -> Key a b integralToKey = fromPrimitivePersistValue . toPrimitivePersistValue getConnectionString :: C.Config -> IO ByteString getConnectionString config = do let params = [ ["host"] , ["hostaddr"] , ["port"] , ["dbname","db"] , ["user"] , ["password","pass"] , ["connection_timeout"] , ["client_encoding"] , ["options"] , ["application_name"] , ["fallback_application_name"] , ["keepalives"] , ["keepalives_idle"] , ["keepalives_interval"] , ["keepalives_count"] , ["sslmode"] , ["sslcompression"] , ["sslcert"] , ["sslkey"] , ["sslrootcert"] , ["sslcrl"] , ["requirepeer"] , ["krbsrvname"] , ["gsslib"] , ["service"] ] connstr <- fmap mconcat $ mapM showParam params extra <- fmap TB.fromText $ C.lookupDefault "" config "connectionString" return $! T.encodeUtf8 (TL.toStrict (TB.toLazyText (connstr <> extra))) where qt = TB.singleton '\'' bs = TB.singleton '\\' sp = TB.singleton ' ' eq = TB.singleton '=' lookupConfig = foldr (\name names -> do mval <- C.lookup config name case mval of Nothing -> names Just _ -> return mval) (return Nothing) showParam [] = undefined showParam names@(name:_) = do mval :: Maybe C.Value <- lookupConfig names let key = TB.fromText name <> eq case mval of Nothing -> return mempty Just (C.Bool x) -> return (key <> showBool x <> sp) Just (C.String x) -> return (key <> showText x <> sp) Just (C.Number x) -> return (key <> showNum x <> sp) Just (C.List _) -> return mempty showBool x = TB.decimal (fromEnum x) nd ratio = (numerator ratio, denominator ratio) showNum (nd -> (n,1)) = TB.decimal n showNum x = TB.formatRealFloat TB.Fixed Nothing ( fromIntegral (numerator x) / fromIntegral (denominator x) :: Double ) showText x = qt <> loop x where loop (T.break escapeNeeded -> (a,b)) = TB.fromText a <> case T.uncons b of Nothing -> qt Just (c,b') -> escapeChar c <> loop b' escapeNeeded c = c == '\'' || c == '\\' escapeChar c = case c of '\'' -> bs <> qt '\\' -> bs <> bs _ -> TB.singleton c
CBMM/CBaaS
cbaas-server/exec/Server/GroundhogAuth.hs
bsd-3-clause
12,061
0
22
3,371
2,428
1,277
1,151
225
11
module MusicTest where import Haskore.Music import Haskore.Melody import Haskore.Basic.Pitch import Haskore.Basic.Duration import Data.List as L import Snippet -- goal arrange_melody 1 m1 m2 = [m1, m2, m2] arrange_melody 2 m1 m2 = [m2, m1, m2] arrange_melody 3 m1 m2 = [m2, m2, m1] combine_melody = line . L.intersperse hnr make_test n m1 m2 = combine_melody $ arrange_melody n m1 m2 pitch_line = line . map ( \x -> x o en () ) where o = 1 :: Octave main = render_to "music_test.midi" $ make_test 2 (pitch_line [c,d,c]) (pitch_line [c,d,e])
nfjinjing/haskore-guide
src/music_test.hs
bsd-3-clause
561
0
10
110
225
127
98
14
1
{-# LANGUAGE OverloadedStrings #-} module Agon.Data( uuids, list, get, create, update, delete ) where import Agon.Types import Agon.Instances import Agon.Agon import Agon.APIConstructors import Agon.Data.Types import Agon.Data.Instances import Agon.HTTP import Control.Lens ((&), (.~), set, view) import Data.Aeson import Servant --- --- Generalised accessors --- uuids :: Int -> AppM [String] uuids n = do url <- viewA agonCouchBaseURL >>= return . (++ ("_uuids?count=" ++ show n)) req <- buildReq url "GET" noBody httpJSON req >>= return . unUUIDs where unUUIDs (UUIDs sx) = sx list :: (Entity e, FromJSON e) => String -> Maybe String -> AppM [e] list tag mkey = do url <- viewURL tag mkey req <- buildReq url "GET" noBody fmap (fmap cliItem . clItems) $ httpJSON req get :: (Entity e, FromJSON e) => String -> AppM e get eid = do url <- docURL eid req <- buildReq url "GET" noBody httpJSON req create :: (Entity e, ToJSON e) => e -> AppM e create e = do uuid <- fmap head $ uuids 1 let e' = set (entityID e) uuid e update e' update :: (Entity e, ToJSON e) => e -> AppM e update e = do url <- docURL (view (entityID e) e) req <- buildReq url "PUT" (Just e) res <- httpJSON req return $ e & (entityRev e) .~ (Just $ curRev res) delete :: String -> String -> AppM () delete eid rev = do url <- viewA agonCouchDBURL >>= return . (++ (eid ++ "?rev=" ++ rev)) req <- buildReq url "DELETE" noBody http' req --- --- --- viewURL :: String -> Maybe String -> AppM String viewURL tag mkey = viewA agonCouchDBURL >>= return . (++ ("_design/agon/_view/" ++ tag ++ keyStr)) where keyStr = case mkey of Nothing -> "" (Just k) -> "?key=" ++ k docURL :: String -> AppM String docURL eid = viewA agonCouchDBURL >>= return . (++ eid) noBody :: Maybe () noBody = Nothing
Feeniks/Agon
app/Agon/Data.hs
bsd-3-clause
1,896
0
12
465
780
395
385
59
2
{-# LANGUAGE OverloadedStrings #-} module Snap.Handlers.Param where import Snap.Core hiding (getParam) import Control.Monad ((<=<)) --import Control.Exception (throw) import Data.Functor ((<$>)) import Data.Maybe (listToMaybe) import Data.Monoid import Data.Text hiding (head) import Data.Text.Encoding as T import Data.ByteString (ByteString) import Safe ---------------------------------------------------------------------- getParam :: ByteString -> Request -> Maybe ByteString getParam name = listToMaybe <=< rqParam name textParam :: MonadSnap m => ByteString -> m (Maybe Text) textParam name = fmap T.decodeUtf8 <$> withRequest (return . getParam name) readParam :: (MonadSnap m, Read a) => ByteString -> m (Maybe a) readParam name = do x <- fmap unpack <$> textParam name return $ readMay =<< x intParam :: MonadSnap m => ByteString -> m (Maybe Int) intParam = readParam modelH :: MonadSnap m => (ByteString -> m (Maybe a)) -> ByteString -> (a -> m (Maybe b)) -> (b -> m ()) -> m () modelH paramExtractor name model handler = maybe pass handler =<< maybe (return Nothing) model =<< paramExtractor name textModelH :: MonadSnap m => ByteString -> (Text -> m (Maybe a)) -> (a -> m ()) -> m () textModelH = modelH textParam readModelH :: (MonadSnap m, Read r) => ByteString -> (r -> m (Maybe a)) -> (a -> m ()) -> m () readModelH = modelH readParam intModelH :: MonadSnap m => ByteString -> (Int -> m (Maybe a)) -> (a -> m ()) -> m () intModelH = modelH intParam redirectToSelf :: MonadSnap m => m () redirectToSelf = redirect =<< withRequest (return . rqURI)
cimmanon/snap-handlers
Snap/Handlers/Param.hs
bsd-3-clause
1,579
2
13
264
636
327
309
32
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} module Opaleye.Trans.Exception ( OpaleyeT (..) , runOpaleyeT , -- * Transactions Transaction , transaction , run , -- * Queries query , queryFirst , -- * Inserts insert , insertMany , insertReturning , insertReturningFirst , insertManyReturning , -- * Updates update , updateReturning , updateReturningFirst , -- * Deletes delete , -- * Exceptions withExceptOpaleye , withExceptTrans , -- * Utilities withError , withoutError , liftError , withTrans , maybeError , -- * Reexports liftIO , MonadIO , ask , Int64 , throwError , catchError ) where import Control.Exception (catch, throw) import Control.Monad.Except (ExceptT (..), MonadError, catchError, runExceptT, throwError, withExceptT) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Reader (MonadReader (..)) import Control.Monad.Trans (MonadTrans (..)) import Control.Monad.Catch (MonadCatch, MonadThrow) import Data.Profunctor.Product.Default (Default) import Database.PostgreSQL.Simple (Connection) import qualified Database.PostgreSQL.Simple as PSQL import GHC.Int (Int64) import Opaleye import qualified Opaleye.Trans as T newtype OpaleyeT e m a = OpaleyeT { unOpaleyeT :: ExceptT e (T.OpaleyeT m) a } deriving ( Functor, Applicative, Monad, MonadIO, MonadReader Connection , MonadError e, MonadCatch, MonadThrow ) instance MonadTrans (OpaleyeT e) where lift = OpaleyeT . lift . lift withOpaleye :: Monad m => T.OpaleyeT m a -> OpaleyeT e m a withOpaleye = OpaleyeT . lift -- | Given a 'Connection', run an 'OpaleyeT' runOpaleyeT :: PSQL.Connection -> OpaleyeT e m a -> m (Either e a) runOpaleyeT c = T.runOpaleyeT c . runExceptT . unOpaleyeT withExceptOpaleye :: Functor m => (e -> e') -> OpaleyeT e m a -> OpaleyeT e' m a withExceptOpaleye f = OpaleyeT . withExceptT f . unOpaleyeT -- | Just like 'T.Transaction' only with exception handling newtype Transaction e a = Transaction { unTransaction :: ExceptT e T.Transaction a } deriving (Functor, Applicative, Monad, MonadReader Connection, MonadError e) withExceptTrans :: (e -> e') -> Transaction e a -> Transaction e' a withExceptTrans f = Transaction . withExceptT f . unTransaction withError :: Monad m => T.OpaleyeT m (Either e a) -> OpaleyeT e m a withError f = withOpaleye f >>= either throwError return withoutError :: Monad m => OpaleyeT e m a -> T.OpaleyeT m (Either e a) withoutError = runExceptT . unOpaleyeT liftError :: Monad m => (T.Transaction (Either e a) -> T.OpaleyeT m (Either r b)) -> Transaction e a -> OpaleyeT r m b liftError f = withError . f . runExceptT . unTransaction -- | Run a postgresql transaction in the 'OpaleyeT' monad transaction :: MonadIO m => Transaction e a -> OpaleyeT e m a transaction = liftError T.transaction -- | Execute a query without a literal transaction run :: MonadIO m => Transaction e a -> OpaleyeT e m a run = liftError T.run withTrans :: T.Transaction a -> Transaction e a withTrans = Transaction . lift -- | Execute a 'Query'. See 'runQuery'. query :: Default QueryRunner a b => Query a -> Transaction e [b] query = withTrans . T.query maybeError :: T.Transaction (Maybe b) -> e -> Transaction e b maybeError f e = withTrans f >>= maybe (throwError e) return -- | Retrieve the first result from a 'Query'. Similar to @listToMaybe <$> runQuery@. queryFirst :: Default QueryRunner a b => e -> Query a -> Transaction e b queryFirst e q = maybeError (T.queryFirst q) e -- | Insert into a 'Table'. See 'runInsert'. insert :: Table w r -> w -> Transaction e Int64 insert t = withTrans . T.insert t -- | Insert many records into a 'Table'. See 'runInsertMany'. insertMany :: Table w r -> [w] -> Transaction e Int64 insertMany t = withTrans . T.insertMany t -- | Insert a record into a 'Table' with a return value. See 'runInsertReturning'. insertReturning :: Default QueryRunner a b => Table w r -> (r -> a) -> w -> Transaction e [b] insertReturning t ret = withTrans . T.insertReturning t ret -- | Insert a record into a 'Table' with a return value. Retrieve only the first result. -- Similar to @'listToMaybe' '<$>' 'insertReturning'@ insertReturningFirst :: Default QueryRunner a b => e -> Table w r -> (r -> a) -> w -> Transaction e b insertReturningFirst e t ret w = maybeError (T.insertReturningFirst t ret w) e -- | Insert many records into a 'Table' with a return value for each record. -- -- Maybe not worth defining. This almost certainly does the wrong thing. insertManyReturning :: Default QueryRunner a b => Table w r -> [w] -> (r -> a) -> Transaction e [b] insertManyReturning t ws = withTrans . T.insertManyReturning t ws -- | Update items in a 'Table' where the predicate is true. See 'runUpdate'. update :: Table w r -> (r -> w) -> (r -> Column PGBool) -> Transaction e Int64 update t r2w = withTrans . T.update t r2w -- | Update items in a 'Table' with a return value. See 'runUpdateReturning'. updateReturning :: Default QueryRunner a b => Table w r -> (r -> w) -> (r -> Column PGBool) -> (r -> a) -> Transaction e [b] updateReturning t r2w p = withTrans . T.updateReturning t r2w p -- | Update items in a 'Table' with a return value. Similar to @'listToMaybe' '<$>' 'updateReturning'@. updateReturningFirst :: Default QueryRunner a b => e -> Table w r -> (r -> w) -> (r -> Column PGBool) -> (r -> a) -> Transaction e b updateReturningFirst e t r2w p r2r = maybeError (T.updateReturningFirst t r2w p r2r) e -- | Delete items in a 'Table' that satisfy some boolean predicate. See 'runDelete'. delete :: Table a b -> (b -> Column PGBool) -> Transaction e Int64 delete t = withTrans . T.delete t
WraithM/opaleye-trans
src/Opaleye/Trans/Exception.hs
bsd-3-clause
6,446
0
12
1,778
1,702
899
803
111
1
module Entity.Paddle where import Graphics.Gloss import Entity -- Paddle x y w h xv data Paddle = Paddle Float Float Float Float Float -- change the direction of the paddle, return a paddle that needs a new x-vel changeDir :: Paddle -> Float -> Paddle changeDir (Paddle x y w h v) = Paddle x y w h paddleColor = Color (makeColor 0.6 0.6 0.6 1.0) instance Entity Paddle where center (Paddle x y _ _ _) = (x, y) left (Paddle x _ w _ _) = x - w / 2.0 right (Paddle x _ w _ _) = x + w / 2.0 top (Paddle _ y _ h _) = y + h / 2.0 bottom (Paddle _ y _ h _) = y - h / 2.0 width (Paddle _ _ w _ _) = w height (Paddle _ _ _ h _) = h xvel (Paddle _ _ _ _ xv) = xv yvel _ = 0 move (Paddle x y w h v) time | x <= (-336) && v <= 0 = Paddle x y w h v | x >= 336 && v >= 0 = Paddle x y w h v | otherwise = Paddle (x + v * time) y w h v render (Paddle x y w h _) = paddleColor $ Translate x y $ rectangleSolid w h
jamiltron/GlossPong
Entity/Paddle.hs
bsd-3-clause
1,074
0
13
408
488
245
243
24
1
{-| High-Level Event-Log Interface TODO Effects storage logic is messy. -} module Urbit.Vere.Log ( EventLog, identity, nextEv, lastEv , new, existing , streamEvents, appendEvents, trimEvents , streamEffectsRows, writeEffectsRow ) where import Urbit.Prelude hiding (init) import Data.Conduit import Data.RAcquire import Database.LMDB.Raw import Foreign.Marshal.Alloc import Foreign.Ptr import Urbit.Vere.Pier.Types import Foreign.Storable (peek, poke, sizeOf) import qualified Data.ByteString.Unsafe as BU import qualified Data.Vector as V -- Types ----------------------------------------------------------------------- type Env = MDB_env type Val = MDB_val type Txn = MDB_txn type Dbi = MDB_dbi type Cur = MDB_cursor data EventLog = EventLog { env :: Env , _metaTbl :: Dbi , eventsTbl :: Dbi , effectsTbl :: Dbi , identity :: LogIdentity , numEvents :: IORef EventId } nextEv :: EventLog -> RIO e EventId nextEv = fmap succ . readIORef . numEvents lastEv :: EventLog -> RIO e EventId lastEv = readIORef . numEvents data EventLogExn = NoLogIdentity | MissingEvent EventId | BadNounInLogIdentity ByteString DecodeErr ByteString | BadKeyInEventLog | BadWriteLogIdentity LogIdentity | BadWriteEvent EventId | BadWriteEffect EventId deriving Show -- Instances ------------------------------------------------------------------- instance Exception EventLogExn where -- Open/Close an Event Log ----------------------------------------------------- rawOpen :: MonadIO m => FilePath -> m Env rawOpen dir = io $ do env <- mdb_env_create mdb_env_set_maxdbs env 3 mdb_env_set_mapsize env (100 * 1024 * 1024 * 1024) mdb_env_open env dir [] pure env create :: HasLogFunc e => FilePath -> LogIdentity -> RIO e EventLog create dir id = do logDebug $ display (pack @Text $ "Creating LMDB database: " <> dir) logDebug $ display (pack @Text $ "Log Identity: " <> show id) env <- rawOpen dir (m, e, f) <- createTables env clearEvents env e writeIdent env m id EventLog env m e f id <$> newIORef 0 where createTables env = rwith (writeTxn env) $ \txn -> io $ (,,) <$> mdb_dbi_open txn (Just "META") [MDB_CREATE] <*> mdb_dbi_open txn (Just "EVENTS") [MDB_CREATE, MDB_INTEGERKEY] <*> mdb_dbi_open txn (Just "EFFECTS") [MDB_CREATE, MDB_INTEGERKEY] open :: HasLogFunc e => FilePath -> RIO e EventLog open dir = do logDebug $ display (pack @Text $ "Opening LMDB database: " <> dir) env <- rawOpen dir (m, e, f) <- openTables env id <- getIdent env m logDebug $ display (pack @Text $ "Log Identity: " <> show id) numEvs <- getNumEvents env e EventLog env m e f id <$> newIORef numEvs where openTables env = rwith (writeTxn env) $ \txn -> io $ (,,) <$> mdb_dbi_open txn (Just "META") [] <*> mdb_dbi_open txn (Just "EVENTS") [MDB_INTEGERKEY] <*> mdb_dbi_open txn (Just "EFFECTS") [MDB_CREATE, MDB_INTEGERKEY] close :: HasLogFunc e => FilePath -> EventLog -> RIO e () close dir (EventLog env meta events effects _ _) = do logDebug $ display (pack @Text $ "Closing LMDB database: " <> dir) io $ do mdb_dbi_close env meta mdb_dbi_close env events mdb_dbi_close env effects mdb_env_sync_flush env mdb_env_close env -- Create a new event log or open an existing one. ----------------------------- existing :: HasLogFunc e => FilePath -> RAcquire e EventLog existing dir = mkRAcquire (open dir) (close dir) new :: HasLogFunc e => FilePath -> LogIdentity -> RAcquire e EventLog new dir id = mkRAcquire (create dir id) (close dir) -- Read/Write Log Identity ----------------------------------------------------- {-| A read-only transaction that commits at the end. Use this when opening database handles. -} _openTxn :: Env -> RAcquire e Txn _openTxn env = mkRAcquire begin commit where begin = io $ mdb_txn_begin env Nothing True commit = io . mdb_txn_commit {-| A read-only transaction that aborts at the end. Use this when reading data from already-opened databases. -} readTxn :: Env -> RAcquire e Txn readTxn env = mkRAcquire begin abort where begin = io $ mdb_txn_begin env Nothing True abort = io . mdb_txn_abort {-| A read-write transaction that commits upon sucessful completion and aborts on exception. Use this when reading data from already-opened databases. -} writeTxn :: Env -> RAcquire e Txn writeTxn env = mkRAcquireType begin finalize where begin = io $ mdb_txn_begin env Nothing False finalize txn = io . \case ReleaseNormal -> mdb_txn_commit txn ReleaseEarly -> mdb_txn_commit txn ReleaseException -> mdb_txn_abort txn cursor :: Txn -> Dbi -> RAcquire e Cur cursor txn dbi = mkRAcquire open close where open = io $ mdb_cursor_open txn dbi close = io . mdb_cursor_close getIdent :: HasLogFunc e => Env -> Dbi -> RIO e LogIdentity getIdent env dbi = do logDebug "Reading log identity" getTbl env >>= traverse decodeIdent >>= \case Nothing -> throwIO NoLogIdentity Just li -> pure li where decodeIdent :: (Noun, Noun, Noun) -> RIO e LogIdentity decodeIdent = fromNounExn . toNoun getTbl :: Env -> RIO e (Maybe (Noun, Noun, Noun)) getTbl env = do rwith (readTxn env) $ \txn -> do who <- getMb txn dbi "who" fake <- getMb txn dbi "is-fake" life <- getMb txn dbi "life" pure $ (,,) <$> who <*> fake <*> life writeIdent :: HasLogFunc e => Env -> Dbi -> LogIdentity -> RIO e () writeIdent env metaTbl ident@LogIdentity{..} = do logDebug "Writing log identity" let flags = compileWriteFlags [] rwith (writeTxn env) $ \txn -> do x <- putNoun flags txn metaTbl "who" (toNoun who) y <- putNoun flags txn metaTbl "is-fake" (toNoun isFake) z <- putNoun flags txn metaTbl "life" (toNoun lifecycleLen) unless (x && y && z) $ do throwIO (BadWriteLogIdentity ident) -- Latest Event Number --------------------------------------------------------- getNumEvents :: Env -> Dbi -> RIO e Word64 getNumEvents env eventsTbl = rwith (readTxn env) $ \txn -> rwith (cursor txn eventsTbl) $ \cur -> withKVPtrs' nullVal nullVal $ \pKey pVal -> io $ mdb_cursor_get MDB_LAST cur pKey pVal >>= \case False -> pure 0 True -> peek pKey >>= mdbValToWord64 -- Write Events ---------------------------------------------------------------- clearEvents :: Env -> Dbi -> RIO e () clearEvents env eventsTbl = rwith (writeTxn env) $ \txn -> rwith (cursor txn eventsTbl) $ \cur -> withKVPtrs' nullVal nullVal $ \pKey pVal -> do let loop = io (mdb_cursor_get MDB_LAST cur pKey pVal) >>= \case False -> pure () True -> do io $ mdb_cursor_del (compileWriteFlags []) cur loop loop appendEvents :: EventLog -> Vector ByteString -> RIO e () appendEvents log !events = do numEvs <- readIORef (numEvents log) next <- pure (numEvs + 1) doAppend $ zip [next..] $ toList events writeIORef (numEvents log) (numEvs + word (length events)) where flags = compileWriteFlags [MDB_NOOVERWRITE] doAppend = \kvs -> rwith (writeTxn $ env log) $ \txn -> for_ kvs $ \(k,v) -> do putBytes flags txn (eventsTbl log) k v >>= \case True -> pure () False -> throwIO (BadWriteEvent k) writeEffectsRow :: EventLog -> EventId -> ByteString -> RIO e () writeEffectsRow log k v = do rwith (writeTxn $ env log) $ \txn -> putBytes flags txn (effectsTbl log) k v >>= \case True -> pure () False -> throwIO (BadWriteEffect k) where flags = compileWriteFlags [] -- Read Events ----------------------------------------------------------------- trimEvents :: HasLogFunc e => EventLog -> Word64 -> RIO e () trimEvents log start = do last <- lastEv log rwith (writeTxn $ env log) $ \txn -> for_ [start..last] $ \eId -> withWordPtr eId $ \pKey -> do let key = MDB_val 8 (castPtr pKey) found <- io $ mdb_del txn (eventsTbl log) key Nothing unless found $ throwIO (MissingEvent eId) writeIORef (numEvents log) (pred start) streamEvents :: HasLogFunc e => EventLog -> Word64 -> ConduitT () ByteString (RIO e) () streamEvents log first = do batch <- lift $ readBatch log first unless (null batch) $ do for_ batch yield streamEvents log (first + word (length batch)) streamEffectsRows :: ∀e. HasLogFunc e => EventLog -> EventId -> ConduitT () (Word64, ByteString) (RIO e) () streamEffectsRows log = go where go :: EventId -> ConduitT () (Word64, ByteString) (RIO e) () go next = do batch <- lift $ readRowsBatch (env log) (effectsTbl log) next unless (null batch) $ do for_ batch yield go (next + fromIntegral (length batch)) {-| Read 1000 rows from the events table, starting from event `first`. Throws `MissingEvent` if an event was missing from the log. -} readBatch :: EventLog -> Word64 -> RIO e (V.Vector ByteString) readBatch log first = start where start = do last <- lastEv log if (first > last) then pure mempty else readRows $ fromIntegral $ min 1000 $ ((last+1) - first) assertFound :: EventId -> Bool -> RIO e () assertFound id found = do unless found $ throwIO $ MissingEvent id readRows count = withWordPtr first $ \pIdx -> withKVPtrs' (MDB_val 8 (castPtr pIdx)) nullVal $ \pKey pVal -> rwith (readTxn $ env log) $ \txn -> rwith (cursor txn $ eventsTbl log) $ \cur -> do assertFound first =<< io (mdb_cursor_get MDB_SET_KEY cur pKey pVal) fetchRows count cur pKey pVal fetchRows count cur pKey pVal = do env <- ask V.generateM count $ \i -> runRIO env $ do key <- io $ peek pKey >>= mdbValToWord64 val <- io $ peek pVal >>= mdbValToBytes idx <- pure (first + word i) unless (key == idx) $ throwIO $ MissingEvent idx when (count /= succ i) $ do assertFound idx =<< io (mdb_cursor_get MDB_NEXT cur pKey pVal) pure val {-| Read 1000 rows from the database, starting from key `first`. -} readRowsBatch :: ∀e. HasLogFunc e => Env -> Dbi -> Word64 -> RIO e (V.Vector (Word64, ByteString)) readRowsBatch env dbi first = readRows where readRows = do logDebug $ display ("(readRowsBatch) From: " <> tshow first) withWordPtr first $ \pIdx -> withKVPtrs' (MDB_val 8 (castPtr pIdx)) nullVal $ \pKey pVal -> rwith (readTxn env) $ \txn -> rwith (cursor txn dbi) $ \cur -> io (mdb_cursor_get MDB_SET_RANGE cur pKey pVal) >>= \case False -> pure mempty True -> V.unfoldrM (fetchBatch cur pKey pVal) 1000 fetchBatch :: Cur -> Ptr Val -> Ptr Val -> Word -> RIO e (Maybe ((Word64, ByteString), Word)) fetchBatch cur pKey pVal 0 = pure Nothing fetchBatch cur pKey pVal n = do key <- io $ peek pKey >>= mdbValToWord64 val <- io $ peek pVal >>= mdbValToBytes io $ mdb_cursor_get MDB_NEXT cur pKey pVal >>= \case False -> pure $ Just ((key, val), 0) True -> pure $ Just ((key, val), pred n) -- Utils ----------------------------------------------------------------------- withKVPtrs' :: (MonadIO m, MonadUnliftIO m) => Val -> Val -> (Ptr Val -> Ptr Val -> m a) -> m a withKVPtrs' k v cb = withRunInIO $ \run -> withKVPtrs k v $ \x y -> run (cb x y) nullVal :: MDB_val nullVal = MDB_val 0 nullPtr word :: Int -> Word64 word = fromIntegral assertExn :: Exception e => Bool -> e -> IO () assertExn True _ = pure () assertExn False e = throwIO e eitherExn :: Exception e => Either a b -> (a -> e) -> IO b eitherExn eat exn = either (throwIO . exn) pure eat byteStringAsMdbVal :: ByteString -> (MDB_val -> IO a) -> IO a byteStringAsMdbVal bs k = BU.unsafeUseAsCStringLen bs $ \(ptr,sz) -> k (MDB_val (fromIntegral sz) (castPtr ptr)) mdbValToWord64 :: MDB_val -> IO Word64 mdbValToWord64 (MDB_val sz ptr) = do assertExn (sz == 8) BadKeyInEventLog peek (castPtr ptr) withWord64AsMDBval :: (MonadIO m, MonadUnliftIO m) => Word64 -> (MDB_val -> m a) -> m a withWord64AsMDBval w cb = do withWordPtr w $ \p -> cb (MDB_val (fromIntegral (sizeOf w)) (castPtr p)) withWordPtr :: (MonadIO m, MonadUnliftIO m) => Word64 -> (Ptr Word64 -> m a) -> m a withWordPtr w cb = withRunInIO $ \run -> allocaBytes (sizeOf w) (\p -> poke p w >> run (cb p)) -- Lower-Level Operations ------------------------------------------------------ getMb :: MonadIO m => Txn -> Dbi -> ByteString -> m (Maybe Noun) getMb txn db key = io $ byteStringAsMdbVal key $ \mKey -> mdb_get txn db mKey >>= traverse (mdbValToNoun key) mdbValToBytes :: MDB_val -> IO ByteString mdbValToBytes (MDB_val sz ptr) = do BU.unsafePackCStringLen (castPtr ptr, fromIntegral sz) mdbValToNoun :: ByteString -> MDB_val -> IO Noun mdbValToNoun key (MDB_val sz ptr) = do bs <- BU.unsafePackCStringLen (castPtr ptr, fromIntegral sz) let res = cueBS bs eitherExn res (\err -> BadNounInLogIdentity key err bs) putNoun :: MonadIO m => MDB_WriteFlags -> Txn -> Dbi -> ByteString -> Noun -> m Bool putNoun flags txn db key val = io $ byteStringAsMdbVal key $ \mKey -> byteStringAsMdbVal (jamBS val) $ \mVal -> mdb_put flags txn db mKey mVal putBytes :: MonadIO m => MDB_WriteFlags -> Txn -> Dbi -> Word64 -> ByteString -> m Bool putBytes flags txn db id bs = io $ withWord64AsMDBval id $ \idVal -> byteStringAsMdbVal bs $ \mVal -> mdb_put flags txn db idVal mVal
ngzax/urbit
pkg/hs/urbit-king/lib/Urbit/Vere/Log.hs
mit
14,287
0
26
3,883
4,797
2,357
2,440
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.RDS.RestoreDBInstanceFromDBSnapshot -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new DB instance from a DB snapshot. The target database is -- created from the source database restore point with the most of original -- configuration, but in a system chosen availability zone with the default -- security group, the default subnet group, and the default DB parameter -- group. By default, the new DB instance is created as a single-AZ -- deployment except when the instance is a SQL Server instance that has an -- option group that is associated with mirroring; in this case, the -- instance becomes a mirrored AZ deployment and not a single-AZ -- deployment. -- -- If your intent is to replace your original DB instance with the new, -- restored DB instance, then rename your original DB instance before you -- call the RestoreDBInstanceFromDBSnapshot action. RDS does not allow two -- DB instances with the same name. Once you have renamed your original DB -- instance with a different identifier, then you can pass the original -- name of the DB instance as the DBInstanceIdentifier in the call to the -- RestoreDBInstanceFromDBSnapshot action. The result is that you will -- replace the original DB instance with the DB instance created from the -- snapshot. -- -- /See:/ <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_RestoreDBInstanceFromDBSnapshot.html AWS API Reference> for RestoreDBInstanceFromDBSnapshot. module Network.AWS.RDS.RestoreDBInstanceFromDBSnapshot ( -- * Creating a Request restoreDBInstanceFromDBSnapshot , RestoreDBInstanceFromDBSnapshot -- * Request Lenses , rdifdsDBSecurityGroups , rdifdsPubliclyAccessible , rdifdsAutoMinorVersionUpgrade , rdifdsDBSubnetGroupName , rdifdsIOPS , rdifdsDomain , rdifdsEngine , rdifdsTDECredentialPassword , rdifdsDBInstanceClass , rdifdsLicenseModel , rdifdsAvailabilityZone , rdifdsVPCSecurityGroupIds , rdifdsMultiAZ , rdifdsOptionGroupName , rdifdsCopyTagsToSnapshot , rdifdsTDECredentialARN , rdifdsTags , rdifdsPort , rdifdsStorageType , rdifdsDBName , rdifdsDBInstanceIdentifier , rdifdsDBSnapshotIdentifier -- * Destructuring the Response , restoreDBInstanceFromDBSnapshotResponse , RestoreDBInstanceFromDBSnapshotResponse -- * Response Lenses , rdifdsrsDBInstance , rdifdsrsResponseStatus ) where import Network.AWS.Prelude import Network.AWS.RDS.Types import Network.AWS.RDS.Types.Product import Network.AWS.Request import Network.AWS.Response -- | -- -- /See:/ 'restoreDBInstanceFromDBSnapshot' smart constructor. data RestoreDBInstanceFromDBSnapshot = RestoreDBInstanceFromDBSnapshot' { _rdifdsDBSecurityGroups :: !(Maybe [Text]) , _rdifdsPubliclyAccessible :: !(Maybe Bool) , _rdifdsAutoMinorVersionUpgrade :: !(Maybe Bool) , _rdifdsDBSubnetGroupName :: !(Maybe Text) , _rdifdsIOPS :: !(Maybe Int) , _rdifdsDomain :: !(Maybe Text) , _rdifdsEngine :: !(Maybe Text) , _rdifdsTDECredentialPassword :: !(Maybe Text) , _rdifdsDBInstanceClass :: !(Maybe Text) , _rdifdsLicenseModel :: !(Maybe Text) , _rdifdsAvailabilityZone :: !(Maybe Text) , _rdifdsVPCSecurityGroupIds :: !(Maybe [Text]) , _rdifdsMultiAZ :: !(Maybe Bool) , _rdifdsOptionGroupName :: !(Maybe Text) , _rdifdsCopyTagsToSnapshot :: !(Maybe Bool) , _rdifdsTDECredentialARN :: !(Maybe Text) , _rdifdsTags :: !(Maybe [Tag]) , _rdifdsPort :: !(Maybe Int) , _rdifdsStorageType :: !(Maybe Text) , _rdifdsDBName :: !(Maybe Text) , _rdifdsDBInstanceIdentifier :: !Text , _rdifdsDBSnapshotIdentifier :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'RestoreDBInstanceFromDBSnapshot' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rdifdsDBSecurityGroups' -- -- * 'rdifdsPubliclyAccessible' -- -- * 'rdifdsAutoMinorVersionUpgrade' -- -- * 'rdifdsDBSubnetGroupName' -- -- * 'rdifdsIOPS' -- -- * 'rdifdsDomain' -- -- * 'rdifdsEngine' -- -- * 'rdifdsTDECredentialPassword' -- -- * 'rdifdsDBInstanceClass' -- -- * 'rdifdsLicenseModel' -- -- * 'rdifdsAvailabilityZone' -- -- * 'rdifdsVPCSecurityGroupIds' -- -- * 'rdifdsMultiAZ' -- -- * 'rdifdsOptionGroupName' -- -- * 'rdifdsCopyTagsToSnapshot' -- -- * 'rdifdsTDECredentialARN' -- -- * 'rdifdsTags' -- -- * 'rdifdsPort' -- -- * 'rdifdsStorageType' -- -- * 'rdifdsDBName' -- -- * 'rdifdsDBInstanceIdentifier' -- -- * 'rdifdsDBSnapshotIdentifier' restoreDBInstanceFromDBSnapshot :: Text -- ^ 'rdifdsDBInstanceIdentifier' -> Text -- ^ 'rdifdsDBSnapshotIdentifier' -> RestoreDBInstanceFromDBSnapshot restoreDBInstanceFromDBSnapshot pDBInstanceIdentifier_ pDBSnapshotIdentifier_ = RestoreDBInstanceFromDBSnapshot' { _rdifdsDBSecurityGroups = Nothing , _rdifdsPubliclyAccessible = Nothing , _rdifdsAutoMinorVersionUpgrade = Nothing , _rdifdsDBSubnetGroupName = Nothing , _rdifdsIOPS = Nothing , _rdifdsDomain = Nothing , _rdifdsEngine = Nothing , _rdifdsTDECredentialPassword = Nothing , _rdifdsDBInstanceClass = Nothing , _rdifdsLicenseModel = Nothing , _rdifdsAvailabilityZone = Nothing , _rdifdsVPCSecurityGroupIds = Nothing , _rdifdsMultiAZ = Nothing , _rdifdsOptionGroupName = Nothing , _rdifdsCopyTagsToSnapshot = Nothing , _rdifdsTDECredentialARN = Nothing , _rdifdsTags = Nothing , _rdifdsPort = Nothing , _rdifdsStorageType = Nothing , _rdifdsDBName = Nothing , _rdifdsDBInstanceIdentifier = pDBInstanceIdentifier_ , _rdifdsDBSnapshotIdentifier = pDBSnapshotIdentifier_ } -- | A list of DB security groups to associate with this DB instance. -- -- Default: The default DB security group for the database engine. rdifdsDBSecurityGroups :: Lens' RestoreDBInstanceFromDBSnapshot [Text] rdifdsDBSecurityGroups = lens _rdifdsDBSecurityGroups (\ s a -> s{_rdifdsDBSecurityGroups = a}) . _Default . _Coerce; -- | Specifies the accessibility options for the DB instance. A value of true -- specifies an Internet-facing instance with a publicly resolvable DNS -- name, which resolves to a public IP address. A value of false specifies -- an internal instance with a DNS name that resolves to a private IP -- address. -- -- Default: The default behavior varies depending on whether a VPC has been -- requested or not. The following list shows the default behavior in each -- case. -- -- - __Default VPC:__ true -- - __VPC:__ false -- -- If no DB subnet group has been specified as part of the request and the -- PubliclyAccessible value has not been set, the DB instance will be -- publicly accessible. If a specific DB subnet group has been specified as -- part of the request and the PubliclyAccessible value has not been set, -- the DB instance will be private. rdifdsPubliclyAccessible :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Bool) rdifdsPubliclyAccessible = lens _rdifdsPubliclyAccessible (\ s a -> s{_rdifdsPubliclyAccessible = a}); -- | Indicates that minor version upgrades will be applied automatically to -- the DB instance during the maintenance window. rdifdsAutoMinorVersionUpgrade :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Bool) rdifdsAutoMinorVersionUpgrade = lens _rdifdsAutoMinorVersionUpgrade (\ s a -> s{_rdifdsAutoMinorVersionUpgrade = a}); -- | The DB subnet group name to use for the new instance. rdifdsDBSubnetGroupName :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsDBSubnetGroupName = lens _rdifdsDBSubnetGroupName (\ s a -> s{_rdifdsDBSubnetGroupName = a}); -- | Specifies the amount of provisioned IOPS for the DB instance, expressed -- in I\/O operations per second. If this parameter is not specified, the -- IOPS value will be taken from the backup. If this parameter is set to 0, -- the new instance will be converted to a non-PIOPS instance, which will -- take additional time, though your DB instance will be available for -- connections before the conversion starts. -- -- Constraints: Must be an integer greater than 1000. -- -- __SQL Server__ -- -- Setting the IOPS value for the SQL Server database engine is not -- supported. rdifdsIOPS :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Int) rdifdsIOPS = lens _rdifdsIOPS (\ s a -> s{_rdifdsIOPS = a}); -- | Specify the Active Directory Domain to restore the instance in. rdifdsDomain :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsDomain = lens _rdifdsDomain (\ s a -> s{_rdifdsDomain = a}); -- | The database engine to use for the new instance. -- -- Default: The same as source -- -- Constraint: Must be compatible with the engine of the source -- -- Valid Values: 'MySQL' | 'oracle-se1' | 'oracle-se' | 'oracle-ee' | -- 'sqlserver-ee' | 'sqlserver-se' | 'sqlserver-ex' | 'sqlserver-web' | -- 'postgres' rdifdsEngine :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsEngine = lens _rdifdsEngine (\ s a -> s{_rdifdsEngine = a}); -- | The password for the given ARN from the Key Store in order to access the -- device. rdifdsTDECredentialPassword :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsTDECredentialPassword = lens _rdifdsTDECredentialPassword (\ s a -> s{_rdifdsTDECredentialPassword = a}); -- | The compute and memory capacity of the Amazon RDS DB instance. -- -- Valid Values: -- 'db.t1.micro | db.m1.small | db.m1.medium | db.m1.large | db.m1.xlarge | db.m2.2xlarge | db.m2.4xlarge | db.m3.medium | db.m3.large | db.m3.xlarge | db.m3.2xlarge | db.r3.large | db.r3.xlarge | db.r3.2xlarge | db.r3.4xlarge | db.r3.8xlarge | db.t2.micro | db.t2.small | db.t2.medium' rdifdsDBInstanceClass :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsDBInstanceClass = lens _rdifdsDBInstanceClass (\ s a -> s{_rdifdsDBInstanceClass = a}); -- | License model information for the restored DB instance. -- -- Default: Same as source. -- -- Valid values: 'license-included' | 'bring-your-own-license' | -- 'general-public-license' rdifdsLicenseModel :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsLicenseModel = lens _rdifdsLicenseModel (\ s a -> s{_rdifdsLicenseModel = a}); -- | The EC2 Availability Zone that the database instance will be created in. -- -- Default: A random, system-chosen Availability Zone. -- -- Constraint: You cannot specify the AvailabilityZone parameter if the -- MultiAZ parameter is set to 'true'. -- -- Example: 'us-east-1a' rdifdsAvailabilityZone :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsAvailabilityZone = lens _rdifdsAvailabilityZone (\ s a -> s{_rdifdsAvailabilityZone = a}); -- | A list of EC2 VPC security groups to associate with this DB instance. -- -- Default: The default EC2 VPC security group for the DB subnet group\'s -- VPC. rdifdsVPCSecurityGroupIds :: Lens' RestoreDBInstanceFromDBSnapshot [Text] rdifdsVPCSecurityGroupIds = lens _rdifdsVPCSecurityGroupIds (\ s a -> s{_rdifdsVPCSecurityGroupIds = a}) . _Default . _Coerce; -- | Specifies if the DB instance is a Multi-AZ deployment. -- -- Constraint: You cannot specify the AvailabilityZone parameter if the -- MultiAZ parameter is set to 'true'. rdifdsMultiAZ :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Bool) rdifdsMultiAZ = lens _rdifdsMultiAZ (\ s a -> s{_rdifdsMultiAZ = a}); -- | The name of the option group to be used for the restored DB instance. -- -- Permanent options, such as the TDE option for Oracle Advanced Security -- TDE, cannot be removed from an option group, and that option group -- cannot be removed from a DB instance once it is associated with a DB -- instance rdifdsOptionGroupName :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsOptionGroupName = lens _rdifdsOptionGroupName (\ s a -> s{_rdifdsOptionGroupName = a}); -- | This property is not currently implemented. rdifdsCopyTagsToSnapshot :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Bool) rdifdsCopyTagsToSnapshot = lens _rdifdsCopyTagsToSnapshot (\ s a -> s{_rdifdsCopyTagsToSnapshot = a}); -- | The ARN from the Key Store with which to associate the instance for TDE -- encryption. rdifdsTDECredentialARN :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsTDECredentialARN = lens _rdifdsTDECredentialARN (\ s a -> s{_rdifdsTDECredentialARN = a}); -- | Undocumented member. rdifdsTags :: Lens' RestoreDBInstanceFromDBSnapshot [Tag] rdifdsTags = lens _rdifdsTags (\ s a -> s{_rdifdsTags = a}) . _Default . _Coerce; -- | The port number on which the database accepts connections. -- -- Default: The same port as the original DB instance -- -- Constraints: Value must be '1150-65535' rdifdsPort :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Int) rdifdsPort = lens _rdifdsPort (\ s a -> s{_rdifdsPort = a}); -- | Specifies the storage type to be associated with the DB instance. -- -- Valid values: 'standard | gp2 | io1' -- -- If you specify 'io1', you must also include a value for the 'Iops' -- parameter. -- -- Default: 'io1' if the 'Iops' parameter is specified; otherwise -- 'standard' rdifdsStorageType :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsStorageType = lens _rdifdsStorageType (\ s a -> s{_rdifdsStorageType = a}); -- | The database name for the restored DB instance. -- -- This parameter doesn\'t apply to the MySQL engine. rdifdsDBName :: Lens' RestoreDBInstanceFromDBSnapshot (Maybe Text) rdifdsDBName = lens _rdifdsDBName (\ s a -> s{_rdifdsDBName = a}); -- | Name of the DB instance to create from the DB snapshot. This parameter -- isn\'t case-sensitive. -- -- Constraints: -- -- - Must contain from 1 to 255 alphanumeric characters or hyphens -- - First character must be a letter -- - Cannot end with a hyphen or contain two consecutive hyphens -- -- Example: 'my-snapshot-id' rdifdsDBInstanceIdentifier :: Lens' RestoreDBInstanceFromDBSnapshot Text rdifdsDBInstanceIdentifier = lens _rdifdsDBInstanceIdentifier (\ s a -> s{_rdifdsDBInstanceIdentifier = a}); -- | The identifier for the DB snapshot to restore from. -- -- Constraints: -- -- - Must contain from 1 to 63 alphanumeric characters or hyphens -- - First character must be a letter -- - Cannot end with a hyphen or contain two consecutive hyphens rdifdsDBSnapshotIdentifier :: Lens' RestoreDBInstanceFromDBSnapshot Text rdifdsDBSnapshotIdentifier = lens _rdifdsDBSnapshotIdentifier (\ s a -> s{_rdifdsDBSnapshotIdentifier = a}); instance AWSRequest RestoreDBInstanceFromDBSnapshot where type Rs RestoreDBInstanceFromDBSnapshot = RestoreDBInstanceFromDBSnapshotResponse request = postQuery rDS response = receiveXMLWrapper "RestoreDBInstanceFromDBSnapshotResult" (\ s h x -> RestoreDBInstanceFromDBSnapshotResponse' <$> (x .@? "DBInstance") <*> (pure (fromEnum s))) instance ToHeaders RestoreDBInstanceFromDBSnapshot where toHeaders = const mempty instance ToPath RestoreDBInstanceFromDBSnapshot where toPath = const "/" instance ToQuery RestoreDBInstanceFromDBSnapshot where toQuery RestoreDBInstanceFromDBSnapshot'{..} = mconcat ["Action" =: ("RestoreDBInstanceFromDBSnapshot" :: ByteString), "Version" =: ("2014-10-31" :: ByteString), "DBSecurityGroups" =: toQuery (toQueryList "DBSecurityGroupName" <$> _rdifdsDBSecurityGroups), "PubliclyAccessible" =: _rdifdsPubliclyAccessible, "AutoMinorVersionUpgrade" =: _rdifdsAutoMinorVersionUpgrade, "DBSubnetGroupName" =: _rdifdsDBSubnetGroupName, "Iops" =: _rdifdsIOPS, "Domain" =: _rdifdsDomain, "Engine" =: _rdifdsEngine, "TdeCredentialPassword" =: _rdifdsTDECredentialPassword, "DBInstanceClass" =: _rdifdsDBInstanceClass, "LicenseModel" =: _rdifdsLicenseModel, "AvailabilityZone" =: _rdifdsAvailabilityZone, "VpcSecurityGroupIds" =: toQuery (toQueryList "VpcSecurityGroupId" <$> _rdifdsVPCSecurityGroupIds), "MultiAZ" =: _rdifdsMultiAZ, "OptionGroupName" =: _rdifdsOptionGroupName, "CopyTagsToSnapshot" =: _rdifdsCopyTagsToSnapshot, "TdeCredentialArn" =: _rdifdsTDECredentialARN, "Tags" =: toQuery (toQueryList "Tag" <$> _rdifdsTags), "Port" =: _rdifdsPort, "StorageType" =: _rdifdsStorageType, "DBName" =: _rdifdsDBName, "DBInstanceIdentifier" =: _rdifdsDBInstanceIdentifier, "DBSnapshotIdentifier" =: _rdifdsDBSnapshotIdentifier] -- | /See:/ 'restoreDBInstanceFromDBSnapshotResponse' smart constructor. data RestoreDBInstanceFromDBSnapshotResponse = RestoreDBInstanceFromDBSnapshotResponse' { _rdifdsrsDBInstance :: !(Maybe DBInstance) , _rdifdsrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'RestoreDBInstanceFromDBSnapshotResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rdifdsrsDBInstance' -- -- * 'rdifdsrsResponseStatus' restoreDBInstanceFromDBSnapshotResponse :: Int -- ^ 'rdifdsrsResponseStatus' -> RestoreDBInstanceFromDBSnapshotResponse restoreDBInstanceFromDBSnapshotResponse pResponseStatus_ = RestoreDBInstanceFromDBSnapshotResponse' { _rdifdsrsDBInstance = Nothing , _rdifdsrsResponseStatus = pResponseStatus_ } -- | Undocumented member. rdifdsrsDBInstance :: Lens' RestoreDBInstanceFromDBSnapshotResponse (Maybe DBInstance) rdifdsrsDBInstance = lens _rdifdsrsDBInstance (\ s a -> s{_rdifdsrsDBInstance = a}); -- | The response status code. rdifdsrsResponseStatus :: Lens' RestoreDBInstanceFromDBSnapshotResponse Int rdifdsrsResponseStatus = lens _rdifdsrsResponseStatus (\ s a -> s{_rdifdsrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-rds/gen/Network/AWS/RDS/RestoreDBInstanceFromDBSnapshot.hs
mpl-2.0
19,048
0
13
3,716
2,341
1,421
920
254
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Config.DeliverConfigSnapshot -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Schedules delivery of a configuration snapshot to the Amazon S3 bucket -- in the specified delivery channel. After the delivery has started, AWS -- Config sends following notifications using an Amazon SNS topic that you -- have specified. -- -- - Notification of starting the delivery. -- - Notification of delivery completed, if the delivery was successfully -- completed. -- - Notification of delivery failure, if the delivery failed to -- complete. -- -- /See:/ <http://docs.aws.amazon.com/config/latest/APIReference/API_DeliverConfigSnapshot.html AWS API Reference> for DeliverConfigSnapshot. module Network.AWS.Config.DeliverConfigSnapshot ( -- * Creating a Request deliverConfigSnapshot , DeliverConfigSnapshot -- * Request Lenses , dcsDeliveryChannelName -- * Destructuring the Response , deliverConfigSnapshotResponse , DeliverConfigSnapshotResponse -- * Response Lenses , dcsrsConfigSnapshotId , dcsrsResponseStatus ) where import Network.AWS.Config.Types import Network.AWS.Config.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | The input for the DeliverConfigSnapshot action. -- -- /See:/ 'deliverConfigSnapshot' smart constructor. newtype DeliverConfigSnapshot = DeliverConfigSnapshot' { _dcsDeliveryChannelName :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeliverConfigSnapshot' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcsDeliveryChannelName' deliverConfigSnapshot :: Text -- ^ 'dcsDeliveryChannelName' -> DeliverConfigSnapshot deliverConfigSnapshot pDeliveryChannelName_ = DeliverConfigSnapshot' { _dcsDeliveryChannelName = pDeliveryChannelName_ } -- | The name of the delivery channel through which the snapshot is -- delivered. dcsDeliveryChannelName :: Lens' DeliverConfigSnapshot Text dcsDeliveryChannelName = lens _dcsDeliveryChannelName (\ s a -> s{_dcsDeliveryChannelName = a}); instance AWSRequest DeliverConfigSnapshot where type Rs DeliverConfigSnapshot = DeliverConfigSnapshotResponse request = postJSON config response = receiveJSON (\ s h x -> DeliverConfigSnapshotResponse' <$> (x .?> "configSnapshotId") <*> (pure (fromEnum s))) instance ToHeaders DeliverConfigSnapshot where toHeaders = const (mconcat ["X-Amz-Target" =# ("StarlingDoveService.DeliverConfigSnapshot" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON DeliverConfigSnapshot where toJSON DeliverConfigSnapshot'{..} = object (catMaybes [Just ("deliveryChannelName" .= _dcsDeliveryChannelName)]) instance ToPath DeliverConfigSnapshot where toPath = const "/" instance ToQuery DeliverConfigSnapshot where toQuery = const mempty -- | The output for the DeliverConfigSnapshot action in JSON format. -- -- /See:/ 'deliverConfigSnapshotResponse' smart constructor. data DeliverConfigSnapshotResponse = DeliverConfigSnapshotResponse' { _dcsrsConfigSnapshotId :: !(Maybe Text) , _dcsrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeliverConfigSnapshotResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcsrsConfigSnapshotId' -- -- * 'dcsrsResponseStatus' deliverConfigSnapshotResponse :: Int -- ^ 'dcsrsResponseStatus' -> DeliverConfigSnapshotResponse deliverConfigSnapshotResponse pResponseStatus_ = DeliverConfigSnapshotResponse' { _dcsrsConfigSnapshotId = Nothing , _dcsrsResponseStatus = pResponseStatus_ } -- | The ID of the snapshot that is being created. dcsrsConfigSnapshotId :: Lens' DeliverConfigSnapshotResponse (Maybe Text) dcsrsConfigSnapshotId = lens _dcsrsConfigSnapshotId (\ s a -> s{_dcsrsConfigSnapshotId = a}); -- | The response status code. dcsrsResponseStatus :: Lens' DeliverConfigSnapshotResponse Int dcsrsResponseStatus = lens _dcsrsResponseStatus (\ s a -> s{_dcsrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-config/gen/Network/AWS/Config/DeliverConfigSnapshot.hs
mpl-2.0
5,162
0
13
1,078
592
358
234
80
1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Test.AWS.Gen.Lambda -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Test.AWS.Gen.Lambda where import Data.Proxy import Test.AWS.Fixture import Test.AWS.Prelude import Test.Tasty import Network.AWS.Lambda import Test.AWS.Lambda.Internal -- Auto-generated: the actual test selection needs to be manually placed into -- the top-level so that real test data can be incrementally added. -- -- This commented snippet is what the entire set should look like: -- fixtures :: TestTree -- fixtures = -- [ testGroup "request" -- [ testGetFunctionConfiguration $ -- getFunctionConfiguration -- -- , testDeleteEventSourceMapping $ -- deleteEventSourceMapping -- -- , testUpdateEventSourceMapping $ -- updateEventSourceMapping -- -- , testRemovePermission $ -- removePermission -- -- , testInvoke $ -- invoke -- -- , testGetEventSourceMapping $ -- getEventSourceMapping -- -- , testCreateFunction $ -- createFunction -- -- , testCreateEventSourceMapping $ -- createEventSourceMapping -- -- , testGetFunction $ -- getFunction -- -- , testListEventSourceMappings $ -- listEventSourceMappings -- -- , testAddPermission $ -- addPermission -- -- , testDeleteFunction $ -- deleteFunction -- -- , testUpdateFunctionConfiguration $ -- updateFunctionConfiguration -- -- , testListFunctions $ -- listFunctions -- -- , testUpdateFunctionCode $ -- updateFunctionCode -- -- , testGetPolicy $ -- getPolicy -- -- ] -- , testGroup "response" -- [ testGetFunctionConfigurationResponse $ -- functionConfiguration -- -- , testDeleteEventSourceMappingResponse $ -- eventSourceMappingConfiguration -- -- , testUpdateEventSourceMappingResponse $ -- eventSourceMappingConfiguration -- -- , testRemovePermissionResponse $ -- removePermissionResponse -- -- , testInvokeResponse $ -- invokeResponse -- -- , testGetEventSourceMappingResponse $ -- eventSourceMappingConfiguration -- -- , testCreateFunctionResponse $ -- functionConfiguration -- -- , testCreateEventSourceMappingResponse $ -- eventSourceMappingConfiguration -- -- , testGetFunctionResponse $ -- getFunctionResponse -- -- , testListEventSourceMappingsResponse $ -- listEventSourceMappingsResponse -- -- , testAddPermissionResponse $ -- addPermissionResponse -- -- , testDeleteFunctionResponse $ -- deleteFunctionResponse -- -- , testUpdateFunctionConfigurationResponse $ -- functionConfiguration -- -- , testListFunctionsResponse $ -- listFunctionsResponse -- -- , testUpdateFunctionCodeResponse $ -- functionConfiguration -- -- , testGetPolicyResponse $ -- getPolicyResponse -- -- ] -- ] -- Requests testGetFunctionConfiguration :: GetFunctionConfiguration -> TestTree testGetFunctionConfiguration = req "GetFunctionConfiguration" "fixture/GetFunctionConfiguration.yaml" testDeleteEventSourceMapping :: DeleteEventSourceMapping -> TestTree testDeleteEventSourceMapping = req "DeleteEventSourceMapping" "fixture/DeleteEventSourceMapping.yaml" testUpdateEventSourceMapping :: UpdateEventSourceMapping -> TestTree testUpdateEventSourceMapping = req "UpdateEventSourceMapping" "fixture/UpdateEventSourceMapping.yaml" testRemovePermission :: RemovePermission -> TestTree testRemovePermission = req "RemovePermission" "fixture/RemovePermission.yaml" testInvoke :: Invoke -> TestTree testInvoke = req "Invoke" "fixture/Invoke.yaml" testGetEventSourceMapping :: GetEventSourceMapping -> TestTree testGetEventSourceMapping = req "GetEventSourceMapping" "fixture/GetEventSourceMapping.yaml" testCreateFunction :: CreateFunction -> TestTree testCreateFunction = req "CreateFunction" "fixture/CreateFunction.yaml" testCreateEventSourceMapping :: CreateEventSourceMapping -> TestTree testCreateEventSourceMapping = req "CreateEventSourceMapping" "fixture/CreateEventSourceMapping.yaml" testGetFunction :: GetFunction -> TestTree testGetFunction = req "GetFunction" "fixture/GetFunction.yaml" testListEventSourceMappings :: ListEventSourceMappings -> TestTree testListEventSourceMappings = req "ListEventSourceMappings" "fixture/ListEventSourceMappings.yaml" testAddPermission :: AddPermission -> TestTree testAddPermission = req "AddPermission" "fixture/AddPermission.yaml" testDeleteFunction :: DeleteFunction -> TestTree testDeleteFunction = req "DeleteFunction" "fixture/DeleteFunction.yaml" testUpdateFunctionConfiguration :: UpdateFunctionConfiguration -> TestTree testUpdateFunctionConfiguration = req "UpdateFunctionConfiguration" "fixture/UpdateFunctionConfiguration.yaml" testListFunctions :: ListFunctions -> TestTree testListFunctions = req "ListFunctions" "fixture/ListFunctions.yaml" testUpdateFunctionCode :: UpdateFunctionCode -> TestTree testUpdateFunctionCode = req "UpdateFunctionCode" "fixture/UpdateFunctionCode.yaml" testGetPolicy :: GetPolicy -> TestTree testGetPolicy = req "GetPolicy" "fixture/GetPolicy.yaml" -- Responses testGetFunctionConfigurationResponse :: FunctionConfiguration -> TestTree testGetFunctionConfigurationResponse = res "GetFunctionConfigurationResponse" "fixture/GetFunctionConfigurationResponse.proto" lambda (Proxy :: Proxy GetFunctionConfiguration) testDeleteEventSourceMappingResponse :: EventSourceMappingConfiguration -> TestTree testDeleteEventSourceMappingResponse = res "DeleteEventSourceMappingResponse" "fixture/DeleteEventSourceMappingResponse.proto" lambda (Proxy :: Proxy DeleteEventSourceMapping) testUpdateEventSourceMappingResponse :: EventSourceMappingConfiguration -> TestTree testUpdateEventSourceMappingResponse = res "UpdateEventSourceMappingResponse" "fixture/UpdateEventSourceMappingResponse.proto" lambda (Proxy :: Proxy UpdateEventSourceMapping) testRemovePermissionResponse :: RemovePermissionResponse -> TestTree testRemovePermissionResponse = res "RemovePermissionResponse" "fixture/RemovePermissionResponse.proto" lambda (Proxy :: Proxy RemovePermission) testInvokeResponse :: InvokeResponse -> TestTree testInvokeResponse = res "InvokeResponse" "fixture/InvokeResponse.proto" lambda (Proxy :: Proxy Invoke) testGetEventSourceMappingResponse :: EventSourceMappingConfiguration -> TestTree testGetEventSourceMappingResponse = res "GetEventSourceMappingResponse" "fixture/GetEventSourceMappingResponse.proto" lambda (Proxy :: Proxy GetEventSourceMapping) testCreateFunctionResponse :: FunctionConfiguration -> TestTree testCreateFunctionResponse = res "CreateFunctionResponse" "fixture/CreateFunctionResponse.proto" lambda (Proxy :: Proxy CreateFunction) testCreateEventSourceMappingResponse :: EventSourceMappingConfiguration -> TestTree testCreateEventSourceMappingResponse = res "CreateEventSourceMappingResponse" "fixture/CreateEventSourceMappingResponse.proto" lambda (Proxy :: Proxy CreateEventSourceMapping) testGetFunctionResponse :: GetFunctionResponse -> TestTree testGetFunctionResponse = res "GetFunctionResponse" "fixture/GetFunctionResponse.proto" lambda (Proxy :: Proxy GetFunction) testListEventSourceMappingsResponse :: ListEventSourceMappingsResponse -> TestTree testListEventSourceMappingsResponse = res "ListEventSourceMappingsResponse" "fixture/ListEventSourceMappingsResponse.proto" lambda (Proxy :: Proxy ListEventSourceMappings) testAddPermissionResponse :: AddPermissionResponse -> TestTree testAddPermissionResponse = res "AddPermissionResponse" "fixture/AddPermissionResponse.proto" lambda (Proxy :: Proxy AddPermission) testDeleteFunctionResponse :: DeleteFunctionResponse -> TestTree testDeleteFunctionResponse = res "DeleteFunctionResponse" "fixture/DeleteFunctionResponse.proto" lambda (Proxy :: Proxy DeleteFunction) testUpdateFunctionConfigurationResponse :: FunctionConfiguration -> TestTree testUpdateFunctionConfigurationResponse = res "UpdateFunctionConfigurationResponse" "fixture/UpdateFunctionConfigurationResponse.proto" lambda (Proxy :: Proxy UpdateFunctionConfiguration) testListFunctionsResponse :: ListFunctionsResponse -> TestTree testListFunctionsResponse = res "ListFunctionsResponse" "fixture/ListFunctionsResponse.proto" lambda (Proxy :: Proxy ListFunctions) testUpdateFunctionCodeResponse :: FunctionConfiguration -> TestTree testUpdateFunctionCodeResponse = res "UpdateFunctionCodeResponse" "fixture/UpdateFunctionCodeResponse.proto" lambda (Proxy :: Proxy UpdateFunctionCode) testGetPolicyResponse :: GetPolicyResponse -> TestTree testGetPolicyResponse = res "GetPolicyResponse" "fixture/GetPolicyResponse.proto" lambda (Proxy :: Proxy GetPolicy)
fmapfmapfmap/amazonka
amazonka-lambda/test/Test/AWS/Gen/Lambda.hs
mpl-2.0
9,749
0
7
1,874
979
581
398
169
1
module Shared.Lifecycle ( withSDL, withWindow, createRenderer, withRenderer, setHint, logWarning, throwSDLError ) where import qualified Graphics.UI.SDL as SDL import Data.Bits import Foreign.C.String import Foreign.C.Types import GHC.Word import Shared.Utilities type Risky a = Either String a initializeSDL :: [Word32] -> IO (Risky ()) initializeSDL flags = do initSuccess <- SDL.init $ foldl (.|.) 0 flags return $ if initSuccess < 0 then Left "SDL could not initialize!" else Right () withSDL :: IO () -> IO () withSDL op = do initializeSDL [SDL.SDL_INIT_VIDEO] >>= either throwSDLError return op SDL.quit withWindow :: String -> (CInt, CInt) -> (SDL.Window -> IO ()) -> IO () withWindow title size op = do window <- createWindow title size >>= either throwSDLError return op window SDL.destroyWindow window createWindow :: String -> (CInt, CInt) -> IO (Risky SDL.Window) createWindow title (w, h) = withCAString title $ \ctitle -> do window <- SDL.createWindow ctitle SDL.SDL_WINDOWPOS_UNDEFINED SDL.SDL_WINDOWPOS_UNDEFINED w h SDL.SDL_WINDOW_SHOWN return $ if window == nullPtr then Left "Window could not be created!" else Right window withRenderer :: (SDL.Renderer -> IO ()) -> SDL.Window -> IO () withRenderer operation window = do _ <- setHint "SDL_RENDER_SCALE_QUALITY" "1" >>= logWarning renderer <- createRenderer window (-1) [SDL.SDL_RENDERER_ACCELERATED] >>= either throwSDLError return operation renderer SDL.destroyRenderer renderer createRenderer :: SDL.Window -> CInt -> [Word32] -> IO (Risky SDL.Renderer) createRenderer window index flags = do renderer <- SDL.createRenderer window index $ foldl (.|.) 0 flags return $ if renderer == nullPtr then Left "Renderer could not be created!" else Right renderer setHint :: String -> String -> IO (Risky Bool) setHint hint value = do result <- withCAString2 hint value SDL.setHint return $ if not result then Left "Warning: Linear texture filtering not enabled!" else Right result throwSDLError :: String -> IO a throwSDLError message = do errorString <- SDL.getError >>= peekCString fail (message ++ " SDL_Error: " ++ errorString) logWarning :: Risky Bool -> IO Bool logWarning = either (\x -> print x >> return False) return
oldmanmike/haskellSDL2Examples
src/shared/lifecycle.hs
gpl-2.0
2,295
0
11
428
781
390
391
53
2
{-# LANGUAGE PackageImports #-} {-# LANGUAGE FlexibleContexts #-} module Propellor.PrivData ( withPrivData, withSomePrivData, addPrivData, setPrivData, dumpPrivData, editPrivData, filterPrivData, listPrivDataFields, makePrivDataDir, decryptPrivData, PrivMap, ) where import Control.Applicative import System.IO import System.Directory import Data.Maybe import Data.Monoid import Data.List import Control.Monad import Control.Monad.IfElse import "mtl" Control.Monad.Reader import qualified Data.Map as M import qualified Data.Set as S import Propellor.Types import Propellor.Types.PrivData import Propellor.Message import Propellor.Info import Propellor.Gpg import Propellor.PrivData.Paths import Utility.Monad import Utility.PartialPrelude import Utility.Exception import Utility.Tmp import Utility.SafeCommand import Utility.Misc import Utility.FileMode import Utility.Env import Utility.Table -- | Allows a Property to access the value of a specific PrivDataField, -- for use in a specific Context or HostContext. -- -- Example use: -- -- > withPrivData (PrivFile pemfile) (Context "joeyh.name") $ \getdata -> -- > property "joeyh.name ssl cert" $ getdata $ \privdata -> -- > liftIO $ writeFile pemfile privdata -- > where pemfile = "/etc/ssl/certs/web.pem" -- -- Note that if the value is not available, the action is not run -- and instead it prints a message to help the user make the necessary -- private data available. -- -- The resulting Property includes Info about the PrivDataField -- being used, which is necessary to ensure that the privdata is sent to -- the remote host by propellor. withPrivData :: (IsContext c, IsPrivDataSource s, IsProp (Property i)) => s -> c -> (((PrivData -> Propellor Result) -> Propellor Result) -> Property i) -> Property HasInfo withPrivData s = withPrivData' snd [s] -- Like withPrivData, but here any one of a list of PrivDataFields can be used. withSomePrivData :: (IsContext c, IsPrivDataSource s, IsProp (Property i)) => [s] -> c -> ((((PrivDataField, PrivData) -> Propellor Result) -> Propellor Result) -> Property i) -> Property HasInfo withSomePrivData = withPrivData' id withPrivData' :: (IsContext c, IsPrivDataSource s, IsProp (Property i)) => ((PrivDataField, PrivData) -> v) -> [s] -> c -> (((v -> Propellor Result) -> Propellor Result) -> Property i) -> Property HasInfo withPrivData' feed srclist c mkprop = addinfo $ mkprop $ \a -> maybe missing (a . feed) =<< getM get fieldlist where get field = do context <- mkHostContext hc <$> asks hostName maybe Nothing (\privdata -> Just (field, privdata)) <$> liftIO (getLocalPrivData field context) missing = do Context cname <- mkHostContext hc <$> asks hostName warningMessage $ "Missing privdata " ++ intercalate " or " fieldnames ++ " (for " ++ cname ++ ")" liftIO $ putStrLn $ "Fix this by running:" liftIO $ showSet $ map (\s -> (privDataField s, Context cname, describePrivDataSource s)) srclist return FailedChange addinfo p = infoProperty (propertyDesc p) (propertySatisfy p) (propertyInfo p <> mempty { _privData = privset }) (propertyChildren p) privset = S.fromList $ map (\s -> (privDataField s, describePrivDataSource s, hc)) srclist fieldnames = map show fieldlist fieldlist = map privDataField srclist hc = asHostContext c showSet :: [(PrivDataField, Context, Maybe PrivDataSourceDesc)] -> IO () showSet l = forM_ l $ \(f, Context c, md) -> do putStrLn $ " propellor --set '" ++ show f ++ "' '" ++ c ++ "' \\" maybe noop (\d -> putStrLn $ " " ++ d) md putStrLn "" addPrivData :: (PrivDataField, Maybe PrivDataSourceDesc, HostContext) -> Property HasInfo addPrivData v = pureInfoProperty (show v) $ mempty { _privData = S.singleton v } {- Gets the requested field's value, in the specified context if it's - available, from the host's local privdata cache. -} getLocalPrivData :: PrivDataField -> Context -> IO (Maybe PrivData) getLocalPrivData field context = getPrivData field context . fromMaybe M.empty <$> localcache where localcache = catchDefaultIO Nothing $ readish <$> readFile privDataLocal type PrivMap = M.Map (PrivDataField, Context) PrivData -- | Get only the set of PrivData that the Host's Info says it uses. filterPrivData :: Host -> PrivMap -> PrivMap filterPrivData host = M.filterWithKey (\k _v -> S.member k used) where used = S.map (\(f, _, c) -> (f, mkHostContext c (hostName host))) $ _privData $ hostInfo host getPrivData :: PrivDataField -> Context -> PrivMap -> Maybe PrivData getPrivData field context = M.lookup (field, context) setPrivData :: PrivDataField -> Context -> IO () setPrivData field context = do putStrLn "Enter private data on stdin; ctrl-D when done:" setPrivDataTo field context =<< hGetContentsStrict stdin dumpPrivData :: PrivDataField -> Context -> IO () dumpPrivData field context = maybe (error "Requested privdata is not set.") putStrLn =<< (getPrivData field context <$> decryptPrivData) editPrivData :: PrivDataField -> Context -> IO () editPrivData field context = do v <- getPrivData field context <$> decryptPrivData v' <- withTmpFile "propellorXXXX" $ \f h -> do hClose h maybe noop (writeFileProtected f) v editor <- getEnvDefault "EDITOR" "vi" unlessM (boolSystem editor [File f]) $ error "Editor failed; aborting." readFile f setPrivDataTo field context v' listPrivDataFields :: [Host] -> IO () listPrivDataFields hosts = do m <- decryptPrivData section "Currently set data:" showtable $ map mkrow (M.keys m) let missing = M.keys $ M.difference wantedmap m unless (null missing) $ do section "Missing data that would be used if set:" showtable $ map mkrow missing section "How to set missing data:" showSet $ map (\(f, c) -> (f, c, join $ M.lookup (f, c) descmap)) missing where header = ["Field", "Context", "Used by"] mkrow k@(field, (Context context)) = [ shellEscape $ show field , shellEscape context , intercalate ", " $ sort $ fromMaybe [] $ M.lookup k usedby ] mkhostmap host mkv = M.fromList $ map (\(f, d, c) -> ((f, mkHostContext c (hostName host)), mkv d)) $ S.toList $ _privData $ hostInfo host usedby = M.unionsWith (++) $ map (\h -> mkhostmap h $ const $ [hostName h]) hosts wantedmap = M.fromList $ zip (M.keys usedby) (repeat "") descmap = M.unions $ map (\h -> mkhostmap h id) hosts section desc = putStrLn $ "\n" ++ desc showtable rows = do putStr $ unlines $ formatTable $ tableWithHeader header rows setPrivDataTo :: PrivDataField -> Context -> PrivData -> IO () setPrivDataTo field context value = do makePrivDataDir m <- decryptPrivData let m' = M.insert (field, context) (chomp value) m gpgEncrypt privDataFile (show m') putStrLn "Private data set." void $ boolSystem "git" [Param "add", File privDataFile] where chomp s | end s == "\n" = chomp (beginning s) | otherwise = s decryptPrivData :: IO PrivMap decryptPrivData = fromMaybe M.empty . readish <$> gpgDecrypt privDataFile makePrivDataDir :: IO () makePrivDataDir = createDirectoryIfMissing False privDataDir
avengerpenguin/propellor
src/Propellor/PrivData.hs
bsd-2-clause
7,060
127
18
1,237
1,984
1,077
907
160
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Общая библиотека </title> <maps> <homeID>commonlib</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Содержание</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Избранное</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/commonlib/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs
apache-2.0
1,015
77
66
157
489
245
244
-1
-1
{-# LANGUAGE ConstraintKinds, TemplateHaskell, PolyKinds, TypeFamilies, RankNTypes #-} module T7021a where import GHC.Prim import Language.Haskell.TH type IOable a = (Show a, Read a) type family ALittleSilly :: Constraint data Proxy a = Proxy foo :: IOable a => a foo = undefined baz :: a b => Proxy a -> b baz = undefined bar :: ALittleSilly => a bar = undefined test :: Q Exp test = do Just fooName <- lookupValueName "foo" Just bazName <- lookupValueName "baz" Just barName <- lookupValueName "bar" reify fooName reify bazName reify barName [t| forall a. (Show a, (Read a, Num a)) => a -> a |] [| \_ -> 0 |]
spacekitteh/smcghc
testsuite/tests/th/T7021a.hs
bsd-3-clause
652
0
8
150
190
98
92
-1
-1
module EitherIn1 where import Prelude -- test introduce patterns -- select x on lhs of g and introduce patterns for the list type... g :: [Int] -> Int g x = head x + tail (head x)
kmate/HaRe
old/testing/introPattern/EitherIn1.hs
bsd-3-clause
183
0
8
40
45
25
20
4
1
{-# LANGUAGE CPP #-} {-# OPTIONS_HADDOCK hide #-} -- GIMP Toolkit (GTK) FFI extras and version dependencies -- -- Author : Axel Simon -- -- Created: 22 June 2001 -- -- Copyright (C) 1999-2005 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. -- -- #hide -- | -- -- This module serves as an impedance matcher for different compiler -- versions. It also adds a few FFI utility functions. -- module System.Glib.FFI ( nullForeignPtr, maybeNull, newForeignPtr, withForeignPtrs, #if MIN_VERSION_base(4,4,0) unsafePerformIO, unsafeForeignPtrToPtr, #endif module Foreign, module Foreign.C ) where -- We should almost certainly not be using the standard free function anywhere -- in the glib or gtk bindings, so we do not re-export it from this module. import Foreign.C #if MIN_VERSION_base(4,4,0) import Foreign hiding (unsafePerformIO, unsafeForeignPtrToPtr, newForeignPtr, free) import System.IO.Unsafe (unsafePerformIO) import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) #else import Foreign hiding (newForeignPtr, free) #endif import qualified Foreign.Concurrent newForeignPtr :: Ptr a -> FinalizerPtr a -> IO (ForeignPtr a) newForeignPtr p finalizer = Foreign.Concurrent.newForeignPtr p (mkFinalizer finalizer p) foreign import ccall "dynamic" mkFinalizer :: FinalizerPtr a -> Ptr a -> IO () nullForeignPtr :: ForeignPtr a nullForeignPtr = unsafePerformIO $ newForeignPtr_ nullPtr -- This is useful when it comes to marshaling lists of GObjects -- withForeignPtrs :: [ForeignPtr a] -> ([Ptr a] -> IO b) -> IO b withForeignPtrs fptrs body = do result <- body (map unsafeForeignPtrToPtr fptrs) mapM_ touchForeignPtr fptrs return result -- A marshaling utility function that is used by the code produced by the code -- generator to marshal return values that can be null maybeNull :: (IO (Ptr a) -> IO a) -> IO (Ptr a) -> IO (Maybe a) maybeNull marshal genPtr = do ptr <- genPtr if ptr == nullPtr then return Nothing else do result <- marshal (return ptr) return (Just result)
mimi1vx/gtk2hs
glib/System/Glib/FFI.hs
gpl-3.0
2,536
0
13
460
423
236
187
31
2
{-| Module : Idris.Elab.Quasiquote Description : Code to elaborate quasiquotations. License : BSD3 Maintainer : The Idris Community. -} module Idris.Elab.Quasiquote (extractUnquotes) where import Idris.AbsSyntax import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.TT extract1 :: Int -> (PTerm -> a) -> PTerm -> Elab' aux (a, [(Name, PTerm)]) extract1 n c tm = do (tm', ex) <- extractUnquotes n tm return (c tm', ex) extract2 :: Int -> (PTerm -> PTerm -> a) -> PTerm -> PTerm -> Elab' aux (a, [(Name, PTerm)]) extract2 n c a b = do (a', ex1) <- extractUnquotes n a (b', ex2) <- extractUnquotes n b return (c a' b', ex1 ++ ex2) extractTUnquotes :: Int -> PTactic -> Elab' aux (PTactic, [(Name, PTerm)]) extractTUnquotes n (Rewrite t) = extract1 n Rewrite t extractTUnquotes n (LetTac name t) = extract1 n (LetTac name) t extractTUnquotes n (LetTacTy name t1 t2) = extract2 n (LetTacTy name) t1 t2 extractTUnquotes n (Exact tm) = extract1 n Exact tm extractTUnquotes n (Try tac1 tac2) = do (tac1', ex1) <- extractTUnquotes n tac1 (tac2', ex2) <- extractTUnquotes n tac2 return (Try tac1' tac2', ex1 ++ ex2) extractTUnquotes n (TSeq tac1 tac2) = do (tac1', ex1) <- extractTUnquotes n tac1 (tac2', ex2) <- extractTUnquotes n tac2 return (TSeq tac1' tac2', ex1 ++ ex2) extractTUnquotes n (ApplyTactic t) = extract1 n ApplyTactic t extractTUnquotes n (ByReflection t) = extract1 n ByReflection t extractTUnquotes n (Reflect t) = extract1 n Reflect t extractTUnquotes n (GoalType s tac) = do (tac', ex) <- extractTUnquotes n tac return (GoalType s tac', ex) extractTUnquotes n (TCheck t) = extract1 n TCheck t extractTUnquotes n (TEval t) = extract1 n TEval t extractTUnquotes n (Claim name t) = extract1 n (Claim name) t extractTUnquotes n tac = return (tac, []) -- the rest don't contain PTerms, or have been desugared away extractPArgUnquotes :: Int -> PArg -> Elab' aux (PArg, [(Name, PTerm)]) extractPArgUnquotes d (PImp p m opts n t) = do (t', ex) <- extractUnquotes d t return (PImp p m opts n t', ex) extractPArgUnquotes d (PExp p opts n t) = do (t', ex) <- extractUnquotes d t return (PExp p opts n t', ex) extractPArgUnquotes d (PConstraint p opts n t) = do (t', ex) <- extractUnquotes d t return (PConstraint p opts n t', ex) extractPArgUnquotes d (PTacImplicit p opts n scpt t) = do (scpt', ex1) <- extractUnquotes d scpt (t', ex2) <- extractUnquotes d t return (PTacImplicit p opts n scpt' t', ex1 ++ ex2) extractDoUnquotes :: Int -> PDo -> Elab' aux (PDo, [(Name, PTerm)]) extractDoUnquotes d (DoExp fc tm) = do (tm', ex) <- extractUnquotes d tm return (DoExp fc tm', ex) extractDoUnquotes d (DoBind fc n nfc tm) = do (tm', ex) <- extractUnquotes d tm return (DoBind fc n nfc tm', ex) extractDoUnquotes d (DoBindP fc t t' alts) = fail "Pattern-matching binds cannot be quasiquoted" extractDoUnquotes d (DoLet fc rc n nfc v b) = do (v', ex1) <- extractUnquotes d v (b', ex2) <- extractUnquotes d b return (DoLet fc rc n nfc v' b', ex1 ++ ex2) extractDoUnquotes d (DoLetP fc t t' alts) = fail "Pattern-matching lets cannot be quasiquoted" extractDoUnquotes d (DoRewrite fc h) = fail "Rewrites in Do block cannot be quasiquoted" extractUnquotes :: Int -> PTerm -> Elab' aux (PTerm, [(Name, PTerm)]) extractUnquotes n (PLam fc name nfc ty body) = do (ty', ex1) <- extractUnquotes n ty (body', ex2) <- extractUnquotes n body return (PLam fc name nfc ty' body', ex1 ++ ex2) extractUnquotes n (PPi plicity name fc ty body) = do (ty', ex1) <- extractUnquotes n ty (body', ex2) <- extractUnquotes n body return (PPi plicity name fc ty' body', ex1 ++ ex2) extractUnquotes n (PLet fc rc name nfc ty val body) = do (ty', ex1) <- extractUnquotes n ty (val', ex2) <- extractUnquotes n val (body', ex3) <- extractUnquotes n body return (PLet fc rc name nfc ty' val' body', ex1 ++ ex2 ++ ex3) extractUnquotes n (PTyped tm ty) = do (tm', ex1) <- extractUnquotes n tm (ty', ex2) <- extractUnquotes n ty return (PTyped tm' ty', ex1 ++ ex2) extractUnquotes n (PApp fc f args) = do (f', ex1) <- extractUnquotes n f args' <- mapM (extractPArgUnquotes n) args let (args'', exs) = unzip args' return (PApp fc f' args'', ex1 ++ concat exs) extractUnquotes n (PAppBind fc f args) = do (f', ex1) <- extractUnquotes n f args' <- mapM (extractPArgUnquotes n) args let (args'', exs) = unzip args' return (PAppBind fc f' args'', ex1 ++ concat exs) extractUnquotes n (PCase fc expr cases) = do (expr', ex1) <- extractUnquotes n expr let (pats, rhss) = unzip cases (pats', exs1) <- fmap unzip $ mapM (extractUnquotes n) pats (rhss', exs2) <- fmap unzip $ mapM (extractUnquotes n) rhss return (PCase fc expr' (zip pats' rhss'), ex1 ++ concat exs1 ++ concat exs2) extractUnquotes n (PIfThenElse fc c t f) = do (c', ex1) <- extractUnquotes n c (t', ex2) <- extractUnquotes n t (f', ex3) <- extractUnquotes n f return (PIfThenElse fc c' t' f', ex1 ++ ex2 ++ ex3) extractUnquotes n (PRewrite fc by x y z) = do (x', ex1) <- extractUnquotes n x (y', ex2) <- extractUnquotes n y case z of Just zz -> do (z', ex3) <- extractUnquotes n zz return (PRewrite fc by x' y' (Just z'), ex1 ++ ex2 ++ ex3) Nothing -> return (PRewrite fc by x' y' Nothing, ex1 ++ ex2) extractUnquotes n (PPair fc hls info l r) = do (l', ex1) <- extractUnquotes n l (r', ex2) <- extractUnquotes n r return (PPair fc hls info l' r', ex1 ++ ex2) extractUnquotes n (PDPair fc hls info a b c) = do (a', ex1) <- extractUnquotes n a (b', ex2) <- extractUnquotes n b (c', ex3) <- extractUnquotes n c return (PDPair fc hls info a' b' c', ex1 ++ ex2 ++ ex3) extractUnquotes n (PAlternative ms b alts) = do alts' <- mapM (extractUnquotes n) alts let (alts'', exs) = unzip alts' return (PAlternative ms b alts'', concat exs) extractUnquotes n (PHidden tm) = do (tm', ex) <- extractUnquotes n tm return (PHidden tm', ex) extractUnquotes n (PGoal fc a name b) = do (a', ex1) <- extractUnquotes n a (b', ex2) <- extractUnquotes n b return (PGoal fc a' name b', ex1 ++ ex2) extractUnquotes n (PDoBlock steps) = do steps' <- mapM (extractDoUnquotes n) steps let (steps'', exs) = unzip steps' return (PDoBlock steps'', concat exs) extractUnquotes n (PIdiom fc tm) = fmap (\(tm', ex) -> (PIdiom fc tm', ex)) $ extractUnquotes n tm extractUnquotes n (PProof tacs) = do (tacs', exs) <- fmap unzip $ mapM (extractTUnquotes n) tacs return (PProof tacs', concat exs) extractUnquotes n (PTactics tacs) = do (tacs', exs) <- fmap unzip $ mapM (extractTUnquotes n) tacs return (PTactics tacs', concat exs) extractUnquotes n (PElabError err) = fail "Can't quasiquote an error" extractUnquotes n (PCoerced tm) = do (tm', ex) <- extractUnquotes n tm return (PCoerced tm', ex) extractUnquotes n (PDisamb ns tm) = do (tm', ex) <- extractUnquotes n tm return (PDisamb ns tm', ex) extractUnquotes n (PUnifyLog tm) = fmap (\(tm', ex) -> (PUnifyLog tm', ex)) $ extractUnquotes n tm extractUnquotes n (PNoImplicits tm) = fmap (\(tm', ex) -> (PNoImplicits tm', ex)) $ extractUnquotes n tm extractUnquotes n (PQuasiquote tm goal) = fmap (\(tm', ex) -> (PQuasiquote tm' goal, ex)) $ extractUnquotes (n+1) tm extractUnquotes n (PUnquote tm) | n == 0 = do n <- getNameFrom (sMN 0 "unquotation") return (PRef (fileFC "(unquote)") [] n, [(n, tm)]) | otherwise = fmap (\(tm', ex) -> (PUnquote tm', ex)) $ extractUnquotes (n-1) tm extractUnquotes n (PRunElab fc tm ns) = fmap (\(tm', ex) -> (PRunElab fc tm' ns, ex)) $ extractUnquotes n tm extractUnquotes n (PConstSugar fc tm) = extractUnquotes n tm extractUnquotes n x = return (x, []) -- no subterms!
kojiromike/Idris-dev
src/Idris/Elab/Quasiquote.hs
bsd-3-clause
8,061
0
16
1,913
3,598
1,796
1,802
164
2
module T14365A where import {-# SOURCE #-} T14365B main = return ()
shlevy/ghc
testsuite/tests/deriving/should_fail/T14365A.hs
bsd-3-clause
70
0
6
14
18
11
7
3
1
---------------------------------------------------------------------------- -- -- Pretty-printing of common Cmm types -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- -- -- This is where we walk over Cmm emitting an external representation, -- suitable for parsing, in a syntax strongly reminiscent of C--. This -- is the "External Core" for the Cmm layer. -- -- As such, this should be a well-defined syntax: we want it to look nice. -- Thus, we try wherever possible to use syntax defined in [1], -- "The C-- Reference Manual", http://www.cminusminus.org/. We differ -- slightly, in some cases. For one, we use I8 .. I64 for types, rather -- than C--'s bits8 .. bits64. -- -- We try to ensure that all information available in the abstract -- syntax is reproduced, or reproducible, in the concrete syntax. -- Data that is not in printed out can be reconstructed according to -- conventions used in the pretty printer. There are at least two such -- cases: -- 1) if a value has wordRep type, the type is not appended in the -- output. -- 2) MachOps that operate over wordRep type are printed in a -- C-style, rather than as their internal MachRep name. -- -- These conventions produce much more readable Cmm output. -- -- A useful example pass over Cmm is in nativeGen/MachCodeGen.hs -- {-# OPTIONS_GHC -fno-warn-orphans #-} module PprCmmExpr ( pprExpr, pprLit ) where import CmmExpr import Outputable import Data.Maybe import Numeric ( fromRat ) ----------------------------------------------------------------------------- instance Outputable CmmExpr where ppr e = pprExpr e instance Outputable CmmReg where ppr e = pprReg e instance Outputable CmmLit where ppr l = pprLit l instance Outputable LocalReg where ppr e = pprLocalReg e instance Outputable Area where ppr e = pprArea e instance Outputable GlobalReg where ppr e = pprGlobalReg e -- -------------------------------------------------------------------------- -- Expressions -- pprExpr :: CmmExpr -> SDoc pprExpr e = sdocWithDynFlags $ \dflags -> case e of CmmRegOff reg i -> pprExpr (CmmMachOp (MO_Add rep) [CmmReg reg, CmmLit (CmmInt (fromIntegral i) rep)]) where rep = typeWidth (cmmRegType dflags reg) CmmLit lit -> pprLit lit _other -> pprExpr1 e -- Here's the precedence table from CmmParse.y: -- %nonassoc '>=' '>' '<=' '<' '!=' '==' -- %left '|' -- %left '^' -- %left '&' -- %left '>>' '<<' -- %left '-' '+' -- %left '/' '*' '%' -- %right '~' -- We just cope with the common operators for now, the rest will get -- a default conservative behaviour. -- %nonassoc '>=' '>' '<=' '<' '!=' '==' pprExpr1, pprExpr7, pprExpr8 :: CmmExpr -> SDoc pprExpr1 (CmmMachOp op [x,y]) | Just doc <- infixMachOp1 op = pprExpr7 x <+> doc <+> pprExpr7 y pprExpr1 e = pprExpr7 e infixMachOp1, infixMachOp7, infixMachOp8 :: MachOp -> Maybe SDoc infixMachOp1 (MO_Eq _) = Just (text "==") infixMachOp1 (MO_Ne _) = Just (text "!=") infixMachOp1 (MO_Shl _) = Just (text "<<") infixMachOp1 (MO_U_Shr _) = Just (text ">>") infixMachOp1 (MO_U_Ge _) = Just (text ">=") infixMachOp1 (MO_U_Le _) = Just (text "<=") infixMachOp1 (MO_U_Gt _) = Just (char '>') infixMachOp1 (MO_U_Lt _) = Just (char '<') infixMachOp1 _ = Nothing -- %left '-' '+' pprExpr7 (CmmMachOp (MO_Add rep1) [x, CmmLit (CmmInt i rep2)]) | i < 0 = pprExpr7 (CmmMachOp (MO_Sub rep1) [x, CmmLit (CmmInt (negate i) rep2)]) pprExpr7 (CmmMachOp op [x,y]) | Just doc <- infixMachOp7 op = pprExpr7 x <+> doc <+> pprExpr8 y pprExpr7 e = pprExpr8 e infixMachOp7 (MO_Add _) = Just (char '+') infixMachOp7 (MO_Sub _) = Just (char '-') infixMachOp7 _ = Nothing -- %left '/' '*' '%' pprExpr8 (CmmMachOp op [x,y]) | Just doc <- infixMachOp8 op = pprExpr8 x <+> doc <+> pprExpr9 y pprExpr8 e = pprExpr9 e infixMachOp8 (MO_U_Quot _) = Just (char '/') infixMachOp8 (MO_Mul _) = Just (char '*') infixMachOp8 (MO_U_Rem _) = Just (char '%') infixMachOp8 _ = Nothing pprExpr9 :: CmmExpr -> SDoc pprExpr9 e = case e of CmmLit lit -> pprLit1 lit CmmLoad expr rep -> ppr rep <> brackets (ppr expr) CmmReg reg -> ppr reg CmmRegOff reg off -> parens (ppr reg <+> char '+' <+> int off) CmmStackSlot a off -> parens (ppr a <+> char '+' <+> int off) CmmMachOp mop args -> genMachOp mop args genMachOp :: MachOp -> [CmmExpr] -> SDoc genMachOp mop args | Just doc <- infixMachOp mop = case args of -- dyadic [x,y] -> pprExpr9 x <+> doc <+> pprExpr9 y -- unary [x] -> doc <> pprExpr9 x _ -> pprTrace "PprCmm.genMachOp: machop with strange number of args" (pprMachOp mop <+> parens (hcat $ punctuate comma (map pprExpr args))) empty | isJust (infixMachOp1 mop) || isJust (infixMachOp7 mop) || isJust (infixMachOp8 mop) = parens (pprExpr (CmmMachOp mop args)) | otherwise = char '%' <> ppr_op <> parens (commafy (map pprExpr args)) where ppr_op = text (map (\c -> if c == ' ' then '_' else c) (show mop)) -- replace spaces in (show mop) with underscores, -- -- Unsigned ops on the word size of the machine get nice symbols. -- All else get dumped in their ugly format. -- infixMachOp :: MachOp -> Maybe SDoc infixMachOp mop = case mop of MO_And _ -> Just $ char '&' MO_Or _ -> Just $ char '|' MO_Xor _ -> Just $ char '^' MO_Not _ -> Just $ char '~' MO_S_Neg _ -> Just $ char '-' -- there is no unsigned neg :) _ -> Nothing -- -------------------------------------------------------------------------- -- Literals. -- To minimise line noise we adopt the convention that if the literal -- has the natural machine word size, we do not append the type -- pprLit :: CmmLit -> SDoc pprLit lit = sdocWithDynFlags $ \dflags -> case lit of CmmInt i rep -> hcat [ (if i < 0 then parens else id)(integer i) , ppUnless (rep == wordWidth dflags) $ space <> dcolon <+> ppr rep ] CmmFloat f rep -> hsep [ double (fromRat f), dcolon, ppr rep ] CmmVec lits -> char '<' <> commafy (map pprLit lits) <> char '>' CmmLabel clbl -> ppr clbl CmmLabelOff clbl i -> ppr clbl <> ppr_offset i CmmLabelDiffOff clbl1 clbl2 i -> ppr clbl1 <> char '-' <> ppr clbl2 <> ppr_offset i CmmBlock id -> ppr id CmmHighStackMark -> text "<highSp>" pprLit1 :: CmmLit -> SDoc pprLit1 lit@(CmmLabelOff {}) = parens (pprLit lit) pprLit1 lit = pprLit lit ppr_offset :: Int -> SDoc ppr_offset i | i==0 = empty | i>=0 = char '+' <> int i | otherwise = char '-' <> int (-i) -- -------------------------------------------------------------------------- -- Registers, whether local (temps) or global -- pprReg :: CmmReg -> SDoc pprReg r = case r of CmmLocal local -> pprLocalReg local CmmGlobal global -> pprGlobalReg global -- -- We only print the type of the local reg if it isn't wordRep -- pprLocalReg :: LocalReg -> SDoc pprLocalReg (LocalReg uniq rep) -- = ppr rep <> char '_' <> ppr uniq -- Temp Jan08 = char '_' <> ppr uniq <> (if isWord32 rep -- && not (isGcPtrType rep) -- Temp Jan08 -- sigh then dcolon <> ptr <> ppr rep else dcolon <> ptr <> ppr rep) where ptr = empty --if isGcPtrType rep -- then doubleQuotes (text "ptr") -- else empty -- Stack areas pprArea :: Area -> SDoc pprArea Old = text "old" pprArea (Young id) = hcat [ text "young<", ppr id, text ">" ] -- needs to be kept in syn with CmmExpr.hs.GlobalReg -- pprGlobalReg :: GlobalReg -> SDoc pprGlobalReg gr = case gr of VanillaReg n _ -> char 'R' <> int n -- Temp Jan08 -- VanillaReg n VNonGcPtr -> char 'R' <> int n -- VanillaReg n VGcPtr -> char 'P' <> int n FloatReg n -> char 'F' <> int n DoubleReg n -> char 'D' <> int n LongReg n -> char 'L' <> int n XmmReg n -> text "XMM" <> int n YmmReg n -> text "YMM" <> int n ZmmReg n -> text "ZMM" <> int n Sp -> text "Sp" SpLim -> text "SpLim" Hp -> text "Hp" HpLim -> text "HpLim" MachSp -> text "MachSp" UnwindReturnReg-> text "UnwindReturnReg" CCCS -> text "CCCS" CurrentTSO -> text "CurrentTSO" CurrentNursery -> text "CurrentNursery" HpAlloc -> text "HpAlloc" EagerBlackholeInfo -> text "stg_EAGER_BLACKHOLE_info" GCEnter1 -> text "stg_gc_enter_1" GCFun -> text "stg_gc_fun" BaseReg -> text "BaseReg" PicBaseReg -> text "PicBaseReg" ----------------------------------------------------------------------------- commafy :: [SDoc] -> SDoc commafy xs = fsep $ punctuate comma xs
tjakway/ghcjvm
compiler/cmm/PprCmmExpr.hs
bsd-3-clause
9,379
0
18
2,676
2,408
1,189
1,219
156
22
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeOperators #-} module Math.Hclaws.ConservationLaws ( Vector, CharField(..), System(..), Wave(..), WaveFan, Rarefaction(..), Shock(..), Linearity(..), rarefactionWave, shockWave, solutionForm, atSpeed, atPoint, integrateFanOnCurve, strengthsToFan, ) where import Prelude hiding (length) import Control.Monad.ST import GHC.TypeLits import qualified Data.Vector as V import qualified Math.FTensor.General as F import qualified Math.FTensor.Lib.Array as A import Math.Hclaws.LinearAlgebra import Math.Hclaws.Fan import qualified Math.Hclaws.Curves as C import qualified Math.Hclaws.Integration as I type Vector (dim::Nat) = F.TensorBoxed '[dim] Double type VectorField (dim::Nat) = Vector dim -> Vector dim type ScalarField (dim::Nat) = Vector dim -> Double type Curve (dim::Nat) = Double -> Vector dim type BasePointCurve (dim::Nat) = Vector dim -> Curve dim type PotentialSolution (dim::Nat) = Point -> Vector dim data Linearity = GNL | LDG | Neither deriving (Eq, Show) data CharField (n::Nat) = CharField { λ :: ScalarField n , r :: VectorField n , rarefactionCurve :: BasePointCurve n , shockCurve :: BasePointCurve n , shockSpeed :: Vector n -> Vector n -> Double , linearity :: Linearity } data System (n::Nat) = System { flux :: VectorField n , dFlux :: Vector n -> F.TensorBoxed '[n, n] Double , fields :: [CharField n] , solveRiemann :: Vector n -> Vector n -> WaveFan n } data Rarefaction (n::Nat) = Rarefaction { speedL :: Double , speedR :: Double , function :: Double -> Vector n , rFamily :: Int } instance Show (Rarefaction n) where show Rarefaction{..} = "Rarefaction {speedL = " ++ show speedL ++ ", speedR = " ++ show speedR ++ ", rFamily = " ++ show rFamily ++ "}" data Shock = Shock { speed :: Double , sFamily :: Int } deriving Show data Wave (n::Nat) = RWave (Rarefaction n) | SWave Shock deriving Show fastestSpeed :: Wave n -> Double fastestSpeed (RWave Rarefaction{..}) = speedR fastestSpeed (SWave Shock{..}) = speed rarefactionWave :: CharField n -> Int -> Vector n -> Vector n -> Wave n rarefactionWave field familyI uL uR = RWave Rarefaction { speedL = λ field uL , speedR = λ field uR , function = \s -> rarefactionCurve field uL (s - λ field uL) , rFamily = familyI } shockWave :: CharField n -> Int -> Vector n -> Vector n -> Wave n shockWave field familyI uL uR = SWave Shock {speed = shockSpeed field uL uR, sFamily = familyI} type WaveFan (n::Nat) = Fan (Vector n) (Wave n) -- can't use findOuterAt, because we don't need just the value atSpeed :: WaveFan n -> Double -> Vector n atSpeed (Fan v last) speed = case V.find (\(_, wave) -> speed <= fastestSpeed wave) v of Nothing -> last Just (_, RWave Rarefaction{..}) | speed > speedL -> function speed Just (value, _) -> value atPoint :: WaveFan n -> Point -> Vector n atPoint wf Point{..} = atSpeed wf (x/t) solutionForm :: System n -> PotentialSolution n -> Point -> F.TensorBoxed '[n, 2] Double solutionForm s u pt = F.Tensor $ runST $ do newArr <- A.new (2*len) let writeOne j = let idx = 2*j in A.write newArr idx (A.index uptArr j) >> A.write newArr (idx+1) (- A.index fuptArr j) loop j | j >= len = return () | otherwise = writeOne j >> loop (j+1) loop 0 A.freeze newArr where len = A.length uptArr upt@(F.Tensor uptArr) = u pt F.Tensor fuptArr = flux s upt accuracy = 0.000001 integrateFanOnCurve :: KnownNat n => C.Curve -> System n -> WaveFan n -> Vector n integrateFanOnCurve c s wf = I.adaptiveSimpsonLineIntegral accuracy c solutionForm' 0 1 where solutionForm' = solutionForm s $ atPoint wf strengthsToFan :: Vector n -> [CharField n] -> [Double] -> WaveFan n strengthsToFan uL fields strengths = Fan (V.generate (V.length shifted) unshift) (fst $ V.last shifted) where shifted = V.unfoldr strengthsToFan_ (uL, fields, strengths, [0..]) unshift 0 = (uL, snd $ V.unsafeIndex shifted 0) unshift i = (fst $ V.unsafeIndex shifted (i-1), snd $ V.unsafeIndex shifted i) strengthsToFan_ (_, [], [], _) = Nothing strengthsToFan_ (uL, _:fs, 0:ss, _:is) = strengthsToFan_ (uL, fs, ss, is) strengthsToFan_ (uL, f:fs, s:ss, i:is) = if linearity f == LDG || s < 0 then Just ( (u2Shock, shockWave f i uL u2Shock) , (u2Shock, fs, ss, is) ) else Just ( (u2Rare, rarefactionWave f i uL u2Rare) , (u2Rare, fs, ss, is) ) where u2Rare = rarefactionCurve f uL s u2Shock = shockCurve f uL s strengthsToFan_ _ = error "strengthsToFan"
mikebenfield/hclaws
src/Math/Hclaws/ConservationLaws.hs
isc
5,055
1
17
1,402
1,837
995
842
-1
-1
{-# LANGUAGE ExistentialQuantification #-} module ExpressionProblem3a ( Area(..) , Circle(..) , Shape(..) , Square(..) ) where -- Initial API -- Two shapes: square and circle -- One operation: area data Square = Square Double deriving Show data Circle = Circle Double deriving Show class Area s where area :: s -> Double instance Area Square where area (Square side) = side * side instance Area Circle where area (Circle radius) = pi * radius * radius data Shape = forall a. Area a => Shape a instance Area Shape where area (Shape s) = area s
rcook/expression-problem
src/ExpressionProblem3a.hs
mit
591
0
8
144
182
102
80
20
0
import MissingH.List main = do c <- getContents putStr (unlines(filter (\line -> contains "Haskell" line) (lines c)))
haskellbr/missingh
missingh-all/examples/simplegrep.hs
mit
151
0
14
50
57
28
29
5
1
module Diagram ( getDiagram, transformDiagram ) where import Types import Data.List cube = Diagram { points = [ Point 1 (-100) 100 (-100) "blue" "A" , Point 2 100 100 (-100) "green" "B" , Point 3 100 (-100) (-100) "black" "C" , Point 4 (-100) (-100) (-100) "brown" "D" , Point 5 (-100) 100 100 "red" "E" , Point 6 100 100 100 "red" "F" , Point 7 100 (-100) 100 "red" "G" , Point 8 (-100) (-100) 100 "red" "H" ] , edges = [ Edge 1 2 "red" "f" , Edge 2 3 "blue" "g" , Edge 3 4 "yellow" "h" , Edge 4 1 "black" "k" , Edge 5 6 "red" "l" , Edge 6 7 "blue" "m" , Edge 7 8 "yellow" "n" , Edge 8 5 "black" "o" , Edge 1 5 "magenta" "p" , Edge 2 6 "magenta" "q" , Edge 3 7 "magenta" "r" , Edge 4 8 "magenta" "s" ] } natural = Diagram { points = [ Point 0 (-100) 100 0 "black" "a" , Point 1 150 100 150 "blue" "F a" , Point 2 150 100 0 "magenta" "G a" , Point 3 150 100 (-150) "red" "H a" , Point 4 (-100) (-100) 0 "black" "b" , Point 5 150 (-100) 150 "blue" "F b" , Point 6 150 (-100) 0 "magenta" "G b" , Point 7 150 (-100) (-150) "red" "H b" ] , edges = [ Edge 0 1 "blue" "F" , Edge 0 2 "magenta" "G" , Edge 0 3 "red" "H" , Edge 4 5 "blue" "F" , Edge 4 6 "magenta" "G" , Edge 4 7 "red" "H" , Edge 0 4 "black" "f" , Edge 1 5 "blue" "F f" , Edge 2 6 "magenta" "G f" , Edge 3 7 "red" "H f" , Edge 1 2 "green" "αa" , Edge 2 3 "green" "βa" , Edge 5 6 "green" "αb" , Edge 6 7 "green" "βb" ] } eyeZ :: Double eyeZ = 500 getDiagram :: Diagram getDiagram = transformDiagram (Vector2 (-300) 160) natural transformDiagram :: Vector2 -> Diagram -> Diagram transformDiagram d diag = zSort $ diag { points = map (transformPoint a b) (points diag) } where -- convert delta to two angles (somewhat arbitrarily) a = atan2 (-(vx d)) eyeZ b = atan2 (-(vy d)) eyeZ transformPoint :: Double -> Double -> Point -> Point transformPoint a b pt = pt { x = x', y = y', z = z' } where (x', y', z') = rotatePt a b (x pt, y pt, z pt) rotatePt :: Double -> Double -> (Double, Double, Double) -> (Double, Double, Double) rotatePt a b = rotateX a . rotateY b rotateX :: Double -> (Double, Double, Double) -> (Double, Double, Double) rotateX a (x, y, z) = (co * x + si * z, y, co * z - si * x) where co = cos a si = sin a rotateY :: Double -> (Double, Double, Double) -> (Double, Double, Double) rotateY a (x, y, z) = (x, co * y - si * z, co * z + si * y) where co = cos a si = sin a zSort :: Diagram -> Diagram zSort diag = diag { points = sortBy cmpPoints (points diag) } where cmpPoints :: Point -> Point -> Ordering cmpPoints p1 p2 = compare (negate $ z p1) (negate $ z p2)
BartoszMilewski/ThreeDee
src/Diagram.hs
mit
3,371
0
11
1,403
1,297
692
605
73
1
{-# Language DeriveFunctor #-} module Unison.TypeVar where import Unison.Var (Var) import qualified Data.Set as Set import qualified Unison.Var as Var data TypeVar v = Universal v | Existential v deriving (Eq,Ord,Functor) underlying :: TypeVar v -> v underlying (Universal v) = v underlying (Existential v) = v instance Show v => Show (TypeVar v) where show (Universal v) = show v show (Existential v) = "'" ++ show v instance Var v => Var (TypeVar v) where named txt = Universal (Var.named txt) name v = Var.name (underlying v) qualifiedName v = Var.qualifiedName (underlying v) freshIn s v = Var.freshIn (Set.map underlying s) <$> v freshenId id v = Var.freshenId id <$> v clear v = Var.clear <$> v
nightscape/platform
shared/src/Unison/TypeVar.hs
mit
723
0
10
141
302
155
147
19
1
-- file: ch04/InteractWith.hs -- For command line framework import System.Environment (getArgs) interactWith function inputFile outputFile = do input <- readFile inputFile writeFile outputFile (function input) main = mainWith myFunction where mainWith function = do args <- getArgs case args of [input, output] -> interactWith function input output _ -> putStrLn "error: where are my two arguments?" -- replace "id" with the name of the desired fuction myFunction = id
imrehg/rwhaskell
ch04/InteractWith.hs
mit
547
0
12
147
115
57
58
11
2
module Tictactoe.Att.Move where import Data.Maybe import Tictactoe.Base import Tictactoe.Move.Base data ExpectedMove a b = NoExp | First | Either a b deriving (Show, Eq) type ScenarioMove = (BoardField, ExpectedMove Coords Coords) att :: ExpectedMove Coords Coords -> Board -> Maybe (BoardField, (ExpectedMove Coords Coords)) att exp board = case moveByScenario exp board of Just scenMove -> Just scenMove -- By scenario _ -> case defaultMove board oppSign mySign of -- default move Just boardField -> Just (boardField, NoExp) _ -> Nothing moveByScenario :: ExpectedMove Coords Coords -> Board -> Maybe ScenarioMove moveByScenario scen board = case scen of First -> case takenAnyEdge board of Just takenCoords -> case takenCoords of (x, 1) -> Just ((abs (x-2), 0, oppSign), NoExp) (1, y) -> Just ((0, abs (y-2), oppSign), NoExp) _ -> case takenAnyCorner board of Just takenCoords -> let (x, y) = oppositeCorner takenCoords in Just ((x, y, oppSign), Either (x, 1) (1, y)) _ -> Nothing Either (x1, y1) (x2, y2) -> case fieldExists board (x1, y1) of Just _ -> Just ((abs (x1-2), y2, oppSign), NoExp) _ -> case fieldExists board (x2, y2) of Just _ -> Just ((x1, abs (y2-2), oppSign), NoExp) _ -> Nothing NoExp -> Nothing
viktorasl/tictactoe-bot
src/Tictactoe/Att/Move.hs
mit
1,665
0
19
648
549
294
255
38
8
module Day15Spec (spec) where import Day15 import Test.Hspec main :: IO () main = hspec spec sampleInput :: String sampleInput = unlines [ "Disc #1 has 5 positions; at time=0, it is at position 4." , "Disc #2 has 2 positions; at time=0, it is at position 1." ] sampleParsed :: [Disc] sampleParsed = [ Disc 1 5 4, Disc 2 2 1 ] actualParsed :: [Disc] actualParsed = [ Disc 1 17 15 , Disc 2 3 2 , Disc 3 19 4 , Disc 4 13 2 , Disc 5 7 2 , Disc 6 5 0 ] spec :: Spec spec = do describe "parseInput" $ do it "parses sample input correctly" $ do parseInput sampleInput `shouldBe` sampleParsed it "parses actual input correctly" $ do actualInput <- readFile "inputs/day15.txt" parseInput actualInput `shouldBe` actualParsed describe "satisfy" $ do it "works on sample" $ do satisfy (map makeRequirement sampleParsed) `shouldBe` 5 describe "day15" $ do it "determines to drop the ball at time t=5 for sample input" $ do day15 sampleInput `shouldBe` 5 it "determines to drop the ball at time t=400589 for actual input" $ do actualInput <- readFile "inputs/day15.txt" day15 actualInput `shouldBe` 400589 describe "day15'" $ do it "determines to drop the ball at time t=85 for sample input" $ do day15' sampleInput `shouldBe` 85 it "determines to drop the ball at time t=3045959 for actual input" $ do actualInput <- readFile "inputs/day15.txt" day15' actualInput `shouldBe` 3045959
brianshourd/adventOfCode2016
test/Day15Spec.hs
mit
1,608
0
16
478
402
195
207
42
1
{----------------------------------------------------------------------------------------- Module name: Header.Converter Made by: Tomas Möre 2015 Conatins functions to convert one header format to another ------------------------------------------------------------------------------------------} {-# LANGUAGE OverloadedStrings, ScopedTypeVariables, DefaultSignatures #-} module Smutt.HTTP.Header.Field (parse) where import qualified Data.ByteString.Lazy.Char8 as BL import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TEnc import qualified Data.Text.Encoding.Error as TEnc -- | Encoding is supposed to be in ascii format. But this accepts UTF8 aswell. -- If there's any encoding errors we let them through and replace them with the UTF8 replacement character (�) -- Note that the field names are all converted to lowercase parse :: BL.ByteString -> Maybe (Text, Text) parse inStr = if value == "" then Nothing else Just (TL.toLower $ decode $ BL.dropWhile (==' ') name, decode (BL.dropWhile (==' ') $ BL.drop 1 value)) where (name, value) = BL.break (==':') inStr decode = TEnc.decodeUtf8With $ TEnc.replace '�'
black0range/Smutt
src/Smutt/HTTP/Header/Field.hs
mit
1,262
0
12
229
205
125
80
14
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} module Config where -- base import GHC.Generics (Generic) import Control.Exception (throwIO) import Control.Monad.Except (ExceptT, MonadError) import Control.Monad.Logger (runNoLoggingT, runStdoutLoggingT) import Control.Monad.Reader (MonadIO, MonadReader, ReaderT) import Control.Monad.Trans.Maybe (MaybeT (..), runMaybeT) import qualified Data.ByteString.Char8 as BS import Data.Monoid ((<>)) import Database.Persist.Postgresql (ConnectionPool, ConnectionString, createPostgresqlPool) import Network.Wai (Middleware) import Network.Wai.Middleware.RequestLogger (logStdout, logStdoutDev) import Servant (ServantErr) import System.Environment (lookupEnv) -- aeson import Data.Aeson (FromJSON) -- text import Data.Text (Text) -- yaml -- import Data.Yaml (fromJSON) -- | This type represents the effects we want to have for our application. -- We wrap the standard Servant monad with 'ReaderT Config', which gives us -- access to the application configuration using the 'MonadReader' -- interface's 'ask' function. -- -- By encapsulating the effects in our newtype, we can add layers to the -- monad stack without having to modify code that uses the current layout. newtype App a = App { runApp :: ReaderT Config (ExceptT ServantErr IO) a } deriving ( Functor, Applicative, Monad, MonadReader Config, MonadError ServantErr, MonadIO) type Port = Int data ServerConfig = ServerConfig { env :: Text , port :: Port } deriving (Generic, Show) instance FromJSON ServerConfig data AppConfig = AppConfig {server :: ServerConfig} deriving (Generic, Show) instance FromJSON AppConfig -- | The Config for our application is (for now) the 'Environment' we're -- running in and a Persistent 'ConnectionPool'. data Config = Config { getPool :: ConnectionPool , getEnv :: Environment , cPort :: Port } -- | Right now, we're distinguishing between three environments. We could -- also add a @Staging@ environment if we needed to. data Environment = Localhost | Development | Test | Staging | Production deriving (Eq, Show, Read) readEnv :: Text -> Environment readEnv txt = case txt of "localhost" -> Localhost "dev" -> Development "test" -> Test "stage" -> Staging "prod" -> Production -- | This returns a 'Middleware' based on the environment that we're in. setLogger :: Environment -> Middleware setLogger Test = id setLogger Localhost = logStdoutDev setLogger Development = logStdoutDev setLogger Production = logStdout -- | This function creates a 'ConnectionPool' for the given environment. -- For 'Development' and 'Test' environments, we use a stock and highly -- insecure connection string. The 'Production' environment acquires the -- information from environment variables that are set by the keter -- deployment application. makePool :: Environment -> IO ConnectionPool makePool Test = runNoLoggingT (createPostgresqlPool (connStr "test") (envPool Test)) makePool Development = runStdoutLoggingT (createPostgresqlPool (connStr "") (envPool Development)) makePool Localhost = runStdoutLoggingT (createPostgresqlPool (connStr "") (envPool Localhost)) makePool Production = do -- This function makes heavy use of the 'MaybeT' monad transformer, which -- might be confusing if you're not familiar with it. It allows us to -- combine the effects from 'IO' and the effect of 'Maybe' into a single -- "big effect", so that when we bind out of @MaybeT IO a@, we get an -- @a@. If we just had @IO (Maybe a)@, then binding out of the IO would -- give us a @Maybe a@, which would make the code quite a bit more -- verbose. pool <- runMaybeT $ do let keys = [ "host=" , "port=" , "user=" , "password=" , "dbname=" ] envs = [ "PGHOST" , "PGPORT" , "PGUSER" , "PGPASS" , "PGDATABASE" ] envVars <- traverse (MaybeT . lookupEnv) envs let prodStr = mconcat . zipWith (<>) keys $ BS.pack <$> envVars runStdoutLoggingT $ createPostgresqlPool prodStr (envPool Production) case pool of -- If we don't have a correct database configuration, we can't -- handle that in the program, so we throw an IO exception. This is -- one example where using an exception is preferable to 'Maybe' or -- 'Either'. Nothing -> throwIO (userError "Database Configuration not present in environment.") Just a -> return a -- | The number of pools to use for a given environment. envPool :: Environment -> Int envPool Test = 1 envPool Development = 1 envPool Localhost = 1 envPool Production = 8 -- | A basic 'ConnectionString' for local/test development. Pass in either -- @""@ for 'Development' or @"test"@ for 'Test'. connStr :: BS.ByteString -> ConnectionString connStr sfx = "host=localhost dbname=airport_service" <> sfx <> " user=test password=test port=5432"
tdox/aircraft-service
src/Config.hs
mit
5,860
0
17
1,833
856
491
365
92
5
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} module Main where import Control.Lens ((+~), ix) import qualified Data.Attoparsec.Text as P import Data.Bifunctor (first) import Data.Foldable (foldl') import Data.Function ((&)) import Data.List.PointedList.Circular (PointedList (..)) import qualified Data.List.PointedList.Circular as C import Data.Maybe (fromJust) import qualified Data.Text.IO as T import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V data Game = G { _scores :: !(Vector Int), _lastMarble :: {-# UNPACK #-}!Int } type Circle = PointedList Int numPlayers :: Game -> Int numPlayers = V.length . _scores make :: Int -> Int -> Game make np = G $ V.replicate np 0 gameP :: P.Parser Game gameP = make <$> (P.decimal <* P.string " players; last marble is worth ") <*> (P.decimal <* P.string " points") move :: Circle -> Int -> (Int, Circle) move c p | p `mod` 23 /= 0 = (0, C.insertLeft p $ C.moveN 2 c) | otherwise = (p + C._focus c', fromJust $ C.deleteRight c') where c' = C.moveN (-7) c play :: Game -> Vector Int play g = fst . foldl' go (_scores g, C.singleton 0) $ zip moves pieces where go (!ss, !circle) (!turn, !piece) = first (\points -> ss & ix turn +~ points) $ move circle piece moves = [i `mod` numPlayers g | i <- [0 ..]] pieces = [1 .. _lastMarble g] part1 :: Game -> Int part1 = V.maximum . play part1Tests :: Vector Bool part1Tests = V.zipWith3 (\np mp s -> s == part1 (make np mp)) ps lm ss where ps = V.fromList [10, 13, 17, 21, 30] lm = V.fromList [1618, 7999, 1104, 6111, 5807] ss = V.fromList [8317, 146373, 2764, 54718, 37305] part2 :: Game -> Int part2 g = V.maximum . play $ g { _lastMarble = 100 * _lastMarble g } main :: IO () main = do print $ V.and part1Tests input <- T.readFile "input" let game = either error id (P.parseOnly gameP input) print $ part1 game print $ part2 game
genos/online_problems
advent_of_code_2018/day09/src/Main.hs
mit
2,183
0
13
624
818
447
371
55
1
-- | A DSL for representing qualifies as a matched token module Text.Tokenify.Regex (Regex(..)) where -- | An Abstract data type for representing a regex data Regex s = Char Char | String s | Alt (Regex s) (Regex s) | Append (Regex s) (Regex s) | Range Char Char | Option (Regex s) | Repeat (Regex s) | Repeat1 (Regex s) | NoPass instance Show s => Show (Regex s) where show regex = "Regex \\" ++ showRegex regex ++ "\\" where showRegex :: Show s => Regex s -> String showRegex r = case r of Char c -> [c] String s -> show s -- -- TODO -- - make '(a|(b|c))' appear as '(a|b|c)' -- - make '(a|nopass)' appear as 'a' -- Alt l NoPass -> showRegex l Alt l r -> "("++showRegex l++"|"++showRegex r++")" Append l NoPass -> showRegex l Append l r -> showRegex l ++ showRegex r Range s e -> "["++[s]++"-"++[e]++"]" Option r -> "("++showRegex r++")?" Repeat r -> "("++showRegex r++")*" Repeat1 r -> "("++showRegex r++")+" unquote string = case string of '\"':xs -> impl xs "" other -> impl string "" where impl ('\"':[]) acc = acc impl (x:xs) acc = impl xs (acc++[x])
AKST/tokenify
src/Text/Tokenify/Regex.hs
mit
1,210
0
15
353
482
243
239
30
3
module Main where import StrawPoll.Types import Prelude hiding (div) import Blaze.React import qualified Text.Blaze.Event as E import qualified Text.Blaze.Event.Keycode as Keycode import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import qualified Blaze.React.Run.ReactJS as ReactJS import qualified Data.Text as T import Data.Time import Data.Aeson import Control.Monad.State import Control.Monad.Writer import NewPoll as NewPoll main :: IO () main = ReactJS.runApp $ ignoreWindowActions NewPoll.app
cschneid/strawpollhs
src/client/Main.hs
mit
622
0
7
146
132
90
42
17
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE OverloadedStrings #-} import Foreign.C.Types import qualified Language.C.Inline as C import qualified Language.C.Inline.Unsafe as CU C.include "<math.h>" C.include "<stdio.h>" test_cexp :: CDouble -> CDouble -> IO CDouble test_cexp x y = [C.exp| double{ cos($(double x)) + cos($(double y)) } |] test_cexp_unsafe :: CDouble -> CDouble -> IO CDouble test_cexp_unsafe x y = [CU.exp| double{ cos($(double x)) + cos($(double y)) } |] test_voidExp :: IO () test_voidExp = [C.exp| void { for (int i = 0; i < 10; i++){ printf("Hello\n"); } } |] main :: IO () main = do print =<< test_cexp 3 4 print =<< test_cexp_unsafe 3 4 test_voidExp
cirquit/Personal-Repository
Haskell/Playground/AdventOfCode/advent-coding/app/Main.hs
mit
818
0
8
186
173
97
76
22
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module Data.Holes ( Hole(..) , Holes(..) ) where import Control.Lens hiding (holes) import Data.Traversable import Data.Monoid import Data.Ix import Data.Bits newtype Hole h = Hole { inside :: h } deriving (Read, Show) data Holes a b c = Holes (a c) (b c) deriving (Read, Show) ------------------------------- -- HOLE ------------------------------- instance Functor Hole where fmap = fmapDefault instance Foldable Hole where foldMap = foldMapDefault instance Traversable Hole where traverse f (Hole h) = Hole <$> f h type instance Index (Hole h) = Int type instance IxValue (Hole h) = h instance Ixed (Hole h) where ix 0 f (Hole h) = Hole <$> f h ix _ _ hole = pure hole ------------------------------- -- HOLES ------------------------------- instance (Functor a, Functor b) => Functor (Holes a b) where fmap f (Holes a b) = Holes (fmap f a) (fmap f b) instance (Foldable a, Foldable b) => Foldable (Holes a b) where foldMap f (Holes a b) = foldMap f a <> foldMap f b instance (Traversable a, Traversable b) => Traversable (Holes a b) where traverse f (Holes a b) = Holes <$> traverse f a <*> traverse f b type instance Index (Holes a b h) = Int type instance IxValue (Holes a b h) = h instance ( Index (a h) ~ Int , Index (b h) ~ Int , IxValue (a h) ~ h , IxValue (b h) ~ h , Ixed (a h) , Ixed (b h) , Traversable a , Traversable b ) => Ixed (Holes a b h) where ix i f (Holes a b) = if i < h then Holes <$> ix i f a <*> pure b else Holes a <$> ix (i - h) f b where h = holes a ------------------------------- -- UTIL ------------------------------- holes :: (Traversable a, Num b) => a h -> b holes = sumOf traverse . (1 <$) ------------------------------- -- SYNONYMS ------------------------------- type H1 = Hole type H2 = Holes H1 H1 type H4 = Holes H2 H2 type H8 = Holes H4 H4 type H16 = Holes H8 H8
nickspinale/holes
Data/Holes.hs
mit
2,143
0
10
586
812
432
380
55
1
{-# LANGUAGE CPP, NoImplicitPrelude #-} {-# LANGUAGE RankNTypes #-} #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif module Data.Type.Equality.Compat ( #if MIN_VERSION_base(4,7,0) module Base #endif ) where #if MIN_VERSION_base(4,7,0) import Data.Type.Equality as Base #endif
haskell-compat/base-compat
base-compat/src/Data/Type/Equality/Compat.hs
mit
297
0
4
38
31
25
6
3
0
{-# htermination minimumBy :: (a -> a -> Ordering) -> [a] -> a #-} import List
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/List_minimumBy_1.hs
mit
79
0
3
16
5
3
2
1
0
module E.FromHs( convertDecls, convertRules, createInstanceRules, procAllSpecs, getMainFunction ) where import Char import Control.Applicative(Applicative) import Control.Monad.Error import Control.Monad.Identity import Control.Monad.RWS import List(isPrefixOf,nub) import Prelude import Text.Printf import qualified Data.Map as Map import qualified Data.Traversable as T import qualified Text.PrettyPrint.HughesPJ as PPrint import C.FFI import C.Prims as CP import DataConstructors import Doc.DocLike import Doc.PPrint import E.E import E.Eta import E.Eval(eval) import E.LetFloat(atomizeAp) import E.PrimDecode import E.Rules import E.Show(render) import E.Subst import E.Traverse import E.TypeCheck import E.Values import FrontEnd.Class import FrontEnd.HsSyn as HS import FrontEnd.Rename(unRename) import FrontEnd.SrcLoc import FrontEnd.Syn.Traverse(getNamesFromHsPat) import FrontEnd.Tc.Main(isTypePlaceholder) import FrontEnd.Tc.Module(TiData(..)) import FrontEnd.Tc.Type hiding(Rule(..)) import FrontEnd.Warning import Info.Types import Name.Id import Name.Name as Name import Name.Names import Name.VConsts import Options import PackedString import StringTable.Atom import Support.CanType import Support.FreeVars import Util.Gen import Util.NameMonad import Util.SetLike import qualified FlagOpts as FO import qualified FrontEnd.Tc.Type as T(Rule(..)) import qualified FrontEnd.Tc.Type as Type import qualified Info.Info as Info ump sl e = EError (show sl ++ ": Unmatched pattern") e r_bits32 = ELit litCons { litName = rt_bits32, litType = eHash } r_bits_max_ = ELit litCons { litName = rt_bits_max_, litType = eHash } r_bits_ptr_ = ELit litCons { litName = rt_bits_ptr_, litType = eHash } createIf e a b = do [tv] <- newVars [Unknown] return $ createIfv tv e a b createIfv v e a b = res where tv = v { tvrType = tBoolzh } ic = eCase (EVar tv) [Alt lTruezh a, Alt lFalsezh b] Unknown res = eCase e [Alt (litCons { litName = dc_Boolzh, litArgs = [tv], litType = tBool }) ic] Unknown ifzh e a b = eCase e [Alt lTruezh a, Alt lFalsezh b] Unknown newVars :: UniqueProducer m => [E] -> m [TVr] newVars xs = f xs [] where f [] xs = return $ reverse xs f (x:xs) ys = do s <- newUniq f xs (tVr (anonymous s) x:ys) tipe t = f t where f (TAp (TAp (TCon arr) a1) a2) | tyconName arr == tc_Arrow = f (TArrow a1 a2) f (TAp t1 t2) = eAp (f t1) (f t2) f (TArrow t1 t2) = EPi (tVr emptyId (f t1)) (f t2) f (TCon (Tycon n k)) | Just n' <- Map.lookup n primitiveAliases = ELit litCons { litName = n', litType = kind k } f (TCon (Tycon n k)) = ELit litCons { litName = n, litType = kind k } f (TVar tv) = EVar (cvar [] tv) f (TMetaVar mv) = cmvar mv f (TForAll vs (ps :=> t)) = foldr EPi (f t) (map (cvar $ freeVars ps) vs) f (TExists xs (_ :=> t)) = let xs' = map (kind . tyvarKind) xs in ELit litCons { litName = unboxedNameTuple TypeConstructor (length xs' + 1), litArgs = f t:xs', litType = eHash } f TAssoc {} = error "E.FromHs.tipe TAssoc" cvar fvs tv@Tyvar { tyvarName = n, tyvarKind = k } | tv `elem` fvs = setProperty prop_SCRUTINIZED (tVr (lt n) (kind k)) | otherwise = tVr (lt n) (kind k) cmvar MetaVar { metaKind = k } = tAbsurd (kind k) lt n | nameType n == TypeVal = toId n -- verifies namespace | otherwise = error "E.FromHs.lt" kind (KBase KUTuple) = eHash kind (KBase KHash) = eHash kind (KBase Star) = eStar kind (KBase KQuest) = eStar -- XXX why do these still exist? kind (KBase KQuestQuest) = eStar kind (Kfun k1 k2) = EPi (tVr emptyId (kind k1)) (kind k2) kind (KVar _) = error "Kind variable still existing." kind _ = error "E.FromHs.kind: unknown" fromTyvar (Tyvar n k) = tVr (toId n) (kind k) fromSigma (TForAll vs (_ :=> t)) = (map fromTyvar vs, tipe t) fromSigma t = ([], tipe t) monadicLookup' k m = case Map.lookup k m of Just x -> return x Nothing -> fail $ "key not found: " ++ show k convertValue n = do assumps <- asks ceAssumps dataTable <- asks ceDataTable t <- monadicLookup' n assumps let ty = removeNewtypes dataTable (tipe t) cc <- asks ceCoerce lm <- case Map.lookup n cc of Nothing -> do let (vs,_) = fromSigma t return (flip (foldr eLam) vs) Just CTId -> do return id Just ~(CTAbs ts) -> do return $ \e -> foldr eLam e (map fromTyvar ts) return (tVr (toId n) ty,ty,lm) --convertType t = do -- dataTable <- asks ceDataTable -- return $ removeNewtypes dataTable (tipe t) matchesConv ms = map v ms where v (HsMatch _ _ ps rhs wh) = (ps,rhs,wh) altConv as = map v as where v (HsAlt _ p rhs wh) = ([p],rhs,wh) argTypes e = span (sortSortLike . getType) (map tvrType xs) where (_,xs) = fromPi e argTypes' :: E -> ([E],E) argTypes' e = let (x,y) = fromPi e in (map tvrType y,x) getMainFunction :: Monad m => DataTable -> Name -> (Map.Map Name (TVr,E)) -> m (TVr,E) getMainFunction dataTable name ds = do mt <- case Map.lookup name ds of Just x -> return x Nothing -> fail $ "Could not find main function: " ++ show name let funcs = runIdentity $ T.mapM (\n -> return . EVar . fst $ runEither (show n) $ monadicLookup' n ds) sFuncNames nameToEntryPoint dataTable (fst mt) (toName Name.Val "theMain") Nothing funcs nameToEntryPoint :: Monad m => DataTable -> TVr -> Name -> Maybe FfiExport -> FuncNames E -> m (TVr,E) nameToEntryPoint dataTable main cname ffi ds = ans where ans = do let runMain = func_runMain ds runExpr = func_runExpr ds runNoWrapper = func_runNoWrapper ds runRaw = func_runRaw ds let e = case extractIO (getType maine) of Just x | not (fopts FO.Wrapper) -> EAp (EAp runNoWrapper x) maine Just x -> EAp (EAp runMain x ) maine Nothing | fopts FO.Raw -> EAp (EAp runRaw ty) maine Nothing -> EAp (EAp runExpr ty) maine ne = ELam worldVar (EAp e (EVar worldVar)) worldVar = tvr { tvrIdent = va1, tvrType = tWorld__ } theMainTvr = tVr (toId cname) (infertype dataTable ne) tvm@(TVr { tvrType = ty}) = main maine = foldl EAp (EVar tvm) [ tAbsurd k | TVr { tvrType = k } <- xs, sortKindLike k ] (_,xs) = fromPi ty return (tvrInfo_u (case ffi of Just ffi -> Info.insert ffi; Nothing -> id) $ setProperty prop_EXPORTED theMainTvr,ne) -- | create a RULE for each instance attached to the class methods. -- These rules allow early specialization of monomorphic code, and are -- eventually used in E.TypeAnalysis.expandPlaceholder to fill out -- the generic class method bodies. {-# NOINLINE createInstanceRules #-} createInstanceRules :: Monad m => DataTable -> ClassHierarchy -> [(TVr,E)] -> m Rules createInstanceRules dataTable classHierarchy funcs = return $ fromRules ans where ans = concatMap cClass (classRecords classHierarchy) cClass classRecord = concat [ method classRecord n mve | (n,TForAll _ (_ :=> t)) <- classAssumps classRecord, mve <- findName n ] method classRecord methodName (methodVar,_) = as where ty = tvrType methodVar defaultName = defaultInstanceName methodName as = [ rule t | Inst { instHead = _ :=> IsIn _ t } <- snub (findClassInsts classHierarchy (className classRecord)) ] rule t = makeRule ("Rule.{" ++ show name ++ "}") (toModule (show name),0) RuleSpecialization ruleFvs methodVar (vp:map EVar args) (removeNewtypes dataTable body) where ruleFvs = [ t | ~(EVar t) <- vs] ++ args (vp,vs) = valToPat' (removeNewtypes dataTable $ tipe t) name = instanceName methodName (getTypeCons t) bodyt = foldl eAp ty (vp:map EVar args) body = case findName name of Just (n,_) -> runIdentity $ do actuallySpecializeE (EVar n) bodyt Nothing -> case findName defaultName of Just (deftvr,_) | otherwise -> runIdentity $ do actuallySpecializeE (EVar deftvr) bodyt Nothing -> EError ( show methodName ++ ": undefined at type " ++ PPrint.render (pprint t)) bodyt --Just (deftvr,_) -> eLet tv vp $ runIdentity $ do actuallySpecializeE (EVar deftvr) (foldl eAp ty $ EVar tv:map EVar args) where -- foldl EAp (EAp (EVar deftvr) (EVar tv)) (map EVar args) where -- tv = tvr { tvrIdent = head [ n | n <- newIds (freeVars vp `mappend` fromList (map tvrIdent args))], tvrType = getType vp } --Just (deftvr,_) | null vs -> foldl EAp (EAp (EVar deftvr) vp) (map EVar args) -- this assumes the class argument is always the first type parameter (_,_:args') = fromPi ty (args,_) = span (sortKindLike . tvrType) args' someIds = newIds (fromList $ map tvrIdent args') valToPat' (ELit LitCons { litAliasFor = af, litName = x, litArgs = ts, litType = t }) = ans where ans = (ELit litCons { litAliasFor = af, litName = x, litArgs = ts', litType = t },ts') ts' = [ EVar (tVr j (getType z)) | z <- ts | j <- someIds] valToPat' (EPi tv@TVr { tvrType = a} b) = (EPi tvr { tvrType = a'} b',[a',b']) where a' = EVar (tVr ja (getType a)) b' = EVar (tVr jb (getType b)) (ja:jb:_) = someIds valToPat' x = error $ "FromHs.valToPat': " ++ show x funcsMap = Map.fromList [ (n,(v,e)) | (v,e) <- funcs, let Just n = fromId (tvrIdent v) ] findName name = case Map.lookup name funcsMap of Nothing -> fail $ "Cannot find: " ++ show name Just n -> return n getTypeCons (TCon (Tycon n _)) = n getTypeCons (TAp a _) = getTypeCons a getTypeCons (TArrow {}) = tc_Arrow getTypeCons x = error $ "getTypeCons: " ++ show x unbox :: DataTable -> E -> Id -> (E -> E) -> E unbox dataTable e _vn wtd | getType (getType e) == eHash = wtd e unbox dataTable e vn wtd = eCase e [Alt (litCons { litName = cna, litArgs = [tvra], litType = te }) (wtd (EVar tvra))] Unknown where te = getType e tvra = tVr vn sta Just (ExtTypeBoxed cna sta _) = lookupExtTypeInfo dataTable te createFunc :: [E] -> ([TVr] -> C (E -> E,E)) -> C E createFunc es ee = do dataTable <- getDataTable xs <- flip mapM es $ \te -> do eti <- ffiTypeInfo ExtTypeVoid te return [n] <- newVars [te] case eti of ExtTypeVoid -> fail "createFunc: attempt to pass a void argument" ExtTypeBoxed cn sta _ -> do [n'] <- newVars [sta] return (n,n',Just cn) ExtTypeRaw _ -> do return (n,n,Nothing) let tvrs' = [ n' | (_,n',_) <- xs ] tvrs = [ t | (t,_,_) <- xs] (me,innerE) <- ee tvrs' let eee = me $ foldr esr innerE xs esr (tvr,tvr',Just cn) e = eCase (EVar tvr) [Alt (litCons { litName = cn, litArgs = [tvr'], litType = tvrType tvr }) e] Unknown esr (_,_,Nothing) e = e return $ foldr ELam eee tvrs instance GenName String where genNames i = map (('x':) . show) [i..] {-# NOINLINE convertRules #-} convertRules :: Module -> TiData -> ClassHierarchy -> Map.Map Name Type -> DataTable -> [HsDecl] -> IO Rules convertRules mod tiData classHierarchy assumps dataTable hsDecls = ans where ans = do rawRules <- concatMapM g hsDecls return $ fromRules [ makeRule n (mod,i) (if catalyst then RuleCatalyst else RuleUser) vs head args e2 | (catalyst,n,vs,e1,e2) <- rawRules, let (EVar head,args) = fromAp e1 | i <- [1..] ] g (HsPragmaRules rs) = mapM f rs g _ = return [] f pr = do let ce = convertE tiData classHierarchy assumps dataTable (hsRuleSrcLoc pr) e1 <- ce (hsRuleLeftExpr pr) e2 <- ce (hsRuleRightExpr pr) (ts,cs) <- runNameMT $ do ts <- flip mapM (filter (sortKindLike . getType) $ freeVars e1) $ \tvr -> do --return (tvrIdent tvr,tvr) nn <- newNameFrom (map (:'\'':[]) ['a' ..]) return (tvrIdent tvr,tvr { tvrIdent = toId (toName TypeVal nn) }) cs <- flip mapM [toTVr assumps dataTable (toName Val v) | (v,_) <- hsRuleFreeVars pr ] $ \tvr -> do let ur = show $ unRename (toUnqualified $ runIdentity $ fromId (tvrIdent tvr)) nn <- newNameFrom (ur:map (\v -> ur ++ show v) [1 ::Int ..]) return (tvrIdent tvr,tvr { tvrIdent = toId (toName Val nn) }) return (ts,cs) let smt = substMap $ fromList [ (x,EVar y)| (x,y) <- ts ] sma = substMap $ fromList [ (x,EVar y)| (x,y) <- cs' ] cs' = [ (x,(tvrType_u smt y))| (x,y) <- cs ] e2' = deNewtype dataTable $ smt $ sma e2 --e2 <- atomizeAp False dataTable Stats.theStats mainModule e2' let e2 = atomizeAp mempty False dataTable e2' return (hsRuleIsMeta pr,hsRuleString pr,( snds (cs' ++ ts) ),eval $ smt $ sma e1,e2) convertE :: TiData -> ClassHierarchy -> Map.Map Name Type -> DataTable -> SrcLoc -> HsExp -> IO E convertE tiData classHierarchy assumps dataTable srcLoc exp = do [(_,_,e)] <- convertDecls tiData mempty classHierarchy assumps dataTable [HsPatBind srcLoc (HsPVar v_silly) (HsUnGuardedRhs exp) []] return e v_silly = toName Val ("Jhc@","silly") data CeEnv = CeEnv { ceAssumps :: Map.Map Name Type, ceCoerce :: Map.Map Name CoerceTerm, ceFuncs :: FuncNames E, ceProps :: IdMap Properties, ceSrcLoc :: SrcLoc, ceDataTable :: DataTable } newtype C a = Ce (RWST CeEnv [Warning] Int IO a) deriving(Monad,Applicative,Functor,MonadIO,MonadReader CeEnv,MonadState Int,MonadError IOError) instance MonadWarn C where addWarning w = liftIO (addWarning w) instance MonadSrcLoc C where getSrcLoc = asks ceSrcLoc instance MonadSetSrcLoc C where withSrcLoc' sl = local (\ce -> ce { ceSrcLoc = sl }) instance UniqueProducer C where newUniq = do i <- get put $! (i + 1) return i instance DataTableMonad C where getDataTable = asks ceDataTable applyCoersion :: CoerceTerm -> E -> C E applyCoersion CTId e = return e applyCoersion ct e = etaReduce `liftM` f ct e where f CTId e = return e f (CTAp ts) e = return $ foldl eAp e (map tipe ts) f (CTAbs ts) e = return $ foldr eLam e (map fromTyvar ts) f (CTCompose ct1 ct2) e = f ct1 =<< (f ct2 e) f (CTFun CTId) e = return e f (CTFun ct) e = do let EPi TVr { tvrType = ty } _ = getType e [y] <- newVars [ty] fgy <- f ct (EAp e (EVar y)) return (eLam y fgy) fromTuple_ :: Monad m => E -> m [E] fromTuple_ (ELit LitCons { litName = n, litArgs = as }) | Just c <- fromUnboxedNameTuple n, c == length as = return as fromTuple_ e = fail "fromTuple_ : not unboxed tuple" {-# NOINLINE convertDecls #-} convertDecls :: TiData -> IdMap Properties -> ClassHierarchy -> Map.Map Name Type -> DataTable -> [HsDecl] -> IO [(Name,TVr,E)] convertDecls tiData props classHierarchy assumps dataTable hsDecls = res where res = do (a,ws) <- evalRWST ans ceEnv 2 mapM_ addWarning ws return a ceEnv = CeEnv { ceCoerce = tiCoerce tiData, ceAssumps = assumps, ceFuncs = funcs, ceProps = props, ceSrcLoc = bogusASrcLoc, ceDataTable = dataTable } Identity funcs = T.mapM (return . EVar . toTVr assumps dataTable) sFuncNames Ce ans = do nds <- mapM cDecl' hsDecls return (map anninst $ concat nds) doNegate e = eAp (eAp (func_negate funcs) (getType e)) e anninst (a,b,c) | "Instance@" `isPrefixOf` show a = (a,setProperty prop_INSTANCE b, deNewtype dataTable c) | otherwise = (a,b, deNewtype dataTable c) -- first argument builds the actual call primitive, given -- (a) the C argtypes -- (b) the C return type -- (c) the extra return variables passed back in pointers -- (d) the arguments themselves -- (e) the real return type -- ccallHelper returns a function expression to perform the call, when given the arguments invalidDecl s = addWarn InvalidDecl s >> fail s ccallHelper :: ([ExtType] -> ExtType -> [ExtType] -> [E] -> E -> E) -> E -> C E ccallHelper myPrim ty = do let (ts,isIO,rt) = extractIO' ty es <- newVars [ t | t <- ts, not (sortKindLike t) ] let (rt':ras) = case fromTuple_ rt of Just (x:ys@(_:_)) -> (x:ys) _ -> [rt] ras' <- forM ras $ \t -> ffiTypeInfo ExtTypeVoid t return ffiTypeInfo Unknown rt' $ \pt -> do cts <- forM (filter (not . sortKindLike) ts) $ \t -> do ffiTypeInfo ExtTypeVoid t $ return [tvrWorld, tvrWorld2] <- newVars [tWorld__,tWorld__] let cFun = createFunc (map tvrType es) prim = myPrim (map extTypeInfoExtType cts) (extTypeInfoExtType pt) (map extTypeInfoExtType ras') case (isIO,pt,ras') of (True,ExtTypeVoid,[]) -> cFun $ \rs -> return (ELam tvrWorld, eStrictLet tvrWorld2 (prim (EVar tvrWorld :[EVar t | t <- rs ]) tWorld__) (eJustIO (EVar tvrWorld2) vUnit)) (False,ExtTypeVoid,_) -> invalidDecl "pure foreign function must return a non void value" (True,_,(_:_)) -> invalidDecl "IO-like functions may not return a tuple" (_,ExtTypeBoxed cn rtt' _,[]) -> do [rtVar,rtVar'] <- newVars [rt',rtt'] let rttIO' = ltTuple' [tWorld__, rtt'] case isIO of False -> cFun $ \rs -> return (id, eStrictLet rtVar' (prim [ EVar t | t <- rs ] rtt') (ELit $ litCons { litName = cn, litArgs = [EVar rtVar'], litType = rt' })) True -> cFun $ \rs -> return $ (,) (ELam tvrWorld) $ eCaseTup' (prim (EVar tvrWorld:[EVar t | t <- rs ]) rttIO') [tvrWorld2,rtVar'] (eLet rtVar (ELit $ litCons { litName = cn, litArgs = [EVar rtVar'], litType = rt' }) (eJustIO (EVar tvrWorld2) (EVar rtVar))) (True,ExtTypeRaw _,[]) -> do let rttIO' = ltTuple' [tWorld__, rt'] cFun $ \rs -> return (ELam tvrWorld,prim (EVar tvrWorld:[EVar t | t <- rs ]) rttIO') (False,ExtTypeRaw _,[]) -> do cFun $ \rs -> return (id,prim [EVar t | t <- rs ] rt') (False,_,(_:_)) -> do let rets = (rt':ras) rets' <- mapM unboxedVersion rets cFun $ \rs -> do fun <- extractUnboxedTup (prim [ EVar t | t <- rs ] (ltTuple' rets')) $ \vs -> do rv <- zipWithM marshallFromC vs rets return $ eTuple' rv return (id,fun) -- _ -> invalidDecl "foreign declaration is of incorrect form." --isExtTypeRaw ExtTypeRaw {} = True --isExtTypeRaw _ = False cDecl,cDecl' :: HsDecl -> C [(Name,TVr,E)] cDecl' d = withSrcLoc (srcLoc d) $ catchError (cDecl d) $ \ (e :: IOError) -> do warn (srcLoc d) InvalidDecl $ "caught error processing decl: " ++ show e return [] cDecl (HsForeignDecl sLoc (FfiSpec (Import cn req) _ Primitive) n _) = do let name = toName Name.Val n (var,ty,lamt) <- convertValue name let (ts,rt) = argTypes' ty es <- newVars [ t | t <- ts, not (sortKindLike t) ] result <- processPrim dataTable sLoc (toAtom cn) [ EVar e | e <- es, not (tvrType e == tUnit)] rt req return [(name,setProperty prop_INLINE var, lamt $ foldr ($) result (map ELam es))] cDecl (HsForeignDecl _ (FfiSpec (ImportAddr rcn req) _ _) n _) = do let name = toName Name.Val n (var,ty,lamt) <- convertValue name let (_ts,rt) = argTypes' ty expr x = return [(name,setProperty prop_INLINE var,lamt x)] prim = (AddrOf req $ packString rcn) -- this needs to be a boxed value since we can't have top-level -- unboxed values yet. ffiTypeInfo [] rt $ \eti -> do case eti of ExtTypeBoxed cn st _ -> do [uvar] <- newVars [st] expr $ eStrictLet uvar (EPrim prim [] st) (ELit (litCons { litName = cn, litArgs = [EVar uvar], litType = rt })) _ -> invalidDecl "foreign import of address must be of a boxed type" cDecl (HsForeignDecl _ (FfiSpec (Import rcn req) safe CCall) n _) = do let name = toName Name.Val n (var,ty,lamt) <- convertValue name result <- ccallHelper (\cts crt cras args rt -> EPrim (Func req (packString rcn) cts crt cras safe) args rt) ty return [(name,setProperty prop_INLINE var,lamt result)] cDecl (HsForeignDecl _ (FfiSpec Dynamic _ CCall) n _) = do -- XXX ensure that the type is of form FunPtr /ft/ -> /ft/ let name = toName Name.Val n (var,ty,lamt) <- convertValue name --let ((fptrTy:_), _) = argTypes' ty -- fty = discardArgs 1 ty result <- ccallHelper (\cts crt cras args rt -> EPrim (IFunc mempty (tail cts) crt) args rt) ty return [(name,setProperty prop_INLINE var,lamt result)] cDecl (HsForeignDecl _ (FfiSpec (Import rcn _) _ DotNet) n _) = do (var,ty,lamt) <- convertValue (toName Name.Val n) let (ts,isIO,rt') = extractIO' ty es <- newVars [ t | t <- ts, not (sortKindLike t) ] ffiTypeInfo [] rt' $ \pt -> do [tvrWorld, tvrWorld2] <- newVars [tWorld__,tWorld__] dnet <- parseDotNetFFI rcn let cFun = createFunc (map tvrType es) prim rs rtt = EPrim dnet result <- case (isIO,pt) of (True,ExtTypeVoid) -> cFun $ \rs -> return $ (,) (ELam tvrWorld) $ eStrictLet tvrWorld2 (prim rs "void" (EVar tvrWorld:[EVar t | t <- rs ]) tWorld__) (eJustIO (EVar tvrWorld2) vUnit) (False,ExtTypeVoid) -> invalidDecl "pure foreign function must return a valid value" _ -> do ExtTypeBoxed cn rtt' rtt <- lookupExtTypeInfo dataTable rt' [rtVar,rtVar'] <- newVars [rt',rtt'] let _rttIO = ltTuple [tWorld__, rt'] rttIO' = ltTuple' [tWorld__, rtt'] case isIO of False -> cFun $ \rs -> return $ (,) id $ eStrictLet rtVar' (prim rs rtt [ EVar t | t <- rs ] rtt') (ELit $ litCons { litName = cn, litArgs = [EVar rtVar'], litType = rt' }) True -> cFun $ \rs -> return $ (,) (ELam tvrWorld) $ eCaseTup' (prim rs rtt (EVar tvrWorld:[EVar t | t <- rs ]) rttIO') [tvrWorld2,rtVar'] (eLet rtVar (ELit $ litCons { litName = cn, litArgs = [EVar rtVar'], litType = rt' }) (eJustIO (EVar tvrWorld2) (EVar rtVar))) return [(toName Name.Val n,var,lamt result)] cDecl x@HsForeignDecl {} = invalidDecl ("Unsupported foreign declaration: "++ show x) cDecl (HsForeignExport _ ffi@FfiExport { ffiExportCName = ecn } n _) = do let name = ffiExportName ffi fn <- convertVar name tn <- convertVar (toName Name.Val n) (var,ty,lamt) <- convertValue name let --(argTys,retTy') = argTypes' ty --(isIO,retTy) = extractIO' retTy' (argTys,isIO,retTy) = extractIO' ty --retCTy <- if retTy == tUnit -- then return unboxedTyUnit -- else liftM (\(_, _, x) -> rawType x) $ lookupCType' dataTable retTy aets <- forM argTys $ \ty -> do ffiTypeInfo (Unknown,undefined,undefined) ty $ \eti -> do -- eti <- lookupExtTypeInfo dataTable ty ty' <- case eti of ExtTypeVoid -> invalidDecl "attempt to foreign export function with void argument" ExtTypeRaw _ -> do return ty ExtTypeBoxed _ ty' _ -> do return ty' [v] <- newVars [ty'] e <- marshallFromC (EVar v) ty return (e,v,ty') let argEs = [ e | (e,_,_) <- aets ] argTvrs = [ v | (_,v,_) <- aets ] argCTys = [ t | (_,_,t) <- aets ] fe <- actuallySpecializeE (EVar tn) ty let inner = foldl EAp fe argEs retE <- case isIO of False -> marshallToC inner retTy True -> do [world_, world__, ret] <- newVars [tWorld__, tWorld__, retTy] retMarshall <- if retTy == tUnit then return (ELit (unboxedTuple [])) else marshallToC (EVar ret) retTy return (eLam world_ (eCaseTup' (eAp inner (EVar world_)) [world__, ret] (ELit (unboxedTuple [EVar world__, retMarshall])))) let retCTy' = typeInfer dataTable retE -- trace ("retE: "++pprint retE) $ return () let result = foldr ELam retE argTvrs realRetCTy:realArgCTys <- mapM (\x -> extTypeInfoExtType `liftM` lookupExtTypeInfo dataTable x) (retTy:argTys) return [(name, tvrInfo_u (Info.insert ffi { ffiExportArgTypes = realArgCTys, ffiExportRetType = realRetCTy } ) (fmap (const (foldr tFunc retCTy' argCTys)) $ setProperty prop_EXPORTED fn), result)] cDecl (HsPatBind sl (HsPVar n) (HsUnGuardedRhs exp) []) | n == v_silly = do e <- cExpr exp return [(v_silly,tvr,e)] cDecl (HsPatBind sl p rhs wh) | (HsPVar n) <- p = do let name = toName Name.Val n (var,ty,lamt) <- convertValue name rhs <- cRhs sl rhs lv <- hsLetE wh rhs return [(name,var,lamt lv)] cDecl (HsPatBind sl p rhs wh) | (HsPVar n) <- p = do let name = toName Name.Val n (var,ty,lamt) <- convertValue name rhs <- cRhs sl rhs lv <- hsLetE wh rhs return [(name,var,lamt lv)] cDecl (HsPatBind sl p rhs wh) | (HsPVar n) <- p = do let name = toName Name.Val n (var,ty,lamt) <- convertValue name rhs <- cRhs sl rhs lv <- hsLetE wh rhs return [(name,var,lamt lv)] cDecl (HsFunBind [(HsMatch sl n ps rhs wh)]) | all isHsPVar ps = do let name = toName Name.Val n (var,ty,lamt) <- convertValue name rhs <- cRhs sl rhs lv <- hsLetE wh rhs lps <- lp ps lv return [(name,var,lamt lps )] cDecl (HsFunBind ms@((HsMatch sl n ps _ _):_)) = do let name = toName Name.Val n (var,t,lamt) <- convertValue name let (targs,eargs) = argTypes t numberPatterns = length ps bs' <- newVars (take numberPatterns eargs) let bs = map EVar bs' rt = discardArgs (length targs + numberPatterns) t z e = foldr eLam e bs' ms <- cMatchs bs (matchesConv ms) (ump sl rt) return [(name,var,lamt $ z ms )] cDecl cd@(HsClassDecl {}) = cClassDecl cd cDecl _ = return [] cExpr :: HsExp -> C E cExpr (HsAsPat n' (HsCon n)) = return $ constructionExpression dataTable (toName DataConstructor n) rt where t' = getAssump n' (_,rt) = argTypes' (tipe t') cExpr (HsLit (HsStringPrim s)) = return $ EPrim (PrimString (packString s)) [] r_bits_ptr_ cExpr (HsLit (HsString s)) = return $ E.Values.toE s cExpr (HsAsPat n' (HsLit (HsIntPrim i))) = ans where t' = getAssump n' ans = return $ ELit (LitInt (fromIntegral i) (tipe t')) cExpr (HsAsPat n' (HsLit (HsCharPrim i))) = ans where t' = getAssump n' ans = return $ ELit (LitInt (fromIntegral $ ord i) (tipe t')) cExpr (HsAsPat n' (HsLit (HsInt i))) = ans where t' = getAssump n' ty = tipe t' -- XXX this can allow us to create integer literals out of things that -- arn't in Num if we arn't careful ans = case lookupExtTypeInfo dataTable ty of Just (ExtTypeBoxed cn st _) -> return $ ELit (litCons { litName = cn, litArgs = [ELit (LitInt (fromIntegral i) st)], litType = ty }) _ -> return $ intConvert' funcs ty i --Just (cn,st,it) -> --cExpr (HsLit (HsInt i)) = return $ intConvert i cExpr (HsLit (HsChar ch)) = return $ toE ch cExpr (HsLit (HsCharPrim ch)) = return $ toEzh ch cExpr (HsLit (HsFrac i)) = return $ toE i cExpr (HsLambda sl ps e) | all isHsPVar ps = do e <- cExpr e lp ps e cExpr (HsInfixApp e1 v e2) = do v <- cExpr v e1 <- cExpr e1 e2 <- cExpr e2 return $ eAp (eAp v e1) e2 cExpr (HsLeftSection op e) = liftM2 eAp (cExpr op) (cExpr e) cExpr (HsApp (HsRightSection e op) e') = do op <- cExpr op e' <- cExpr e' e <- cExpr e return $ eAp (eAp op e') e cExpr (HsRightSection e op) = do cop <- cExpr op ce <- cExpr e let (_,TVr { tvrType = ty}:_) = fromPi (getType cop) [var] <- newVars [ty] return $ eLam var (eAp (eAp cop (EVar var)) ce) cExpr (HsApp e1 e2) = liftM2 eAp (cExpr e1) (cExpr e2) cExpr (HsParen e) = cExpr e cExpr (HsExpTypeSig _ e _) = cExpr e cExpr (HsNegApp e) = liftM doNegate (cExpr e) cExpr (HsLet dl e) = hsLet dl e cExpr (HsIf e a b) = join $ liftM3 createIf (cExpr e) (cExpr a) (cExpr b) cExpr (HsCase _ []) = error "empty case" cExpr (HsAsPat n HsError { hsExpString = msg }) = do ty <- convertTyp (toName Name.Val n) return $ EError msg ty cExpr (HsAsPat n hs@(HsCase e alts)) = do ty <- convertTyp (toName Name.Val n) scrut <- cExpr e cMatchs [scrut] (altConv alts) (EError ("No Match in Case expression at " ++ show (srcLoc hs)) ty) cExpr (HsTuple es) = liftM eTuple (mapM cExpr es) cExpr (HsUnboxedTuple es) = liftM eTuple' (mapM cExpr es) cExpr (HsAsPat n (HsList xs)) = do ty <- convertTyp (toName Name.Val n) let cl (x:xs) = liftM2 eCons (cExpr x) (cl xs) cl [] = return $ eNil ty cl xs cExpr (HsVar n) = do t <- convertVar (toName Name.Val n) return (EVar t) cExpr (HsAsPat n' e) = do e <- cExpr e cc <- asks ceCoerce case Map.lookup (toName Val n') cc of Nothing -> return e Just c -> applyCoersion c e cExpr e = invalidDecl ("Cannot convert: " ++ show e) hsLetE [] e = return e hsLetE dl e = do nds <- mconcatMapM cDecl dl return $ eLetRec [ (b,c) | (_,b,c) <- nds] e hsLet dl e = do e <- cExpr e hsLetE dl e cMatchs :: [E] -> [([HsPat],HsRhs,[HsDecl])] -> E -> C E cMatchs bs ms els = do pg <- processGuards ms convertMatches bs pg els cGuard (HsUnGuardedRhs e) = liftM const $ cExpr e cGuard (HsGuardedRhss (HsComp _ ~[HsQualifier g] e:gs)) = do g <- cExpr g e <- cExpr e fg <- cGuard (HsGuardedRhss gs) [nv] <- newVars [Unknown] return (\els -> createIfv nv g e (fg els)) cGuard (HsGuardedRhss []) = return id getAssump n = case Map.lookup (toName Name.Val n) assumps of Just z -> z Nothing -> error $ "Lookup failed: " ++ (show n) lp [] e = return e lp (HsPVar n:ps) e = do v <- convertVar (toName Name.Val n) eLam v `liftM` lp ps e lp p e = error $ "unsupported pattern:" <+> tshow p <+> tshow e cRhs sl (HsUnGuardedRhs e) = cExpr e cRhs sl (HsGuardedRhss []) = error "HsGuardedRhss: empty" cRhs sl (HsGuardedRhss gs@(HsComp _ _ e:_)) = f gs where f (HsComp _ ~[HsQualifier g] e:gs) = join $ liftM3 createIf (cExpr g) (cExpr e) (f gs) f [] = do e <- cExpr e return $ ump sl $ getType e processGuards xs = flip mapM xs $ \ (ps,e,wh) -> do cg <- cGuard e nds <- mconcatMapM cDecl wh let elet = eLetRec [ (b,c) | (_,b,c) <- nds] return (ps,elet . cg ) cClassDecl (HsClassDecl _ chead decls) = do props <- asks ceProps let cr = findClassRecord classHierarchy className className = hsClassHead chead cClass classRecord = [ f n (toId n) (removeNewtypes dataTable $ tipe t) | (n,t) <- classAssumps classRecord ] where f n i t = (n,setProperties [prop_METHOD,prop_PLACEHOLDER] $ tVr i t, foldr ELam (EPrim (primPrim ("Placeholder: " ++ show n)) [] ft) args) where (ft',as) = fromPi t (args,rargs) = case mlookup i props of Just p | getProperty prop_NOETA p -> span (sortKindLike . getType) as _ -> (as,[]) ft = foldr EPi ft' rargs return (cClass cr) cClassDecl _ = error "cClassDecl" convertVar n = do (t,_,_) <- convertValue n return t convertTyp n = do (_,t,_) <- convertValue n return t toTVr assumps dataTable n = tVr (toId n) typeOfName where typeOfName = case Map.lookup n assumps of Just z -> removeNewtypes dataTable (tipe z) Nothing -> error $ "convertVal.Lookup failed: " ++ (show n) integer_cutoff = 500000000 intConvert i | abs i > integer_cutoff = ELit (litCons { litName = dc_Integer, litArgs = [ELit $ LitInt (fromInteger i) r_bits_max_], litType = tInteger }) intConvert i = ELit (litCons { litName = dc_Int, litArgs = [ELit $ LitInt (fromInteger i) r_bits32], litType = tInt }) intConvert' funcs typ i = EAp (EAp fun typ) (ELit (litCons { litName = con, litArgs = [ELit $ LitInt (fromInteger i) rawtyp], litType = ltype })) where (con,ltype,fun,rawtyp) = case abs i > integer_cutoff of True -> (dc_Integer,tInteger,f_fromInteger,r_bits_max_) False -> (dc_Int,tInt,f_fromInt,r_bits32) f_fromInt = func_fromInt funcs f_fromInteger = func_fromInteger funcs litconvert (HsChar i) t | t == tChar = LitInt (fromIntegral $ ord i) tCharzh litconvert (HsCharPrim i) t | t == tCharzh = LitInt (fromIntegral $ ord i) tCharzh litconvert (HsIntPrim i) t = LitInt (fromIntegral i) t litconvert e t = error $ "litconvert: shouldn't happen: " ++ show (e,t) fromHsPLitInt (HsPLit l@(HsInt _)) = return l fromHsPLitInt (HsPLit l@(HsFrac _)) = return l fromHsPLitInt x = fail $ "fromHsPLitInt: " ++ show x tidyPat :: HsPat -> E -> C (HsPat,E -> E) tidyPat p b = f p where f HsPWildCard = return (HsPWildCard,id) f (HsPVar n) | isTypePlaceholder n = return (HsPWildCard,id) f (HsPAsPat n p) | isTypePlaceholder n = f p f (HsPTypeSig _ p _) = f p f p@HsPLit {} = return (p,id) f (HsPVar n) = do v <- convertVar (toName Name.Val n) return (HsPWildCard,if EVar v /= b then eLet v b else id) f (HsPAsPat n p) = do (p',g') <- f p v <- convertVar (toName Name.Val n) return (p',(if EVar v /= b then eLet v b else id) . g') f pa@(HsPApp n [p]) = do dataTable <- getDataTable patCons <- getConstructor (toName DataConstructor n) dataTable case conChildren patCons of DataAlias ErasedAlias -> f p _ -> return (pa,id) f p@HsPApp {} = return (p,id) f (HsPIrrPat (Located ss p)) = f p >>= \ (p',fe) -> case p' of HsPWildCard -> return (p',fe) _ -> do (lbv,bv) <- varify b let f n = do v <- convertVar (toName Name.Val n) fe <- convertMatches [bv] [([p],const (EVar v))] (EError (show ss ++ ": Irrefutable pattern match failed") (getType v)) return (v,fe) zs <- mapM f (getNamesFromHsPat p) return (HsPWildCard,lbv . eLetRec zs) f ~(HsPBangPat (Located ss (HsPAsPat v p))) = do (p',fe) <- f p v <- convertVar (toName Name.Val v) return (p',eStrictLet v b . fe) -- converts a value to an updatable closure if it isn't one already. varify b@EVar {} = return (id,b) varify b = do [bv] <- newVars [getType b] return (eLet bv b,EVar bv) tidyHeads :: E -> [([HsPat],E->E)] -- [(pats,else -> value)] -> C [(HsPat,[HsPat],E->E)] -- pulls the head off of each pattern, tidying it up perhaps tidyHeads b ps = mapM f ps where f (~(p:ps),fe) = do (p',fe') <- tidyPat p b return (p',ps,fe' . fe) convertMatches :: [E] -- input expressions we are matching against. -> [([HsPat],E->E)] -- [(pats,else -> value)] -> E -- else, what to do if nothing matches -> C E convertMatches bs ms err = do assumps <- asks ceAssumps dataTable <- getDataTable funcs <- asks ceFuncs let fromInt = func_fromInt funcs fromInteger = func_fromInteger funcs fromRational = func_fromRational funcs isJoinPoint (EAp (EVar x) _) | getProperty prop_JOINPOINT x = True isJoinPoint _ = False match :: [E] -> [([HsPat],E->E)] -> E -> C E -- when we run out of arguments, we should run out of patterns. simply fold the transformers. match [] ps err = return $ foldr f err ps where f (~[],fe) err = fe err -- when we are out of patterns, return the error term match _ [] err = return err match ~(b:bs) ps err = do (b',mf) <- if isEVar b then return (b,id) else do [ev] <- newVars [getType b] return $ (EVar ev, eLet ev b) pps <- tidyHeads b' ps let patternGroups = groupUnder (isHsPWildCard . fst3) pps f [] err = return err f (ps:pss) err = do err' <- f pss err if isEVar err' || isEError err' || isJoinPoint err' then matchGroup b' bs ps err' else do [ev] <- newVars [EPi tvr { tvrType = unboxedTyUnit } $ getType err'] let ev' = setProperties [prop_ONESHOT, prop_JOINPOINT] ev nm <- matchGroup b' bs ps (EAp (EVar ev') unboxedUnit) return $ eLetRec [(ev',ELam (setProperty prop_ONESHOT tvr { tvrType = unboxedTyUnit }) err')] nm liftM mf $ f patternGroups err matchGroup b bs ps err | all (isHsPWildCard . fst3) ps = match bs [ (ps,e) | (_,ps,e) <- ps] err | Just () <- mapM_ (fromHsPLitInt . fst3) ps = do let tb = getType b (lbv,bv) <- varify b let gps = [ (p,[ (ps,e) | (_,ps,e) <- xs ]) | (p,xs) <- sortGroupUnderF fst3 ps] eq = EAp (func_equals funcs) tb f els (HsPLit (HsInt i),ps) = do let ip | abs i > integer_cutoff = (EAp (EAp fromInteger tb) (intConvert i)) | otherwise = (EAp (EAp fromInt tb) (intConvert i)) m <- match bs ps err createIf (EAp (EAp eq bv) ip) m els f els ~(HsPLit (HsFrac i),ps) = do let ip = (EAp (EAp fromRational tb) (toE i)) m <- match bs ps err createIf (EAp (EAp eq bv) ip) m els e <- foldlM f err gps return $ lbv e | all (isHsPString . fst3) ps = do (lbv,bv) <- varify b (eqString,_,_) <- convertValue v_eqString (eqUnpackedString,_,_) <- convertValue v_eqUnpackedString let gps = [ (p,[ (ps,fe) | (_,ps,fe) <- xs ]) | (p,xs) <- sortGroupUnderF fst3 ps] f els (HsPLit (HsString ""),ps) = do m <- match bs ps err return $ eCase bv [Alt (litCons { litName = dc_EmptyList, litType = tString }) m] els f els ~(HsPLit (HsString s),ps) = do m <- match bs ps err let (s',packed) = packupString s if packed then return $ ifzh (EAp (EAp (EVar eqUnpackedString) s') bv) m els else return $ ifzh (EAp (EAp (EVar eqString) s') bv) m els e <- foldlM f err gps return $ lbv e | all (isHsPLit . fst3) ps = do let gps = [ (p,[ (ps,fe) | (_,ps,fe) <- xs ]) | (p,xs) <- sortGroupUnderF fst3 ps] f (~(HsPLit l),ps) = do m <- match bs ps err return (Alt (litconvert l (getType b)) m) as@(_:_) <- mapM f gps [TVr { tvrIdent = vr }] <- newVars [Unknown] return $ unbox dataTable b vr $ \tvr -> eCase tvr as err | Just ps <- mapM pappConvert ps = do let gps = sortGroupUnderF (hsPatName . fst3) ps (Just patCons) = getConstructor (toName DataConstructor $ fst $ head gps) dataTable f (name,ps) = do let spats = hsPatPats $ fst3 (head ps) _nargs = length spats vs <- newVars (slotTypesHs dataTable (toName DataConstructor name) (getType b)) ps' <- mapM pp ps m <- match (map EVar vs ++ bs) ps' err deconstructionExpression dataTable (toName DataConstructor name) (getType b) vs m pp (~(HsPApp n ps),rps,e) = do return $ (ps ++ rps , e) as@(_:_) <- mapM f gps case conVirtual patCons of Nothing -> return $ eCase b as err Just sibs -> do let (Just Constructor { conChildren = DataNormal [vCons] }) = getConstructor (conInhabits patCons) dataTable (Just Constructor { conOrigSlots = [SlotNormal rtype] }) = getConstructor vCons dataTable [z] <- newVars [rtype] let err' = if length sibs <= length as then Unknown else err return $ eCase b [Alt litCons { litName = vCons, litArgs = [z], litType = getType b } (eCase (EVar z) as err')] Unknown | otherwise = error $ "Heterogenious list: " ++ show (map fst3 ps) pappConvert (p@HsPApp {},x,y) = return (p,x,y) pappConvert (HsPLit (HsString ""),ps,b) = return (HsPApp (nameName $ dc_EmptyList) [],ps,b) pappConvert (HsPLit (HsString (c:cs)),ps,b) = return (HsPApp (nameName $ dc_Cons) [HsPLit (HsChar c),HsPLit (HsString cs)],ps,b) pappConvert _ = fail "pappConvert" isHsPString (HsPLit HsString {}) = True isHsPString _ = False match bs ms err packupString :: String -> (E,Bool) packupString s | all (\c -> c > '\NUL' && c <= '\xff') s = (EPrim (PrimString (packString s)) [] r_bits_ptr_,True) packupString s = (toE s,False) actuallySpecializeE :: Monad m => E -- ^ the general expression -> E -- ^ the specific type -> m E -- ^ the specialized value actuallySpecializeE ge st = do -- trace (pprint (ge, getType ge, st)) $ return () liftM (foldl EAp ge) (specializeE (getType ge) st) specializeE :: Monad m => E -- ^ the general type -> E -- ^ the specific type -> m [E] -- ^ what to apply the general type to to get the specific one specializeE gt st = do let f zs x | Just mm <- match (const Nothing) zs x st = mapM (g mm) (reverse zs) where g mm tvr = case lookup tvr mm of Just x -> return x Nothing -> fail $ "specializeE: variable not bound: " ++ pprint (((gt,st),(mm,tvr)),(zs,x)) f zs (EPi vbind exp) = f (vbind:zs) exp f _ _ = fail $ render (text "specializeE: attempt to specialize types that do not unify:" <$> pprint (gt,st) <$> tshow gt <$> tshow st) f [] gt procAllSpecs :: Monad m => DataTable -> [Type.Rule] -> [(TVr,E)] -> m ([(TVr,E)],Rules) procAllSpecs dataTable rs ds = do let specMap = Map.fromListWith (++) [ (toId n,[r]) | [email protected] { Type.ruleName = n } <- rs] f (t,e) | Just rs <- Map.lookup (tvrIdent t) specMap = do hs <- mapM (makeSpec dataTable (t,e)) rs return (unzip hs) f _ = return mempty (nds,rules) <- mconcat `liftM` mapM f ds return $ (nds,fromRules rules) makeSpec :: Monad m => DataTable -> (TVr,E) -> T.Rule -> m ((TVr,E),Rule) makeSpec dataTable (t,e) T.RuleSpec { T.ruleType = rt, T.ruleUniq = (m,ui), T.ruleSuper = ss } = do let nt = removeNewtypes dataTable $ tipe rt as <- specializeE (getType t) nt let ntvr = tvr { tvrIdent = toId newName, tvrType = getType nbody, tvrInfo = setProperties (prop_SPECIALIZATION:sspec) mempty } Just nn = fromId (tvrIdent t) (ntype,Just (show -> m),q) = nameParts nn newName = toName ntype (Just $ toModule ("Spec@." ++ m ++ "." ++ show ui),'f':m ++ "." ++ q) sspec = if ss then [prop_SUPERSPECIALIZE] else [] ar = makeRule ("Specialize.{" ++ show newName) (toModule m,ui) RuleSpecialization bvars t as (foldl eAp (EVar ntvr) (map EVar bvars)) bvars = nub $ freeVars as nbody = foldr ELam (foldl EAp e as) bvars return ((ntvr,nbody),ar) makeSpec _ _ _ = fail "E.FromHs.makeSpec: invalid specialization" deNewtype :: DataTable -> E -> E deNewtype dataTable e = removeNewtypes dataTable (f e) where f ECase { eCaseScrutinee = e, eCaseAlts = ((Alt (LitCons { litName = n, litArgs = [v], litType = t }) z):_) } | alias == DataAlias ErasedAlias = f (eLet v e z) where Identity Constructor { conChildren = alias } = getConstructor n dataTable f ECase { eCaseScrutinee = e, eCaseAlts = ((Alt (LitCons { litName = n, litArgs = [v], litType = t }) z):_) } | alias == DataAlias RecursiveAlias = f $ eLet v (prim_unsafeCoerce e (getType v)) z where Identity Constructor { conChildren = alias } = getConstructor n dataTable f e = runIdentity $ emapE (return . f) e ffiTypeInfo bad t cont = do dataTable <- getDataTable case lookupExtTypeInfo dataTable t of Just r -> cont r Nothing -> do sl <- getSrcLoc liftIO $ warn sl InvalidFFIType $ printf "Type '%s' cannot be used in a foreign declaration" (pprint t :: String) return bad unboxedVersion t = do ffiTypeInfo Unknown t $ \eti -> case eti of ExtTypeBoxed _ uv _ -> return uv ExtTypeRaw _ -> return t ExtTypeVoid -> return (eTuple' []) marshallToC e te = do ffiTypeInfo Unknown te $ \eti -> do case eti of ExtTypeBoxed cna sta _ -> do [tvra] <- newVars [sta] return $ eCase e [Alt (litCons { litName = cna, litArgs = [tvra], litType = te }) (EVar tvra)] Unknown ExtTypeRaw _ -> return e ExtTypeVoid -> fail "marshallToC: trying to marshall void" marshallFromC ce te = do ffiTypeInfo Unknown te $ \eti -> do case eti of ExtTypeBoxed cna _ _ -> return $ ELit (litCons { litName = cna, litArgs = [ce], litType = te }) ExtTypeRaw _ -> return ce ExtTypeVoid -> fail "marshallFromC: trying to marshall void" extractUnboxedTup :: E -> ([E] -> C E) -> C E extractUnboxedTup e f = do vs <- newVars $ concat (fromTuple_ (getType e)) a <- f (map EVar vs) return $ eCaseTup' e vs a
m-alvarez/jhc
src/E/FromHs.hs
mit
47,722
5
33
15,159
19,025
9,574
9,451
-1
-1
main = do putStrLn "Year of birth?" yob <- readLn let age = 2014 - yob putStrLn $ "You're " ++ (show age) ++ " years old"
raimohanska/Monads
examples/exercises/4_CalcAge.hs
mit
133
0
10
37
53
24
29
5
1
import Control.Monad (replicateM) import Criterion.Main import qualified Data.Clustering.Hierarchical as C import qualified Data.Vector as V import System.Random.MWC import AI.Clustering.Hierarchical import AI.Clustering.Hierarchical.Types ((!)) import Bench.Hierarchical (benchHierarchical) import Bench.KMeans (benchKMeans) main :: IO () main = defaultMain [ benchHierarchical , benchKMeans ]
kaizhang/clustering
benchmarks/bench.hs
mit
410
0
6
55
103
65
38
13
1
module Grafs.Cli where import Protolude hiding ((<>)) import Options.Applicative data CLIOptions = CLIOptions { port :: Int } cliOptions :: Parser CLIOptions cliOptions = CLIOptions <$> option auto ( long "port" <> short 'p' <> metavar "PORT" <> help "The port Grafs runs on" ) getOpts :: IO CLIOptions getOpts = execParser opts where opts = info (helper <*> cliOptions) $ fullDesc <> header "Generic Registering and Form Service" <> progDesc "Run Grafs on given PORT"
uwap/Grafs
src/Grafs/Cli.hs
mit
592
0
12
199
137
72
65
18
1
------------------------------------------------------------------------------- -- Module : Domain.Sign.Type -- Copyright : (c) 2015 Marcelo Sousa ------------------------------------------------------------------------------- module Domain.Sign.Type where import qualified Data.ByteString as BS import Data.Hashable import qualified Data.HashTable.ST.Cuckoo as C import qualified Data.HashTable.Class as H import Data.List import qualified Data.Map as M import Data.Map (Map) import Util.Generic hiding (safeLookup) import Domain.Domain data Sign = Bot | Negative | Zero | Positive | Top deriving (Show, Eq, Ord) instance Domain Sign where join Bot a = a join a Bot = a join a b = if a == b then a else Top meet Top a = a meet a Top = a meet a b = if a == b then a else Bot --instance Hashable Sign where -- hash = hash . M.toList -- hashWithSalt s st = hashWithSalt s $ M.toList st
marcelosousa/poet
src/Domain/Sign/Type.hs
gpl-2.0
912
0
7
161
211
129
82
19
0
module Language.Dockerfile.FormatCheck (formatCheck) where import Language.Dockerfile.Rules import Language.Dockerfile.Syntax formatCheck :: Check -> String formatCheck (Check md source ln _) = formatPos source ln ++ code md ++ " " ++ message md formatPos :: Filename -> Linenumber -> String formatPos source ln = if ln >= 0 then source ++ ":" ++ show ln ++ " " else source ++ " "
beijaflor-io/haskell-language-dockerfile
src/Language/Dockerfile/FormatCheck.hs
gpl-3.0
420
0
8
101
130
69
61
11
2
module Controller.App where import Control.Monad import Control.Monad.Trans (lift) import Control.Monad.Trans.Maybe import Controller.Bootstrap import Controller.CLI import Controller.Fractal import Controller.GUI import Data.Maybe (maybe) import Graphics.UI.SDL as SDL import Model.Fractal import Model.Progression import View.Fractal as F import View.GUI as G data AppController = AppController { appScreen :: Surface , appProgression :: FractalProgression , appWidth :: Double , appHeight :: Double , appX :: Double , appY :: Double , appZoom :: Double , appZoomFactor :: Double , appMaxIter :: Integer , appModel :: FractalModel , appFView :: FractalView , appGUIVisible :: Bool , appGView :: GUIView } run :: AppController -> IO () run app = do showCursor False enableKeyRepeat 200 10 -- TODO: make the first render loop app SDL.quit loop :: AppController -> IO () loop app = do (continue,newApp) <- handleEvents app when continue $ do -- TODO: here F.expose (appModel newApp) (appFView newApp) (mx,my,_) <- getMouseState when (appGUIVisible app) $ exposeGUI mx my app SDL.flip $ appScreen newApp loop newApp handleEvents :: AppController -> IO (Bool,AppController) handleEvents app = do event <- pollEvent case event of NoEvent -> nochange Quit -> quit KeyUp k -> case symKey k of SDLK_ESCAPE -> quit SDLK_SPACE -> loopback $ app { appGUIVisible = toggle (appGUIVisible app) } SDLK_RETURN -> alter $ updateModel >=> updateModelView SDLK_MINUS -> loopback $ changeMaxIter (\a -> a-50) app -- TODO: woah, pretty weird the - operator... SDLK_PLUS -> loopback $ changeMaxIter (+50) app _ -> loopback app KeyDown k -> case symKey k of SDLK_LEFTPAREN -> alter $ return . changeZoomWindowSize (/1.05) >=> updateGUIZoomWindow SDLK_RIGHTPAREN -> alter $ return . changeZoomWindowSize (*1.05) >=> updateGUIZoomWindow _ -> loopback app MouseButtonUp x y b -> case b of ButtonLeft -> alter $ (onMouseButtonLeft (fromIntegral x) (fromIntegral y) >=> updateModel >=> updateModelView) _ -> loopback app _ -> loopback app where quit = return (False,app) nochange = return (True,app) loopback = handleEvents alter f = f app >>= loopback onMouseButtonLeft :: Double -> Double -> AppController -> IO AppController onMouseButtonLeft x y app = let w = appWidth app h = appHeight app cz = appZoom app czf = appZoomFactor app (rx :+ ry) = toCart w h (x :+ y)   (nx,ny) = (appX app + rx/cz,appY app + ry/cz) newZ = cz * czf in return app { appX = nx, appY = ny, appZoom = newZ } updateModel :: AppController -> IO AppController updateModel app = do let p = appProgression app m = appModel app w = appWidth app h = appHeight app x = appX app y = appY app z = appZoom app i = appMaxIter app putStr $ "updating fractal [x:" ++ show x ++ " y:" ++ show y ++ " z:" ++ show z ++ " i:" ++ show i ++ "] ..." newModel <- regen p m w h x y z i putStrLn "done!" return app { appModel = newModel } updateModelView :: AppController -> IO AppController updateModelView app = do pixelizeSurface (appModel app) $ stdViewFractalSurface $ appFView app return app exposeGUI :: Int -> Int -> AppController -> IO () exposeGUI x y app = do let rw = floor $ appWidth app / zf rh = floor $ appHeight app / zf rx = x - rw `div` 2 ry = y - rh `div` 2 zf = appZoomFactor app gv = appGView app case gv of G.StandardView _ za -> do _ <- blitSurface za Nothing (appScreen app) (Just $ Rect rx ry rw rh) return () changeZoomWindowSize :: (Double -> Double) -> AppController -> AppController changeZoomWindowSize f app = let zf = appZoomFactor app in app { appZoomFactor = f zf } updateGUIZoomWindow :: AppController -> IO AppController updateGUIZoomWindow app = do let w = appWidth app h = appHeight app zf = appZoomFactor app newZoomWindow <- runMaybeT $ tryCreateZoomWindow (floor w) (floor h) zf case newZoomWindow of Nothing -> return app Just zoomWindow -> do let gv = appGView app case gv of G.StandardView _ zw -> do let ngv = gv { stdViewZoomArea = zoomWindow } return app { appGView = ngv } changeMaxIter :: (Integer -> Integer) -> AppController -> AppController changeMaxIter f app = let mi = appMaxIter app in app { appMaxIter = f mi }
phaazon/phraskell
src/Controller/App.hs
gpl-3.0
4,661
0
21
1,270
1,582
802
780
-1
-1
module Data.BTree ( BTree(..) , unfoldTree , unfoldTreeM ) where import Control.Applicative import Data.Maybe (fromMaybe) data BTree a = BNode a (BTree a) (BTree a) | Leaf deriving (Eq, Show, Read) instance Functor BTree where fmap f Leaf = Leaf fmap f (BNode a lb rb) = BNode (f a) (fmap f lb) (fmap f rb) unfoldTree :: (b -> (a, (Maybe b, Maybe b))) -> b -> BTree a unfoldTree f b = let (a, (mleft, mright)) = f b in BNode a (fromMaybe Leaf $ unfoldTree f <$> mleft) (fromMaybe Leaf $ unfoldTree f <$> mright) unfoldTreeM :: (Applicative m, Monad m) => (b -> m (a, (Maybe b, Maybe b))) -> b -> m (BTree a) unfoldTreeM f b = do (a, (mleft, mright)) <- f b BNode a <$> fromMaybe (return Leaf) (unfoldTreeM f <$> mleft) <*> fromMaybe (return Leaf) (unfoldTreeM f <$> mright)
xaphiriron/maps
Data/BTree.hs
gpl-3.0
799
12
12
173
431
223
208
24
1
{- as3tohaxe - An Actionscript 3 to haXe source file translator Copyright (C) 2008 Don-Duong Quach 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 (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, see <http://www.gnu.org/licenses/>. -} module ActionhaXe.CLArgs (CLArg(..), Conf(..), clargs) where import System.Console.ParseArgs import Data.Generics import Data.Map data CLArg = NumberToInt | NoCarriage | CreateImports | Input | OutputDir deriving (Eq, Ord, Show, Data, Typeable) data Conf = Conf{ confArgs::Args CLArg, confInput::String, confOutput::String, imports::Map String [String] } | ConfNone deriving (Show, Data, Typeable) initArg f desc = Arg{ argIndex = f, argAbbr = Nothing, argName = Nothing, argData = Nothing, argDesc = desc } clargs = [ (initArg NumberToInt "translate :Number to :Int (default :Float)"){ argAbbr = Just 'i', argName = Just "intnum" } , (initArg NoCarriage "remove carriage returns '\\r' in output"){ argAbbr = Just 'r', argName = Just "nocarriage" } , (initArg CreateImports "creates \"Import\" files in place of * imports (e.g. import a.*;)"){ argAbbr= Just 'c', argName = Just "imports" } , (initArg Input "input to convert") { argData = argDataRequired "directory | file" ArgtypeString } ]
geekrelief/as3tohaxe
ActionhaXe/CLArgs.hs
gpl-3.0
1,838
0
10
397
310
181
129
20
1
{-# LANGUAGE BangPatterns, FlexibleContexts #-} module Main where import Control.DeepSeq (force) import Control.Monad import Control.Parallel.Strategies (parList, parListChunk, rdeepseq, using) import qualified Data.ByteString.Lazy as BL import Data.List (foldl', minimumBy) import Data.List.Split (chunksOf) import Data.Maybe (fromJust, isJust, maybe) import qualified Data.Vector as V import qualified Data.Vector.Generic.Mutable as M import Linear.Metric (dot, normalize) import Linear.V3 import qualified Graphics.OpenEXR as EXR import System.Environment (getArgs) import qualified Camera as C import qualified DiffGeometry as DG import qualified Geometry as G import qualified GeometryData as GD import qualified Instance as I import N3 import qualified Ray as R import Render import qualified Scene as S import qualified SceneParser as SP import qualified Transform as T import qualified BVH samples :: Render -> [(Double, Double, Double, Double)] samples r@(Render (w, h)) = [(mkSample r (fromIntegral x) (fromIntegral y)) | y <- [0..h - 1], x <- [0..w - 1]] mkSample :: Render -> Double -> Double -> (Double, Double, Double, Double) mkSample ren x y = (px, py, dx, dy) where (w, h) = resolution ren px = (2*(x + 0.5)/fromIntegral w - 1)*aspectRatio py = 1 - 2*(y + 0.5)/fromIntegral h dx = (2*(x + 1.5)/fromIntegral w - 1)*aspectRatio dy = 1 - 2*(y + 1.5)/fromIntegral h aspectRatio = fromIntegral w/fromIntegral h rays s f = map (C.mkRayDiff (S.camera s)) . samples $ f trace :: S.Scene -> V.Vector R.Ray -> V.Vector EXR.PixelRGBF trace s = (<$>) (maybe (EXR.PixelRGBF 0 0 0) (shade . snd)) . S.intersect s shade :: DG.DiffGeometry -> EXR.PixelRGBF shade dg = {-EXR.PixelRGBF matte matte matte-} EXR.PixelRGBF (realToFrac (DG.u dg)) (realToFrac (DG.v dg)) 0 where matte = realToFrac $ (0.90*(max 0 $ dot (normalize n) (normalize (V3 0.5 0.5 1))) + 0.1) p = DG.point dg (N3 n) = DG.normal dg (V3 x y z) = n -- serial rendering renderScene1 :: S.Scene -> Render -> EXR.Image renderScene1 s render@(Render (resX, resY)) = EXR.ImageRGBF resX resY rs where rs = V.concat . (<$>) (force . trace s . V.fromList) . chunksOf (64*64) . rays s $ render -- parallel scanline order chunked rendering {- renderScene2 :: S.Scene -> Render -> Image renderScene2 s r@(Render (resX, resY)) = ImageRGBF resX resY (V.fromList (rs `using` parListChunk 1000 rdeepseq)) where rs = trace s . V.fromList . rays s $ r -} data Tile = Tile { offsetX, offsetY, width, height :: Int } deriving Show -- parallel tiled rendering, scanline order -- currently image must be power of two {- renderScene3 :: S.Scene -> Render -> Image renderScene3 s r@(Render (resX, resY)) = ImageRGBF resX resY (V.update initImg (V.concat tiles)) where initImg = V.replicate (resX*resY) (EXR.PixelRGBF 0 0 0) tiles = [renderTile (Tile (x*tileW) (y*tileH) tileW tileH) | y <- [0..nTilesH], x <- [0..nTilesW]] `using` parList rdeepseq tileW = 16 tileH = 16 nTilesW = (resX - 1) `quot` tileW nTilesH = (resY - 1) `quot` tileH renderTile t = V.fromList px where px = [(index x y, trace s (ray (offsetX t + x) (offsetY t + y))) | y <- [0..height t - 1], x <- [0..width t - 1]] index x y = offsetX t + x + (offsetY t + y) * resX ray x y = C.mkRayDiff (S.camera s) $ mkSample r (fromIntegral x) (fromIntegral y) -} main = do [sceneFile] <- getArgs (scene, render) <- fmap (fromJust . SP.parse) (BL.readFile sceneFile) EXR.writeFile "image.exr" (renderScene1 scene render) EXR.ZipCompression
pavolzetor/currypath
src/Main.hs
gpl-3.0
3,794
0
17
911
1,008
571
437
55
1
<?xml version='1.0' encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN" "http://java.sun.com/products/javahelp/helpset_1_0.dtd"> <helpset version="1.0"> <title>Wlz Section Viewer - Help</title> <maps> <homeID>sv.description</homeID> <mapref location="Map.jhm"/> </maps> <view> <name>TOC</name> <label>Table Of Contents</label> <type>javax.help.TOCView</type> <data>ViewerHelpTOC.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>ViewerHelpIndex.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> </helpset>
ma-tech/JavaWoolz
uk/ac/mrc/hgu/SectionViewer/classes/sectionViewer/help/ViewerHelp.hs
gpl-3.0
915
72
30
196
344
183
161
-1
-1
-- Author: Paul Reiners -- https://github.com/paul-reiners/a-golden-prime-project module PrintPairCounts where import AGPP import Text.Printf import Control.Exception import System.CPUTime import System.Environment nums :: Integer -> [Integer] nums n = [m | m <- [4..n], even m] primePairCounts :: Integer -> [Int] primePairCounts n = map primePairCount (nums n) primeDivisorCounts :: Integer -> [Int] primeDivisorCounts n = map primeDivisorCount (nums n) numsAndPrimePairCounts :: Integer -> [(Integer, Int, Int)] numsAndPrimePairCounts n = zip3 (nums n) (primePairCounts n) (primeDivisorCounts n) showTup :: (Show a, Show b, Show c) => (a,b,c) -> String showTup (a,b,c) = (show a) ++ "," ++ (show b) ++ "," ++ (show c) main = do args <- getArgs mapM_ (putStrLn . showTup) (numsAndPrimePairCounts (read $ head args :: Integer))
paul-reiners/a-golden-prime-project
src/PrintPairCounts.hs
gpl-3.0
846
0
12
136
324
175
149
19
1
grafo n xs = grafo' n xs [0..(n-1)] grafo' _ [] _ =[] grafo' n ((com,a,b):xs) ds= if(com=="une")then True: (grafo' n xs (une a b ds)) else (conectados a b ds):grafo' n xs ds une a b ds=une' (fs a ds) (fs b ds) ds 0 une' a b (x:xs) c= if(c==a) then (b:xs) else x:une' a b (xs) (c+1) conectados a b ds = if((fs a ds)==(fs b ds)) then True else False fs i ds=if((arreglo ds i 0)==i) then i else fs (arreglo ds i 0) ds arreglo (x:xs) i n=if(i==n) then x else arreglo (xs) i (n+1)
SDKE/Programacion-Logica-y-Funcional
Practica5.hs
gpl-3.0
491
6
10
115
401
201
200
13
2
module Test.QuickFuzz.Gen.Bnfc ( module Test.QuickFuzz.Gen.Bnfc.Grammar, ) where import Test.QuickFuzz.Gen.Bnfc.Grammar
CIFASIS/QuickFuzz
src/Test/QuickFuzz/Gen/Bnfc.hs
gpl-3.0
122
0
5
11
28
21
7
3
0
{-# 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.Genomics.CallSets.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new call set. For the definitions of call sets and other -- genomics resources, see [Fundamentals of Google -- Genomics](https:\/\/cloud.google.com\/genomics\/fundamentals-of-google-genomics) -- -- /See:/ <https://cloud.google.com/genomics Genomics API Reference> for @genomics.callsets.create@. module Network.Google.Resource.Genomics.CallSets.Create ( -- * REST Resource CallSetsCreateResource -- * Creating a Request , callSetsCreate , CallSetsCreate -- * Request Lenses , cscXgafv , cscUploadProtocol , cscPp , cscAccessToken , cscUploadType , cscPayload , cscBearerToken , cscCallback ) where import Network.Google.Genomics.Types import Network.Google.Prelude -- | A resource alias for @genomics.callsets.create@ method which the -- 'CallSetsCreate' request conforms to. type CallSetsCreateResource = "v1" :> "callsets" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] CallSet :> Post '[JSON] CallSet -- | Creates a new call set. For the definitions of call sets and other -- genomics resources, see [Fundamentals of Google -- Genomics](https:\/\/cloud.google.com\/genomics\/fundamentals-of-google-genomics) -- -- /See:/ 'callSetsCreate' smart constructor. data CallSetsCreate = CallSetsCreate' { _cscXgafv :: !(Maybe Xgafv) , _cscUploadProtocol :: !(Maybe Text) , _cscPp :: !Bool , _cscAccessToken :: !(Maybe Text) , _cscUploadType :: !(Maybe Text) , _cscPayload :: !CallSet , _cscBearerToken :: !(Maybe Text) , _cscCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CallSetsCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cscXgafv' -- -- * 'cscUploadProtocol' -- -- * 'cscPp' -- -- * 'cscAccessToken' -- -- * 'cscUploadType' -- -- * 'cscPayload' -- -- * 'cscBearerToken' -- -- * 'cscCallback' callSetsCreate :: CallSet -- ^ 'cscPayload' -> CallSetsCreate callSetsCreate pCscPayload_ = CallSetsCreate' { _cscXgafv = Nothing , _cscUploadProtocol = Nothing , _cscPp = True , _cscAccessToken = Nothing , _cscUploadType = Nothing , _cscPayload = pCscPayload_ , _cscBearerToken = Nothing , _cscCallback = Nothing } -- | V1 error format. cscXgafv :: Lens' CallSetsCreate (Maybe Xgafv) cscXgafv = lens _cscXgafv (\ s a -> s{_cscXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). cscUploadProtocol :: Lens' CallSetsCreate (Maybe Text) cscUploadProtocol = lens _cscUploadProtocol (\ s a -> s{_cscUploadProtocol = a}) -- | Pretty-print response. cscPp :: Lens' CallSetsCreate Bool cscPp = lens _cscPp (\ s a -> s{_cscPp = a}) -- | OAuth access token. cscAccessToken :: Lens' CallSetsCreate (Maybe Text) cscAccessToken = lens _cscAccessToken (\ s a -> s{_cscAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). cscUploadType :: Lens' CallSetsCreate (Maybe Text) cscUploadType = lens _cscUploadType (\ s a -> s{_cscUploadType = a}) -- | Multipart request metadata. cscPayload :: Lens' CallSetsCreate CallSet cscPayload = lens _cscPayload (\ s a -> s{_cscPayload = a}) -- | OAuth bearer token. cscBearerToken :: Lens' CallSetsCreate (Maybe Text) cscBearerToken = lens _cscBearerToken (\ s a -> s{_cscBearerToken = a}) -- | JSONP cscCallback :: Lens' CallSetsCreate (Maybe Text) cscCallback = lens _cscCallback (\ s a -> s{_cscCallback = a}) instance GoogleRequest CallSetsCreate where type Rs CallSetsCreate = CallSet type Scopes CallSetsCreate = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/genomics"] requestClient CallSetsCreate'{..} = go _cscXgafv _cscUploadProtocol (Just _cscPp) _cscAccessToken _cscUploadType _cscBearerToken _cscCallback (Just AltJSON) _cscPayload genomicsService where go = buildClient (Proxy :: Proxy CallSetsCreateResource) mempty
rueshyna/gogol
gogol-genomics/gen/Network/Google/Resource/Genomics/CallSets/Create.hs
mpl-2.0
5,429
0
18
1,319
864
503
361
121
1
module Handler.PasteView where import Import getPasteViewR :: PasteId -> Handler Html getPasteViewR pasteId = do paste <- runDB (get pasteId) >>= \case Just x -> return x Nothing -> notFound defaultLayout $ $(widgetFile "paste-view")
learnyou/lypaste
Handler/PasteView.hs
agpl-3.0
283
0
12
83
83
40
43
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -funbox-strict-fields #-} module Types where import Control.Lens import Control.Lens.TH import Control.Monad import Control.Monad.List import Control.Monad.State.Lazy import Control.Monad.Trans.Class import Control.Monad.Trans.Maybe import qualified Data.Aeson as A import qualified Data.ByteString.Lazy.Char8 as LBS8 import Data.Char (toLower) import Data.Foldable import qualified Data.List as List import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.Maybe import Data.Monoid import qualified Data.Set as Set import Debug.Trace import System.Random.Shuffle (shuffleM) import Text.Show.Pretty (ppShow) import THUtils -- Game State ------------------------------------------------------------------------------------------------ data Color = Red | Green | Blue | Yellow deriving (Eq, Ord, Enum, Bounded) data Size = Small | Medium | Large deriving (Eq, Ord, Enum, Bounded) data Piece = Piece { _color ∷ !Color, _size ∷ !Size } deriving (Eq, Ord, Bounded) data Ship = Ship { _owner ∷ !PlayerId, _piece ∷ !Piece } deriving (Eq, Ord) data Star = Binary !Piece !Piece | Single !Piece deriving (Eq, Ord, Show) data System = System { _star ∷ !Star, _ships ∷ ![Ship] } deriving (Eq, Ord, Show) type PlayerId = Int type SystemId = Int data GameSt = GameSt { _reserve ∷ !(IntMap Int) , _systems ∷ !(IntMap System) , _turn ∷ !PlayerId , _numSystems ∷ !Int , _numPlayers ∷ !Int , _history ∷ ![Event] } deriving (Eq, Ord, Show) -- Events ---------------------------------------------------------------------------------------------------- data Setup = Setup !Piece !Piece !Color deriving (Eq, Ord, Show) data Destination = Existing !SystemId | Fresh !Piece deriving (Eq, Ord, Show) data Action = Construct !SystemId !Color | Trade !SystemId !Piece !Color | Move !SystemId !Piece !Destination | Attack !SystemId !Ship | Sacrifice !SystemId !Piece | Catastrophe !SystemId !Color deriving (Eq, Ord, Show) data Event = Join !Setup | Resign | Turn ![Action] deriving (Eq, Ord, Show) -- The Game and Move Monads ---------------------------------------------------------------------------------- type GameT = StateT GameSt type MoveM = GameT Maybe type GameM = GameT [] -- Instances ------------------------------------------------------------------------------------------------- intMapList ∷ IntMap a → [Maybe a] intMapList m | IntMap.null m = [] intMapList m = IntMap.findMax m & \case (k,_) → flip IntMap.lookup m <$> [0..k] numberOfSizes ∷ Int numberOfSizes = 1 + fromEnum (maxBound ∷ Size) instance Enum Piece where enumFrom pc = enumFromTo pc maxBound enumFromThen pc pc2 = enumFromThenTo pc pc2 maxBound fromEnum (Piece pc sz) = fromEnum sz + (fromEnum pc * numberOfSizes) toEnum i = Piece pc sz where sz = toEnum $ i `mod` numberOfSizes pc = toEnum $ i `div` numberOfSizes instance Show Color where show = \case { Red → "r"; Green → "g"; Blue → "b"; Yellow → "y" } instance Show Size where show = \case { Small → "1"; Medium → "2"; Large → "3" } instance Show Piece where show (Piece color size) = show color <> show size instance Show Ship where show (Ship player piece) = "\"" <> show piece <> "@" <> show player <> "\"" instance A.ToJSON Color where toJSON = A.toJSON . show instance A.FromJSON Color where parseJSON = undefined instance A.ToJSON Piece where toJSON = A.toJSON . show instance A.FromJSON Piece where parseJSON = undefined makeLenses ''Piece makeLenses ''Ship makeLenses ''Star makeLenses ''System makeLenses ''GameSt makeLenses ''Setup makeLenses ''Action makeLenses ''Event $(deriveJSON ''Size) $(deriveJSON ''Star) $(deriveJSON ''Ship) $(deriveJSON ''System) $(deriveJSON ''GameSt) $(deriveJSON ''Setup) $(deriveJSON ''Destination) $(deriveJSON ''Action) $(deriveJSON ''Event)
benjamin-wagon/homeworld
Types.hs
agpl-3.0
4,425
0
11
1,132
1,306
691
615
-1
-1
letter2int :: Char -> Int letter2int a = case a of 'I' -> 1 'V' -> 5 'X' -> 10 'D' -> 500 'L' -> 50 'C' -> 100 'M' -> 1000 roman2Int :: (Int,String) -> Int roman2Int (i,"") = i roman2Int (0, (x:xs)) = case xs of [] -> roman2Int ((letter2int x), "") xs -> roman2Int ((letter2int x), (x:xs)) roman2Int (i, (x:"")) = i roman2Int (i, (x:y:xs)) = case (y,x) of ('V', 'I') -> roman2Int (i+(letter2int y)-2,(y:xs)) ('X', 'I') -> roman2Int (i+(letter2int y)-2,(y:xs)) ('M', 'C') -> roman2Int (i+(letter2int y)-200,(y:xs)) ('D', 'C') -> roman2Int (i+(letter2int y)-200,(y:xs)) ('C', 'X') -> roman2Int (i+(letter2int y)-20,(y:xs)) ('L', 'X') -> roman2Int (i+(letter2int y)-20,(y:xs)) (_,_) -> roman2Int (i+(letter2int y), (y:xs))
ccqpein/Arithmetic-Exercises
Roman-To-Integer/RTI.hs
apache-2.0
763
0
13
157
515
281
234
23
8
{-# LANGUAGE BangPatterns, OverloadedStrings, TemplateHaskell #-} module Collectors.Cpu where import Control.Applicative ((<$>), (<*)) import Control.Lens.TH (makeClassy) import Data.Text (Text(), append, empty, pack, singleton) import Text.Parsec import Text.Parsec.Text data CoreMetric = CoreMetric { _coreName :: !Text , _user :: !Int , _nice :: !Int , _system :: !Int , _idle :: !Int , _iowait :: !Int , _irq :: !Int , _softirq :: !Int } deriving Show $(makeClassy ''CoreMetric) data StatMetrics = StatMetrics { _total :: !CoreMetric , _cores :: ![CoreMetric] } deriving Show $(makeClassy ''StatMetrics) parseStat :: Parser StatMetrics parseStat = do (m:ms) <- endBy cpuLine newline return $ StatMetrics m ms cpuLine :: Parser CoreMetric cpuLine = do name <- identifier <* space (u:n:sy:idl:io:ir:so:_) <- metrics return $ CoreMetric name u n sy idl io ir so metrics :: Parser [Int] metrics = sepBy number (char ' ') <?> "metrics" number :: Parser Int number = read <$> many1 digit <?> "number" identifier :: Parser Text identifier = do n <- pack <$> string "cpu" <?> "identifier" i <- digit <|> space <?> "identifier" return $ n `append` if i == ' ' then empty else singleton i
muhbaasu/hmon
src/Collectors/Cpu.hs
apache-2.0
1,543
0
15
549
451
241
210
61
2
-- | Types and algorithms for Markov logic networks. The module has quite a -- few 'fromStrings' methods that take strings and parse them into data -- structure to make it easier to play with Markov logic in the repl. -- -- For Markov logic, data is often represented with a Set (Predicate a, Bool). -- This is prefered to Map since it simplifies queries such as -- "P(Cancer(Bob) | !Cancer(Bob))", where a map would not allow these two -- different predicate -> value mappings. module Akarui.FOL.MarkovLogic ( MLN(..) , tell , allPredicates , allGroundings , allWGroundings , fromStrings , groundNetwork , factors , ask , marginal , joint , conditional , constructNetwork ) where import qualified Data.Text as T import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Set as Set import Data.Set (Set) import Data.List (partition) import Control.Applicative ((<|>)) import qualified Akarui.FOL.FOL as FOL import Akarui.FOL.FOL (FOL) import qualified Akarui.FOL.Formula as F import Akarui.FOL.Predicate import Akarui.FOL.Term import Akarui.FOL.Symbols import Akarui.Network import Akarui.ShowTxt import qualified Akarui.FOL.FormulaSet as FS import Akarui.Parser.Probability import Akarui.Parser.FOL -- | A Markov logic network is a set of first-order logical formulas associated -- with a weight. data MLN = MLN { network :: Map FOL Double } instance Show MLN where show = T.unpack . fmtMLN instance ShowTxt MLN where showTxt = fmtMLN -- | Prints a Markov logic network. fmtMLN :: MLN -> T.Text fmtMLN (MLN m) = Map.foldrWithKey (\k v acc -> T.concat [fmtWFormula symbolic k v, "\n", acc]) "" m -- | Prints a weighted formula. fmtWFormula :: Symbols -> FOL -> Double -> T.Text fmtWFormula s f w = T.concat [F.prettyPrintFm s f, ", ", T.pack $ show w, "."] -- | Adds a formula to the markov logic network using the parser. If the parser -- fails, the function returns the MLN unmodified. tell :: String -> MLN -> MLN tell s mln@(MLN m) = case parseWFOL s of Left _ -> mln Right (f, w) -> MLN $ Map.insert f w m -- | Gathers all the predicates of a markov logic network in a set. allPredicates :: MLN -> Set Predicate allPredicates (MLN m) = Map.foldrWithKey (\k _ acc -> Set.union (F.atoms k) acc) Set.empty m -- | Get all groundings from a Markov logic network. allGroundings :: [Term] -> MLN -> Set FOL allGroundings ts (MLN m) = FS.allGroundings ts $ Map.keysSet m -- | Get all groundings from a Markov logic network, keeping the weights -- assigned to the original formula in the Markov logic network. allWGroundings :: [Term] -> MLN -> MLN allWGroundings ts (MLN m) = MLN $ Map.foldrWithKey (\k v a -> Set.foldr' (\k' a' -> Map.insert k' v a') a (FOL.groundings ts k)) Map.empty m -- | Builds a ground network for Markov logic. groundNetwork :: [Term] -> MLN -> UNetwork Predicate groundNetwork ts (MLN m) = Set.foldr' (\p acc -> Map.insert p (mb p) acc) Map.empty ps where -- All groundings from all formulas in the knowledge base: gs = Set.foldr' (\g acc -> Set.union (FOL.groundings ts g) acc) Set.empty (Map.keysSet m) -- All the predicates ps = FS.allPredicates gs -- The Markov blanket of predicate 'p', that is: all its neighbours. mb p = Set.delete p $ FS.allPredicates $ Set.filter (FOL.hasPred p) gs -- | Returns all the factors in the MLN. Instead of mappings sets of predicates -- to weights, this function maps them to the formula (the MLN provides the -- weight). factors :: [Term] -> MLN -> Map (Set Predicate) FOL factors ts (MLN m) = fs where -- All groundings mapped to their original formula gs = Set.foldr' (\k a -> Set.foldr' (`Map.insert` k) a (FOL.groundings ts k)) Map.empty (Map.keysSet m) -- Separate the formula in sets of predicates: fs = Map.foldrWithKey (\k v a -> Map.insert (F.atoms k) v a) Map.empty gs -- | All possible assignments to the predicates in the network. allAss :: [Term] -> MLN -> [Map Predicate Bool] allAss ts mln = FOL.allAss $ allGroundings ts mln -- | Helper function to facilitate answering conditional & joint probability -- queries from the console. See 'Sphinx.Parser.parseCondQuery' and -- 'Sphinx.Parser.parseJointQuery' to understand what kind of strings can -- be parsed. ask :: MLN -- ^ A Markov logic network. -> [T.Text] -- ^ A list of constants to ground the Markov logic network. -> String -- ^ A query to be parsed by 'Sphinx.Parser.parseCondQuery' or 'Sphinx.Parser.parseJointQuery'. -> Maybe Double -- ^ Either a double in [0.0, 1.0] or Nothing if the parsers fail. ask mln terms query = pq <|> pj where ts = map Constant terms pq = case parseCondQuery query of Left _ -> Nothing; Right (q, c) -> Just $ conditional mln ts q c pj = case parseJointQuery query of Left _ -> Nothing; Right q -> Just $ joint mln ts q -- | Direct method of computing joint probabilities for Markov logic (does not -- scale!). partitionAss :: Set (Predicate, Bool) -- ^ The joint query. -> [Map Predicate Bool] -- ^ All possiblement assignments. -> ([Map Predicate Bool], [Map Predicate Bool]) -- ^ A probability in [0.0, 1.0] partitionAss query = partition valid where -- Check if an assignment fits the query: valid ass = Set.foldr' (\(k, v) acc -> acc && case Map.lookup k ass of Just b -> v == b; _ -> False) True query -- | Direct method of computing joint probabilities for Markov logic (does not -- scale!). joint :: MLN -- ^ The Markov logic network. -> [Term] -- ^ List of constants to ground the Markov logic network. -> Set (Predicate, Bool) -- ^ An set of assignments. The reason... -> Double -- ^ A probability in [0.0, 1.0] joint mln ts query = vq / z where vq = sum $ map evalNet toEval vo = sum $ map evalNet others z = vq + vo -- All possible assignments allass = allAss ts fs -- Assignments to evaluate: (toEval, others) = partitionAss query allass -- The formula (the factors) to evaluate fs = allWGroundings ts mln -- Value of the network for a given assignment. evalNet ass' = exp $ Map.foldrWithKey (\f w a -> val f w ass' + a) 0.0 (network fs) -- Values of a factor val f w ass' = let v = FOL.eval ass' f in if v == FOL.top then w else if v == FOL.bot then 0.0 else error ("Eval failed for " ++ show v ++ " given " ++ show ass') -- | Direct method of computing marginal probabilities for Markov logic (does -- not scale!). marginal :: MLN -- ^ The Markov logic network. -> [Term] -- ^ List of constants to ground the Markov logic network. -> Predicate-- ^ An assignment to all predicates in the Markov logic network. -> Bool -- ^ Truth value of the predicate. -> Double -- ^ A probability in [0.0, 1.0]Alicia Malone marginal mln ts p b = joint mln ts $ Set.fromList [(p, b)] -- | Direct method of computing conditional probabilities for Markov logic (does -- not scale!). conditional :: MLN -- ^ The Markov logic network. -> [Term] -- ^ List of constants to ground the Markov logic network. -> Set (Predicate, Bool) -- ^ An set of assignments for the query. -> Set (Predicate, Bool) -- ^ Conditions. -> Double -- ^ A probability in [0.0, 1.0] conditional mln ts query cond = vnum / vden where vnum = sum $ map evalNet numerator vden = sum $ map evalNet denom -- All possible assignments allass = allAss ts fs -- Assignments to evaluate: (numerator, _) = partitionAss (Set.union query cond) allass (denom, _ ) = partitionAss cond allass -- The formula (the factors) to evaluate fs = allWGroundings ts mln -- Value of the network for a given assignment. evalNet ass' = exp $ Map.foldrWithKey (\f w a -> val f w ass' + a) 0.0 (network fs) -- Values of a factor val f w ass' = let v = FOL.eval ass' f in if v == FOL.top then w else if v == FOL.bot then 0.0 else error ("Eval failed for " ++ show v ++ " given " ++ show ass') -- | Algorithm to construct a network for Markov logic network inference. -- -- Reference: -- P Domingos and D Lowd, Markov Logic: An Interface Layer for Artificial -- Intelligence, 2009, Morgan & Claypool. p. 26. constructNetwork :: Set Predicate -> [Predicate] -> [Term] -> MLN -> UNetwork Predicate constructNetwork query evidence ts (MLN m) = Set.foldr' (\p acc -> Map.insert p (mb p) acc) Map.empty ps where -- All groundings from all formulas in the knowledge base: gs = Set.foldr' (\g acc -> Set.union (FOL.groundings ts g) acc) Set.empty (Map.keysSet m) -- Predicates in the network ps = step query query -- The Markov blanket of predicate 'p', that is: all its neighbours. mb p = Set.delete p $ FS.allPredicates $ Set.filter (FOL.hasPred p) gs -- One step of the algorithm step f g | Set.null f = g | Set.findMin f `elem` evidence = step (Set.deleteMin f) g | otherwise = let mbq = mb $ Set.findMin f in step (Set.union (Set.deleteMin f) (Set.intersection mbq g)) (Set.union g mbq) -- | Builds a weighted knowledge base from a list of strings. If -- 'Sphinx.Parser.parseWFOL' fails to parse a formula, it is ignored. fromStrings :: [String] -- ^ A set of string, each of which is a first-order logic formula with a weight. Is being parsed by 'Sphinx.Parser.parseWFOL'. -> MLN -- ^ A Markov logic network. fromStrings s = MLN $ foldr (\k acc -> case parseWFOL k of Left _ -> acc Right (f, w) -> Map.insert f w acc) Map.empty s
PhDP/Manticore
Akarui/FOL/MarkovLogic.hs
apache-2.0
9,522
0
16
2,098
2,395
1,290
1,105
154
3
module EquationSolver.Solver where import EquationSolver.Common import Control.Monad.Error import Control.Monad.State import Control.Monad.Identity import Control.Monad.Writer import Data.List newtonReal :: Equation -> Flow [Double] newtonReal (Equation lhs rhs) = let lhs' = simplify lhs rhs' = simplify rhs vars = map head . group . sort $ extractVariables lhs' ++ extractVariables rhs' in solve 0 (map (\v -> (v, -1000)) vars) lhs' rhs' where solve 1000 _ _ _ = throwError "No more iterations available." solve step vars lhs rhs = let lvalue = evaluate vars lhs rvalue = evaluate vars rhs in if abs (rvalue - lvalue) > theta then solve (step + 1) (map (\(x, v) -> (x, v + 0.1)) vars) lhs rhs else return $ map (\(x, v) -> v) vars where theta = 0 evaluate :: [(Char, Double)] -> Expr -> Double evaluate substitution (Mult a b) = (evaluate substitution a) * (evaluate substitution b) evaluate substitution (Div a b) = (evaluate substitution a) / (evaluate substitution b) evaluate substitution (Plus a b) = (evaluate substitution a) + (evaluate substitution b) evaluate substitution (Minus a b) = (evaluate substitution a) - (evaluate substitution b) evaluate substitution (Pow a b) = (evaluate substitution a) ** (evaluate substitution b) evaluate substitution (Sqrt a) = sqrt (evaluate substitution a) evaluate substitution (Variable x) = case lookup x substitution of Just v -> v evaluate _ (Constant c) = c substitute :: Expr -> Char -> Double -> Expr substitute (Mult a b) x value = Mult (substitute a x value) (substitute b x value) substitute (Div a b) x value = Div (substitute a x value) (substitute b x value) substitute (Plus a b) x value = Plus (substitute a x value) (substitute b x value) substitute (Minus a b) x value = Minus (substitute a x value) (substitute b x value) substitute (Pow a b) x value = Pow (substitute a x value) (substitute b x value) substitute (Sqrt a) x value = Sqrt (substitute a x value) substitute v@(Variable x') x value | x' == x = (Constant value) | otherwise = v extractVariables :: Expr -> [Char] extractVariables (Mult a b) = extractVariables a ++ extractVariables b extractVariables (Div a b) = extractVariables a ++ extractVariables b extractVariables (Sqrt a) = extractVariables a extractVariables (Plus a b) = extractVariables a ++ extractVariables b extractVariables (Minus a b) = extractVariables a ++ extractVariables b extractVariables (Pow a b) = extractVariables a ++ extractVariables b extractVariables (Variable v) = [v] extractVariables _ = [] algebraicReal :: Equation -> Flow [Double] algebraicReal (Equation lhs rhs) = solve $ simplify $ reduce lhs rhs where solve :: Expr -> Flow [Double] solve (Minus (Constant c) (Variable x)) = return [c] solve (Plus (Constant c) (Variable x)) = return [(-c)] solve (Plus (Constant c) (Mult (Constant a) (Variable x))) = return [c / a] solve (Plus (Constant c) (Plus (Mult (Constant a) (Pow (Variable x1) (Constant 2))) (Mult (Constant b) (Variable x2)))) = quadratic a b c solve (Plus (Constant c) (Plus (Pow (Variable x1) (Constant 2)) (Mult (Constant b) (Variable x2)))) = quadratic 1 b c solve (Plus (Constant c) (Plus (Pow (Variable x1) (Constant 2)) (Variable x2))) = quadratic 1 1 c solve (Plus (Pow (Variable x1) (Constant 2)) (Variable x2)) = quadratic 1 0 1 solve x = do tell ["Don't know how solve " ++ (show x)] throwError $ "Fail at " ++ (show x) quadratic a b c = let d = b * b - 4 * a * c in if (d >= 0) then return [(-b / 2 * a) + sqrt d, (-b / 2 * a) - sqrt d] else throwError "Complex solution" reduce :: Expr -> Expr -> Expr reduce lhs (Constant 0) = order lhs reduce lhs rhs = order $ Plus lhs (Mult (Constant (-1)) rhs) simplify :: Expr -> Expr -- constant collapse simplify (Mult (Constant a) (Constant b)) = Constant (a * b) simplify (Div (Constant a) (Constant b)) = Constant (a / b) simplify (Plus (Constant a) (Constant b)) = Constant (a + b) simplify (Minus (Constant a) (Constant b)) = Constant (a - b) -- pow, /, *, + simplify (Mult (Constant 1) x) = order $ simplify x simplify (Mult (Constant 0) x) = Constant 0 simplify (Div x (Constant 1)) = order $ simplify x simplify (Plus (Constant 0) x) = order $ simplify x simplify (Pow x (Constant 1)) = order $ simplify x simplify (Pow x (Constant 0)) = Constant 1 simplify (Mult a b) = order $ simplify' a b Mult simplify (Div a b) = order $ simplify' a b Div simplify (Plus a b) = order $ simplify' a b Plus simplify (Minus a b) = order $ simplify' a b Minus simplify (Pow a b) = order $ simplify' a b Pow simplify x = x simplify' :: Expr -> Expr -> (Expr -> Expr -> Expr) -> Expr simplify' a b expr = let (sa, sb) = (simplify a, simplify b) in if (sa /= a || sb /= b) then simplify $ expr sa sb else expr a b order :: Expr -> Expr order (Mult x c@(Constant _)) = Mult c x order (Plus x c@(Constant _)) = Plus c x order (Minus x c@(Constant _)) = Minus c x order x = x -- solveEquation :: Equation -> (Equation -> Flow a) Flow a -- solveEquation equation method = met runSolveEquation :: Flow Equation -> (Equation -> Flow a) -> Either String a runSolveEquation equation method = fst $ runIdentity $ runWriterT $ runErrorT $ equation >>= method
janm399/equationsolver
src/EquationSolver/Solver.hs
apache-2.0
5,800
0
17
1,611
2,544
1,273
1,271
107
9
{-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-type-defaults #-} module Blockchain.Colors ( red , green , yellow , blue , magenta , cyan , white2 , white , black , bright , dim , underline , blink , Blockchain.Colors.reverse , hidden , setTitle ) where bright string = "\ESC[1m" ++ string ++ "\ESC[0m" dim string = "\ESC[2m" ++ string ++ "\ESC[0m" underline string = "\ESC[4m" ++ string ++ "\ESC[0m" blink string = "\ESC[5m" ++ string ++ "\ESC[0m" reverse string = "\ESC[7m" ++ string ++ "\ESC[0m" hidden string = "\ESC[8m" ++ string ++ "\ESC[0m" black string = "\ESC[30m" ++ string ++ "\ESC[0m" red string = "\ESC[31m" ++ string ++ "\ESC[0m" green string = "\ESC[32m" ++ string ++ "\ESC[0m" yellow string = "\ESC[33m" ++ string ++ "\ESC[0m" blue string = "\ESC[34m" ++ string ++ "\ESC[0m" magenta string = "\ESC[35m" ++ string ++ "\ESC[0m" --AKA purple cyan string = "\ESC[36m" ++ string ++ "\ESC[0m" --AKA aqua white string = "\ESC[37m" ++ string ++ "\ESC[0m" white2 string = "\ESC[38m" ++ string ++ "\ESC[0m" setTitle :: String -> IO () setTitle value = putStr $ "\ESC]0;" ++ value ++ "\007"
zchn/ethereum-analyzer
ethereum-analyzer-deps/src/Blockchain/Colors.hs
apache-2.0
1,157
0
7
235
336
179
157
35
1
-- vim: sw=2: ts=2: set expandtab: {-# LANGUAGE QuasiQuotes, TemplateHaskell, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, UndecidableInstances, CPP #-} ----------------------------------------------------------------------------- -- -- Module : Parser -- Copyright : BSD -- License : AllRightsReserved -- -- Maintainer : Ki Yung Ahn -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module Parser where import Language.LBNF hiding (printTree) import Language.LBNF.Runtime (Doc) import Unbound.LocallyNameless hiding (Con, Data) import Unbound.LocallyNameless.Ops (unsafeUnbind) import Syntax (Ki, Ty, Tm, PSUT, isKi, isTy, isTm) import qualified Syntax as S import Control.Applicative import System.IO import Data.Char -- import Debug.Trace trace _ a = a -- antiquote "[" ":" ":]" ; bnfc [lbnf| token CommentHeader ( '-' '-' ) ; comment "--" ; token BlockCommentOpen ( '{' '-' ) ; token BlockCommentClose ( '-' '}' ) ; comment "{-" "-}" ; token LIdent ( ('`' | lower | '_') (letter | digit | '_' | '\'')* ) ; token UIdent (upper (letter | digit | '_' | '\'')* ) ; Prog. Prog ::= [Dec] ; KVar. Kind2 ::= LIdent ; KStar. Kind2 ::= "*" ; KArr. Kind1 ::= KArg "->" Kind1 ; coercions Kind 2 ; KArgL. KArg ::= "{" Type "}" ; KArgR. KArg ::= Kind2 ; TVar. Type3 ::= LIdent ; TCon. Type3 ::= UIdent ; TArr. Type1 ::= Type2 "->" Type1 ; TApp. Type2 ::= Type2 TArg; TFix. Type2 ::= "Mu" Type3 ; coercions Type 3 ; TArgL. TArg ::= "{" Term "}" ; TArgR. TArg ::= Type3 ; Var. Term3 ::= LIdent ; Con. Term3 ::= UIdent ; In . Term2 ::= "In" Integer Term3 ; MIt. Term2 ::= "mit" LIdent "{" [Alt] "}" ; MItAnn. Term2 ::= "mit" LIdent "{" IxMap "}" "{" [Alt] "}" ; MPr. Term2 ::= "mpr" LIdent LIdent "{" [Alt] "}" ; MPrAnn. Term2 ::= "mpr" LIdent LIdent "{" IxMap "}" "{" [Alt] "}" ; Lam. Term1 ::= "\\" LIdent "->" Term1 ; App. Term2 ::= Term2 Term3 ; Let. Term1 ::= "let" LIdent "=" Term1 "in" Term1 ; Alt. Term3 ::= "{" [Alt] "}" ; AltAnn. Term3 ::= "{" IxMap "}" "{" [Alt] "}" ; coercions Term 3 ; Case. Alt ::= UIdent [LIdent] "->" Term ; separator Alt ";" ; Phi. IxMap ::= [IVar] "." Type ; IVarR. IVar ::= LIdent ; IVarL. IVar ::= "{" LIdent "}" ; []. [IVar] ::= ; (:). [IVar] ::= IVar [IVar] ; []. [LIdent] ::= ; (:). [LIdent] ::= LIdent [LIdent] ; []. [Type3] ::= ; (:). [Type3] ::= Type3 [Type3] ; Gadt. Dec ::= "data" UIdent [IVar] ":" Kind "where" "{" [GadtAlt] "}" ; Data. Dec ::= "data" UIdent [IVar] "=" [DataAlt] ; Def. Dec ::= LIdent "=" Term ; separator Dec ";" ; GAlt. GadtAlt ::= UIdent ":" Type ; separator GadtAlt ";"; DAlt. DataAlt ::= UIdent [Type3] ; separator DataAlt "|"; |] -- entrypoints Prog, Dec, Kind, Type, Term ; instance Print S.PSUT where prt n x | isKi x = prt n (ki2Kind x) | isTy x = prt n (ty2Type x) | isTm x = prt n (tm2Term x) prtList xs@(x:_) | isKi x = prtList (map ki2Kind xs) | isTy x = prtList (map ty2Type xs) | isTm x = prtList (map tm2Term xs) prtList [] = prtList ([]::[Integer]) -- instance Print Ki where -- prt n = prt n . ki2Kind -- prtList = prtList . map ki2Kind -- -- instance Print Ty where -- prt n = prt n . ty2Type -- prtList = prtList . map ty2Type -- -- instance Print Tm where -- prt n = prt n . tm2Term -- prtList = prtList . map tm2Term -- Translating between BNFC syntax and Unbound syntax kind2Ki KStar = S.Star kind2Ki (KVar (LIdent s)) = S.Var (string2Name s) kind2Ki (KArr (KArgR k1) k2) = S.KArr (Right $ kind2Ki k1) (kind2Ki k2) kind2Ki (KArr (KArgL t1) k2) = S.KArr (Left $ type2Ty t1) (kind2Ki k2) ki2Kind S.Star = KStar ki2Kind (S.Var nm) = KVar (LIdent $ show nm) ki2Kind (S.KArr (Right k1) k2) = KArr (KArgR $ ki2Kind k1) (ki2Kind k2) ki2Kind (S.KArr (Left t1) k2) = KArr (KArgL $ ty2Type t1) (ki2Kind k2) type2Ty (TVar (LIdent s)) = S.Var (string2Name s) type2Ty (TCon (UIdent s)) = S.TCon (string2Name s) type2Ty (TArr t1 t2) = S.TArr (type2Ty t1) (type2Ty t2) type2Ty (TApp t1 (TArgR t2)) = S.TApp (type2Ty t1) (Right $ type2Ty t2) type2Ty (TApp t1 (TArgL e2)) = S.TApp (type2Ty t1) (Left $ term2Tm e2) type2Ty (TFix t) = S.TFix (type2Ty t) ty2Type (S.Var nm) = TVar (LIdent $ show nm) ty2Type (S.TCon nm) = TCon (UIdent $ show nm) ty2Type (S.TArr t1 t2) = TArr (ty2Type t1) (ty2Type t2) ty2Type (S.TApp t1 (Right t2)) = TApp (ty2Type t1) (TArgR $ ty2Type t2) ty2Type (S.TApp t1 (Left e2)) = TApp (ty2Type t1) (TArgL $ tm2Term e2) ty2Type (S.TFix t) = TFix (ty2Type t) term2Tm (Var (LIdent s)) = S.Var (string2Name s) term2Tm (Con (UIdent s)) = S.Con (string2Name s) term2Tm (In n e) = S.In n (term2Tm e) term2Tm (MIt (LIdent f) as) = S.MIt $ bind (string2Name f) $ term2Tm (Alt as) term2Tm (MItAnn (LIdent f) phi as) = S.MIt $ bind (string2Name f) $ term2Tm (AltAnn phi as) term2Tm (MPr (LIdent f) (LIdent cast) as) = S.MPr $ bind (string2Name f, string2Name cast) $ term2Tm (Alt as) term2Tm (MPrAnn (LIdent f) (LIdent cast) phi as) = S.MPr $ bind (string2Name f, string2Name cast) $ term2Tm (AltAnn phi as) term2Tm (Lam (LIdent s) e) = S.Lam (bind (string2Name s) (term2Tm e)) term2Tm (App e1 e2) = S.App (term2Tm e1) (term2Tm e2) term2Tm (Let (LIdent s) e1 e2) = S.Let (bind (string2Name s, embed (term2Tm e1)) (term2Tm e2)) term2Tm (Alt cs) = S.Alt Nothing [ (string2Name c, bind [string2Name s | LIdent s <- as] (term2Tm e)) | Case (UIdent c) as e <- cs ] term2Tm (AltAnn (Phi xs ty) cs) = S.Alt (Just $ bind (map ident2names xs) (type2Ty ty)) [ (string2Name c, bind [string2Name s | LIdent s <- as] (term2Tm e)) | Case (UIdent c) as e <- cs ] where ident2names (IVarR (LIdent s)) = Right (string2Name s) ident2names (IVarL (LIdent s)) = Left (string2Name s) tm2Term (S.Var nm) = Var (LIdent $ show nm) tm2Term (S.Con nm) = Con (UIdent $ show nm) tm2Term (S.In n e) = In n (tm2Term e) tm2Term (S.MIt b) = case tm2Term sAlt of Alt cs -> MIt (LIdent $ show nm) cs AltAnn phi cs -> MItAnn (LIdent $ show nm) phi cs where (nm,sAlt) = unsafeUnbind b tm2Term (S.MPr b) = case tm2Term sAlt of Alt cs -> MPr (LIdent $ show nm1) (LIdent $ show nm2) cs AltAnn phi cs -> MPrAnn (LIdent $ show nm1) (LIdent $ show nm2) phi cs where ((nm1,nm2),sAlt) = unsafeUnbind b tm2Term (S.Lam bnd) = Lam (LIdent $ show nm) (tm2Term e) where (nm,e) = unsafeUnbind bnd tm2Term (S.App e1 e2) = App (tm2Term e1) (tm2Term e2) tm2Term (S.Let bnd) = Let (LIdent $ show nm) (tm2Term e1) (tm2Term e2) where ((nm,Embed e1),e2) = unsafeUnbind bnd tm2Term (S.Alt Nothing cs) = Alt [ Case (UIdent c) (map (LIdent . show) as) (tm2Term e) | (c,(as,e)) <- map (\(nm,bnd) -> (show nm, unsafeUnbind bnd)) cs ] tm2Term (S.Alt (Just phi) cs) = AltAnn (Phi (map names2ident nms) (ty2Type ty)) [ Case (UIdent c) (map (LIdent . show) as) (tm2Term e) | (c,(as,e)) <- map (\(nm,bnd) -> (show nm, unsafeUnbind bnd)) cs ] where (nms,ty) = unsafeUnbind phi names2ident (Right nm) = IVarR (LIdent $ show nm) names2ident (Left nm) = IVarL (LIdent $ show nm) tm2Term t = Con(UIdent $ printTree t) hTokens h = tokens <$> hGetContents h hProg h = pProg <$> hTokens h ------------------------------------------------------ -- -- * Overloaded pretty-printer printTree :: Print a => a -> String printTree = render . prt 0 render :: Doc -> String render = renderN 0 renderN n d = rend n (map ($ "") $ d []) "" where rend i ss = case ss of "[" :ts -> showChar '[' . rend i ts "(" :ts -> showChar '(' . rend i ts "{" :ts -> let rendDefault = showChar '{' . new (i+1) . rend (i+1) ts (ts1, ts2) = break (=="}") ts in if (null ts2 || elem "{" ts1 || elem ";" ts1) then rendDefault else case ts2 of "}":";":ts' -> showChar '{' . rend i ts1 . space "}" . showChar ';' . new i . rend i ts' "}" :ts' -> let rend_ts1 = case ts1 of [] -> id [t] -> showString t _ -> rend i ts1 in showChar '{' . rend_ts1 . space "}" . rend i ts' _ -> rendDefault "}" : ";":ts -> new (i-1) . showChar '}' . showChar ';' . new (i-1) . rend (i-1) ts "}" :ts -> new (i-1) . showChar '}' . new (i-1) . rend (i-1) ts ";" :ts -> showChar ';' . new i . rend i ts t : "," :ts -> showString t . space "," . rend i ts t : ")" :ts@(")":_) -> showString t . showChar ')' . rend i ts t : ")" :ts@("}":_) -> showString t . showChar ')' . rend i ts t : ")" :[] -> showString t . showChar ')' t : ")" :ts -> showString t . space ")" . rend i ts t : "]" :ts -> showString t . showChar ']' . rend i ts t :[] -> showString t t :ts -> space t . rend i ts _ -> id new i = showChar '\n' . replicateS (2*i) (showChar ' ') . dropWhile isSpace space t = showString t . (\s -> if null s then "" else (' ':s)) concatS :: [ShowS] -> ShowS concatS = foldr (.) id replicateS :: Int -> ShowS -> ShowS replicateS n f = concatS (replicate n f) ------------------------------------------------------ instance Show PSUT where show = printTree instance Alpha PSUT where instance Subst PSUT PSUT where isvar (S.Var x) = Just (SubstName x) -- isvar (S.TCon x) = Just (SubstName x) -- isvar (S.Con x) = Just (SubstName x) isvar _ = Nothing
kyagrd/mininax
src/Parser.hs
bsd-2-clause
9,849
0
23
2,657
3,592
1,788
1,804
149
21
module Translate where import My.Control.Monad import qualified Data.Map as M import Data.Maybe import Data.Bimap as BM import ID import PCode import Context.Types as C class Translatable t where translate :: (ID -> ID) -> t -> t mapTranslate m = \s -> fromMaybe s $ M.lookup s m instance Translatable ID where translate = ($) instance Translatable a => Translatable (Range a) where translate t (Range (a,b)) = Range (translate t a,translate t b) instance Translatable e => Translatable [e] where translate tr l = map (translate tr) l instance Translatable C.Value where translate tr (Verb code) = Verb (translate tr code) translate tr (Noun size init) = Noun (translate tr size) (translate tr init) translate tr x = x instance Translatable Instruction where translate tr (Op b v vs) = Op b (translate tr v) (translate tr vs) translate tr (Branch v as) = Branch (translate tr v) as translate tr (Bind bv v) = Bind (translate tr bv) (fmap (translate tr) v) translate tr Noop = Noop instance Translatable PCode.Value where translate tr (SymVal t id) = SymVal t (translate tr id) translate tr v = v instance Translatable Code where translate tr (Code args code ret) = Code (translate tr args) (translate tr code) (fmap (translate tr) ret) instance Translatable BindVar where translate tr (BindVar id s pad subs) = BindVar (translate tr id) s pad [(translate tr bv,s) | (bv,s) <- subs]
lih/Alpha
src/Translate.hs
bsd-2-clause
1,419
0
10
273
629
322
307
33
1
module Main where import Data.Binary import Data.Binary.Typed import qualified Data.ByteString.Lazy as BSL import Data.Typeable (Typeable) import Data.Int import Text.Printf main :: IO () main = do putStrLn "Comparison of message lengths depending on serialization method" putStrLn "===============================================================" putStrLn "" putStrLn (ppr (measure "maxBound :: Int" (maxBound :: Int))) putStrLn (ppr (measure "\"Hello\"" "Hello")) putStrLn (ppr (measure "100 chars lipsum" lipsum)) putStrLn (ppr (measure "Right (Left \"Hello\") :: Either (Char, Int) (Either String (Maybe Integer))" (Right (Left "Hello") :: Either (Char, Int) (Either String (Maybe Integer))))) lipsum :: String lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam\ \ vitae lacinia tellus. Maecenas posuere." data EncodeLengths = EL { info :: String , binary :: Int64 , typedUntyped :: Int64 , typedHashed32 :: Int64 , typedHashed64 :: Int64 , typedShown :: Int64 , typedFull :: Int64 } -- | Prettyprint 'EncodeLengths' ppr :: EncodeLengths -> String ppr el = unlines [ info el , printf " Binary: %d" (binary el) , printf " Typed/Untyped: %d (+%d, +%2.2f%%)" (typedUntyped el) (absolute (binary el) (typedUntyped el)) (percent (binary el) (typedUntyped el)) , printf " Typed/Hashed32: %d (+%d, +%2.2f%%)" (typedHashed32 el) (absolute (binary el) (typedHashed32 el)) (percent (binary el) (typedHashed32 el)) , printf " Typed/Hashed64: %d (+%d, +%2.2f%%)" (typedHashed64 el) (absolute (binary el) (typedHashed64 el)) (percent (binary el) (typedHashed64 el)) , printf " Typed/Shown: %d (+%d, +%2.2f%%)" (typedShown el) (absolute (binary el) (typedShown el)) (percent (binary el) (typedShown el)) , printf " Typed/Full: %d (+%d, +%2.2f%%)" (typedFull el) (absolute (binary el) (typedFull el)) (percent (binary el) (typedFull el)) ] -- | Calculate how much percent the first parameter deviates from the second. percent :: Int64 -> Int64 -> Double percent base x = let x' = fromIntegral x base' = fromIntegral base in abs ((x'-base')*100/base') -- | Absolute deviation of the second from the first parameter absolute :: Int64 -> Int64 -> Int64 absolute base x = x - base -- | Measure the message lengths generated by different encodings. measure :: (Binary a, Typeable a) => String -> a -> EncodeLengths measure i x = EL { info = i , binary = BSL.length binary' , typedUntyped = BSL.length typedUntyped' , typedHashed32 = BSL.length typedHashed32' , typedHashed64 = BSL.length typedHashed64' , typedShown = BSL.length typedShown' , typedFull = BSL.length typedFull' } where binary' = encode x typedUntyped' = encodeTyped Untyped x typedHashed32' = encodeTyped Hashed32 x typedHashed64' = encodeTyped Hashed64 x typedShown' = encodeTyped Shown x typedFull' = encodeTyped Full x
quchen/binary-typed
benchmark/MessageLength.hs
bsd-2-clause
3,895
0
17
1,513
863
450
413
69
1
{-# LANGUAGE FlexibleContexts #-} module Revelation.Utils where import Pipes import Linear import Revelation.Mat import Revelation.Core import Control.Monad import Control.Lens import Data.Vector.Storable as VS indexP :: (Storable (ElemT c e), Show (ElemT c e), CVElement (ElemT c e), Storable (Vector (ElemT c e))) => V2 Int -> Pipe (Mat rs cs c e) (Mat rs cs c e) CV () indexP i = forever $ do m <- await let v = m ^. neighborhood 1 i liftCV $ print (show v) yield m
arjuncomar/revelation
Revelation/Utils.hs
bsd-3-clause
527
0
12
141
212
109
103
15
1
module Network.HTTP.Types.Method ( Method , methodGet , methodPost , methodHead , methodPut , methodDelete , methodTrace , methodConnect , methodOptions , StdMethod(..) , parseMethod , renderMethod , renderStdMethod ) where import Control.Arrow ((|||)) import Data.Array import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 -- | HTTP method (flat string type). type Method = B.ByteString -- | HTTP Method constants. methodGet, methodPost, methodHead, methodPut, methodDelete, methodTrace, methodConnect, methodOptions :: Method methodGet = renderStdMethod GET methodPost = renderStdMethod POST methodHead = renderStdMethod HEAD methodPut = renderStdMethod PUT methodDelete = renderStdMethod DELETE methodTrace = renderStdMethod TRACE methodConnect = renderStdMethod CONNECT methodOptions = renderStdMethod OPTIONS -- | HTTP standard method (as defined by RFC 2616). data StdMethod = GET | POST | HEAD | PUT | DELETE | TRACE | CONNECT | OPTIONS deriving (Read, Show, Eq, Ord, Enum, Bounded, Ix) -- These are ordered by suspected frequency. More popular methods should go first. -- The reason is that methodList is used with lookup. -- lookup is probably faster for these few cases than setting up an elaborate data structure. methodArray :: Array StdMethod Method methodArray = listArray (minBound, maxBound) $ map (B8.pack . show) [minBound :: StdMethod .. maxBound] methodList :: [(Method, StdMethod)] methodList = map (\(a, b) -> (b, a)) (assocs methodArray) -- | Convert a method 'ByteString' to a 'StdMethod' if possible. parseMethod :: Method -> Either B.ByteString StdMethod parseMethod bs = maybe (Left bs) Right $ lookup bs methodList -- | Convert an algebraic method to a 'ByteString'. renderMethod :: Either B.ByteString StdMethod -> Method renderMethod = id ||| renderStdMethod -- | Convert a 'StdMethod' to a 'ByteString'. renderStdMethod :: StdMethod -> Method renderStdMethod m = methodArray ! m
kazu-yamamoto/http-types
Network/HTTP/Types/Method.hs
bsd-3-clause
2,040
0
9
381
437
260
177
49
1
-- Test data start_v2 = Coordinates 1 1 start_p = Coordinates 15.0 15.0 board = Board 123456 (Paddle 19 "foo") (Paddle 14 "bar") (Ball (Coordinates 100 100)) (Conf 640 480 50 10 5 15) board' = Board 123471 (Paddle 19 "foo") (Paddle 14 "bar") (Ball (Coordinates 2 2)) (Conf 640 480 50 10 5 15) losingHistory = [board',board] winningBoard = Board 123456 (Paddle 19 "foo") (Paddle 14 "bar") (Ball (Coordinates 500 400)) (Conf 640 480 50 10 5 15) winningBoard' = Board 123471 (Paddle 19 "foo") (Paddle 14 "bar") (Ball (Coordinates 639 479)) (Conf 640 480 50 10 5 15) winningHistory = [winningBoard',winningBoard]
timorantalaiho/pong11
test/TestData.hs
bsd-3-clause
614
2
9
108
298
149
149
8
1
module Container.Tree.Morph where import Generics.Fixpoint import qualified Container.Tree.Abstract as F import qualified Generics.Morphism.Ana as Ana () import qualified Generics.Morphism.Apo as Apo import qualified Generics.Morphism.Cata as Cata () import qualified Generics.Morphism.Para as Para -- Insert is WRONG! see EQ case that throws existing k v. insert :: Ord k => k -> v -> Apo.CoEndo (F.Tree k v) insert k v = Apo.Phi $ \(InF s) -> case s of F.Branch m w l r -> case k `compare` m of LT -> F.Branch m w (Left l) (Left r) EQ -> F.Branch k v (Right l) (Left r) GT -> F.Branch m w (Right l) (Right r) F.Leaf -> F.Branch k v (Right (InF F.Leaf)) (Right (InF F.Leaf)) fromList :: Apo.Coalg [(k, v)] (F.Tree k v) fromList = Apo.Phi $ \f -> case f of [] -> F.Leaf (k, v):xs -> let l = take (length xs `div` 2) xs r = drop (length l) xs in F.Branch k v (Left l) (Left r) lookup :: Ord k => k -> Para.Alg (F.Tree k v) (Maybe v) lookup k = Para.Psi $ \f -> case f of F.Leaf -> Nothing F.Branch c d (_, l) (_, r) -> case k `compare` c of LT -> l EQ -> Just d GT -> r size :: Num n => Para.Alg (F.Tree k v) n size = Para.Psi $ \f -> case f of F.Leaf -> 0 F.Branch _ _ (_, l) (_, r) -> 1 + l + r depth :: (Ord n, Num n) => Para.Alg (F.Tree k v) n depth = Para.Psi $ \f -> case f of F.Leaf -> 0 F.Branch _ _ (_, l) (_, r) -> 1 + max l r
sebastiaanvisser/islay
src/Container/Tree/Morph.hs
bsd-3-clause
1,560
0
17
509
762
405
357
43
4