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
import Data.List import Data.Char vowels = "aeiou" doubles = [ [c, c] | i <- [0..25], let c = chr (ord 'a' + i) ] bad = ["ab", "cd", "pq", "xy"] good s = hasVowels && hasDoubles && notBad where hasVowels = length (filter (`elem` vowels) s) >= 3 hasDoubles = any (`isInfixOf` s) doubles notBad = not $ any (`isInfixOf` s) bad answer f = interact $ (++"\n") . show . f main = answer $ length . filter good . lines
msullivan/advent-of-code
2015/A5a.hs
mit
434
0
13
105
207
116
91
11
1
module Main where -- β€’ How many different ways can you find to write allEven? allEvenComprehension :: [Integer] -> [Integer] allEvenComprehension list = [x | x <- list, even x] allEvenFilter :: [Integer] -> [Integer] allEvenFilter list = filter even list -- β€’ Write a function that takes a list and returns the same list in reverse. reverseList [] = [] reverseList (h:t) = reverseList(t) ++ [h] -- β€’ Write a function that builds two-tuples with all possible combinations of two of the colors black, white, blue, yellow, and red. Note that you should include only one of (black, blue) and (blue, black). colorCombinations = do let colors = ["black", "white", "yellow", "red"] [(a, b) | a <- colors, b <- colors, a <= b] -- β€’ Write a list comprehension to build a childhood multiplication table. The table would be a list of three-tuples where the first two are integers from 1–12 and the third is the product of the first two. multiplicationTable = [(a, b, a * b) | a <- [1..12], b <- [1..12] ] -- β€’ Solve the map-coloring problem (Map Coloring,on page 101) using Haskell. mapColoring = do let colors = ["red", "green", "blue"] [("Alabama", a, "Mississippi", m, "Georgia", g, "Tennessee", t, "Florida", f) | a <- colors, m <- colors, g <- colors, t <- colors, f <- colors, m /= t, m /= a, a /= t, a /= m, a /= g, a /= f, g /= f, g /= t ]
hemslo/seven-in-seven
haskell/day1/day1.hs
mit
1,400
0
10
301
390
215
175
16
1
-- From a blog post: http://www.jonmsterling.com/posts/2012-01-12-unifying-monoids-and-monads-with-polymorphic-kinds.html {-# LANGUAGE PolyKinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE TypeFamilies #-} module Main where import Data.Kind import Control.Monad (Monad(..), join, ap, liftM) import Data.Monoid (Monoid(..)) import Data.Semigroup (Semigroup(..)) -- First we define the type class Monoidy: class Monoidy (to :: k0 -> k1 -> Type) (m :: k1) where type MComp to m :: k1 -> k1 -> k0 type MId to m :: k0 munit :: MId to m `to` m mjoin :: MComp to m m m `to` m -- We use functional dependencies to help the typechecker understand that -- m and ~> uniquely determine comp (times) and id. -- This kind of type class would not have been possible in previous -- versions of GHC; with the new kind system, however, we can abstract -- over kinds!2 Now, let’s create types for the additive and -- multiplicative monoids over the natural numbers: newtype Sum a = Sum a deriving Show newtype Product a = Product a deriving Show instance Num a β‡’ Monoidy (β†’) (Sum a) where type MComp (β†’) (Sum a) = (,) type MId (β†’) (Sum a) = () munit _ = Sum 0 mjoin (Sum x, Sum y) = Sum $ x + y instance Num a β‡’ Monoidy (β†’) (Product a) where type MComp (β†’) (Product a) = (,) type MId (β†’) (Product a) = () munit _ = Product 1 mjoin (Product x, Product y) = Product $ x * y -- It will be slightly more complicated to make a monadic instance with -- Monoidy. First, we need to define the identity functor, a type for -- natural transformations, and a type for functor composition: data Id Ξ± = Id { runId :: Ξ± } deriving Functor -- A natural transformation (Λ f g Ξ±. (f Ξ±) → (g Ξ±)) may be encoded in Haskell as follows: data NT f g = NT { runNT :: βˆ€ Ξ±. f Ξ± β†’ g Ξ± } -- Functor composition (Λ f g Ξ±. f (g Ξ±)) is encoded as follows: data FC f g Ξ± = FC { runFC :: f (g Ξ±) } -- Now, let us define some type T which should be a monad: data Wrapper a = Wrapper { runWrapper :: a } deriving (Show, Functor) instance Monoidy NT Wrapper where type MComp NT Wrapper = FC type MId NT Wrapper = Id munit = NT $ Wrapper . runId mjoin = NT $ runWrapper . runFC -- With these defined, we can use them as follows: test1 = do { print (mjoin (munit (), Sum 2)) -- Sum 2 ; print (mjoin (Product 2, Product 3)) -- Product 6 ; print (runNT mjoin $ FC $ Wrapper (Wrapper "hello, world")) -- Wrapper {runWrapper = "hello, world" } } -- We can even provide a special binary operator for the appropriate monoids as follows: (<+>) :: (Monoidy (β†’) m, MId (β†’) m ~ (), MComp (β†’) m ~ (,)) β‡’ m β†’ m β†’ m (<+>) = curry mjoin test2 = print (Sum 1 <+> Sum 2 <+> Sum 4) -- Sum 7 -- Now, all the extra wrapping that Haskell requires for encoding this is -- rather cumbersome in actual use. So, we can give traditional Monad and -- Monoid instances for instances of Monoidy: instance (MId (β†’) m ~ (), MComp (β†’) m ~ (,), Monoidy (β†’) m) β‡’ Semigroup m where (<>) = curry mjoin instance (MId (β†’) m ~ (), MComp (β†’) m ~ (,), Monoidy (β†’) m) β‡’ Monoid m where mempty = munit () instance Applicative Wrapper where pure = return (<*>) = ap instance Monad Wrapper where return x = runNT munit $ Id x x >>= f = runNT mjoin $ FC (f `fmap` x) -- And so the following works: test3 = do { print (mappend mempty (Sum 2)) -- Sum 2 ; print (mappend (Product 2) (Product 3)) -- Product 6 ; print (join $ Wrapper $ Wrapper "hello") -- Wrapper {runWrapper = "hello" } ; print (Wrapper "hello, world" >>= return) -- Wrapper {runWrapper = "hello, world" } } main = test1 >> test2 >> test3
ghcjs/ghcjs
test/ghc/polykinds/monoidsTF.hs
mit
4,111
2
12
993
1,105
613
492
-1
-1
module Topology.Main where import Notes import Topology.MetricSpace import Topology.TopologicalSpace topology :: Note topology = chapter "Topology" $ do topologicalSpaceS metricSpaceS
NorfairKing/the-notes
src/Topology/Main.hs
gpl-2.0
229
0
7
65
42
23
19
8
1
module PrefixTree (Dict ,suggest ,suggestAny ,mkDict) where import Data.List (find, groupBy, isPrefixOf, stripPrefix) import Data.Map (Map) import Data.Maybe (maybe) import Data.Function (on) import qualified Data.Map as Map data Dict = Index (Map Char Dict) | Words [String] deriving (Show) suggest :: Dict -> String -> Maybe String suggest d@(Index m) s = case s of (c:cs) -> Map.lookup c m >>= \d -> suggest d cs [] -> Just (suggestAny d) suggest (Words ws) p = find (isPrefixOf p) ws >>= stripPrefix p suggestAny :: Dict -> String suggestAny (Index m) = let (c,d) = head $ Map.assocs m in c : suggestAny d suggestAny (Words ws) = head ws -- (mkDict n ws) create a dictionary with words ws indexed on the -- n first characters. -- n should not be to big -- 2 or 3 should suffice for a small set of -- words. -- ws must be sorted mkDict :: Int -> [String] -> Dict mkDict l ws | l < 1 = Words ws | otherwise = let gs = groupBy ((==) `on` head) (filter (not . null) ws) as = map (\ws -> (head $ head ws, mkDict (l-1) (map tail ws))) gs in Index $ Map.fromList as
holmisen/hrunner
src/PrefixTree.hs
gpl-3.0
1,209
0
16
350
460
245
215
30
2
module Hob.Ui.CommandEntrySpec (main, spec) where import Control.Monad.Reader import Data.IORef import Graphics.UI.Gtk import Graphics.UI.Gtk.General.StyleContext import Hob.Context import Hob.Context.UiContext import Hob.Control import Hob.Ui.CommandEntry import Test.Hspec import HobTest.Context.Default import HobTest.Control type CommandHandlerReaders = (IO (Maybe String), IO (Maybe String), IO (Maybe String)) type EntryApi = (App(), App()) main :: IO () main = hspec spec spec :: Spec spec = describe "command entry" $ do it "is named" $ do ctx <- loadDefaultContext name <- widgetGetName $ commandEntry . uiContext $ ctx name `shouldBe` "commandEntry" it "initially there is no error class applied" $ do ctx <- loadDefaultContext styleCtx <- widgetGetStyleContext $ commandEntry . uiContext $ ctx hasErrorClass <- styleContextHasClass styleCtx "error" hasErrorClass `shouldBe` False it "applies error style class if the command is unknown" $ do ctx <- loadDefaultContext let entry = commandEntry . uiContext $ ctx entrySetText entry "qweqwe" styleCtx <- widgetGetStyleContext entry flushEvents hasErrorClass <- styleContextHasClass styleCtx "error" hasErrorClass `shouldBe` True it "removes error style on empty command" $ do ctx <- loadDefaultContext let entry = commandEntry . uiContext $ ctx entrySetText entry "not empty" styleCtx <- widgetGetStyleContext entry styleContextAddClass styleCtx "error" entrySetText entry "" flushEvents hasErrorClass <- styleContextHasClass styleCtx "error" hasErrorClass `shouldBe` False it "removes error style on known command" $ do (ctx, entry, entryApi, _) <- loadDefaultGuiWithMockedCommand styleCtx <- widgetGetStyleContext entry styleContextAddClass styleCtx "error" runCtxActions ctx $ invokePreview entry entryApi "cmd->asd" hasErrorClass <- styleContextHasClass styleCtx "error" hasErrorClass `shouldBe` False it "invokes preview on the command" $ do (ctx, entry, entryApi, (_, previewReader, previewResetReader)) <- loadDefaultGuiWithMockedCommand runCtxActions ctx $ invokePreview entry entryApi "cmd->asd" previewText <- previewReader previewResetText <- previewResetReader previewText `shouldBe` Just "asd" previewResetText `shouldBe` Nothing it "resets preview before next preview" $ do (ctx, entry, entryApi, (_, previewReader, previewResetReader)) <- loadDefaultGuiWithMockedCommand runCtxActions ctx $ invokePreview entry entryApi "cmd->asd" runCtxActions ctx $ invokePreview entry entryApi "cmd->as" previewText <- previewReader previewResetText <- previewResetReader previewText `shouldBe` Just "as" previewResetText `shouldBe` Just "called" it "executes the command" $ do (ctx, entry, entryApi, (executeReader, _, _)) <- loadDefaultGuiWithMockedCommand runCtxActions ctx $ invokeCommand entry entryApi "cmd->asd" executed <- executeReader executed `shouldBe` Just "asd" it "clears command entry when executing a command" $ do (ctx, entry, entryApi, _) <- loadDefaultGuiWithMockedCommand runCtxActions ctx $ invokeCommand entry entryApi "cmd->asd" text <- entryGetText entry text `shouldBe` "" it "resets the last preview command before executing a command" $ do (ctx, entry, entryApi, (executeReader, _, previewResetReader)) <- loadDefaultGuiWithMockedCommand runCtxActions ctx $ invokeCommand entry entryApi "cmd->asd" executed <- executeReader previewResetText <- previewResetReader executed `shouldBe` Just "asd" previewResetText `shouldBe` Just "called" invokePreview :: Entry -> EntryApi -> String -> App () invokePreview entry api text = do liftIO $ entrySetText entry text fst api invokeCommand :: Entry -> EntryApi -> String -> App () invokeCommand entry api text = do invokePreview entry api text _ <- snd api return() loadDefaultGuiWithMockedCommand :: IO (Context, Entry, EntryApi, CommandHandlerReaders) loadDefaultGuiWithMockedCommand = do defaultCtx <- loadDefaultContext (matcher, readHandledCommands) <- mockedMatcher "cmd->" let ctx = defaultCtx{baseCommands = matcher} entry <- entryNew ret <- runApp ctx (newCommandEntryDetached entry) return (ctx, entry, ret, readHandledCommands) mockedMatcher :: String -> IO (CommandMatcher, CommandHandlerReaders) mockedMatcher prefix = do (handler, readHandledCommands) <- recordingHandler let matcher = createMatcherForPrefix prefix handler return (matcher, readHandledCommands) recordingHandler :: IO (String -> CommandHandler, CommandHandlerReaders) recordingHandler = do cmd <- newIORef Nothing previewCmd <- newIORef Nothing previewResetCmd <- newIORef Nothing return ( \params -> CommandHandler (Just $ PreviewCommandHandler (liftIO $ writeIORef previewCmd $ Just params) (liftIO $ writeIORef previewResetCmd $ Just "called")) (liftIO $ writeIORef cmd $ Just params), ( readIORef cmd, readIORef previewCmd, readIORef previewResetCmd ) )
svalaskevicius/hob
test/Hob/Ui/CommandEntrySpec.hs
gpl-3.0
5,477
0
17
1,291
1,407
689
718
122
1
module Parser ( module Parser.Ast, module Parser.Utils, parse ) where import Data.Maybe import Parser.Ast import Parser.Utils import Lexer -- Define the top-level `parse` function class Parsable p where parse :: [p] -> Ast instance Parsable Char where parse s = parse $ getTokens s instance Parsable Token where parse t = case parseE t of Parser (astRoot, []) -> astRoot Parser (_, tokens) -> error $ "Expected EOF but found tokens: " ++ (show tokens) -- Parsers for each grammar component parseE :: [Token] -> ParserResult -- E -> 'let' D 'in' E parseE (TokenKeyword "let" : tokens) = do (aa, ta) <- parseD tokens tb <- consume ta $ TokenKeyword "in" (ac, tc) <- parseE tb return (AstLet aa ac, tc) -- E -> 'fn' Vb+ '.' E parseE (TokenKeyword "fn" : tokens) = do (aa, ta) <- parseVb tokens -- There should be at least one Vb (ab, tb) <- many ta parseVb (\t -> head t == TokenOperator ".") tc <- advance tb (ad, td) <- parseE tc return (AstLambda (aa : ab) ad, td) parseE t = parseEw t -- Ew -> T 'where' Dr -- -> T parseEw :: [Token] -> ParserResult parseEw tokens = parseT tokens >>= \(aa, ta) -> case ta of (TokenKeyword "where" : tb) -> do (ac, tc) <- parseDr tb return (AstWhere aa ac, tc) _ -> return (aa, ta) -- T -> Ta ( ',' Ta )+ -- -> Ta parseT :: [Token] -> ParserResult parseT tokens = do (aa, ta) <- manySep tokens parseTa (TokenPunction ",") return ( if length aa > 1 then (AstTau aa, ta) else (head aa, ta) ) -- Ta -> Ta 'aug' Tc -- -> Tc parseTa :: [Token] -> ParserResult parseTa tokens = leftRecursive tokens parseTc (TokenKeyword "aug") AstAug -- Tc -> B '->' Tc '|' Tc -- -> B parseTc :: [Token] -> ParserResult parseTc tokens = do parseB tokens >>= \(aa, ta) -> case ta of (TokenOperator "->" : tb) -> do (ac, tc) <- parseTc tb td <- consume tc $ TokenOperator "|" (ae, te) <- parseTc td return (AstCond aa ac ae, te) _ -> return (aa, ta) -- B -> B 'or' Bt -- -> Bt parseB :: [Token] -> ParserResult parseB tokens = leftRecursive tokens parseBt (TokenKeyword "or") AstOr -- Bt -> Bt '&' Bs -- -> Bs parseBt :: [Token] -> ParserResult parseBt tokens = leftRecursive tokens parseBs (TokenOperator "&") AstAmp -- Bs -> 'not' Bp parseBs :: [Token] -> ParserResult parseBs (TokenKeyword "not" : tokens) = do (aa, ta) <- parseBp tokens return (AstNot aa, ta) -- Bs -> Bp parseBs tokens = parseBp tokens -- Bp -> A ( 'gr' | '>' ) A -- -> A ( 'ge' | '>=' ) A -- -> A ( 'ls' | '<' ) A -- -> A ( 'le' | '<=' ) A -- -> A 'eq' A -- -> A 'ne' A -- -> A parseBp :: [Token] -> ParserResult parseBp tokens = parseA tokens >>= \(aa, ta) -> let combTypeMaybe = if length ta == 0 then Nothing else case head ta of -- My eyes are starting to hurt... TokenKeyword "gr" -> Just AstGr TokenOperator ">" -> Just AstGr TokenKeyword "ge" -> Just AstGe TokenOperator ">=" -> Just AstGe TokenKeyword "ls" -> Just AstLs TokenOperator "<" -> Just AstLs TokenKeyword "le" -> Just AstLe TokenOperator "<=" -> Just AstLe TokenKeyword "eq" -> Just AstEq TokenKeyword "ne" -> Just AstNe _ -> Nothing in case combTypeMaybe of Just combType -> do tb <- advance ta (ac, tc) <- parseA tb return (combType aa ac, tc) Nothing -> return (aa, ta) -- A -> A '+' At -- -> A '-' At -- -> '+' At -- -> '-' At -- -> At -- There is actually (In my opinion) a bug in the grammar spec here, which we -- replicate for compatibility. `-5 * 5` is valid grammar, but `5 * -5` is not. parseA :: [Token] -> ParserResult parseA tokens = do (aa, ta) <- parseAtNeg tokens parseAPartial aa ta where parseAPartial leftAst partialTokens = case partialTokens of (TokenOperator "+" : ta) -> do (ab, tb) <- parseAtNeg ta parseAPartial (AstPlus leftAst ab) tb (TokenOperator "-" : ta) -> do (ab, tb) <- parseAtNeg ta parseAPartial (AstMinus leftAst ab) tb _ -> return (leftAst, partialTokens) -- handle possible '+' or '-' uniary operators parseAtNeg (TokenOperator "-" : partialTokens) = do (aa, ta) <- parseAt partialTokens return (AstNeg aa, ta) parseAtNeg (TokenOperator "+" : partialTokens) = parseAt partialTokens parseAtNeg partialTokens = parseAt partialTokens -- At -> At '*' Af -- -> At '/' Af -- -> Af parseAt :: [Token] -> ParserResult parseAt tokens = do (aa, ta) <- parseAf tokens parseAtPartial aa ta where parseAtPartial leftAst partialTokens = case partialTokens of (TokenOperator "*" : ta) -> do (ab, tb) <- parseAf ta parseAtPartial (AstMult leftAst ab) tb (TokenOperator "/" : ta) -> do (ab, tb) <- parseAf ta parseAtPartial (AstDiv leftAst ab) tb _ -> return (leftAst, partialTokens) -- Af -> Ap '**' Af -- -> Ap parseAf :: [Token] -> ParserResult parseAf tokens = parseAp tokens >>= \(aa, ta) -> case ta of (TokenOperator "**" : tb) -> do (ac, tc) <- parseAf tb return (AstPow aa ac, tc) _ -> return (aa, ta) -- Ap -> Ap '@' '<IDENTIFIER>' R -- -> R parseAp :: [Token] -> ParserResult parseAp tokens = do (aa, ta) <- parseR tokens parseApPartial aa ta where parseApPartial leftAst partialTokens = case partialTokens of (TokenOperator "@" : TokenIdentifier functionName: ta) -> do (ab, tb) <- parseR ta parseApPartial (AstInfix leftAst (AstIdentifier functionName) ab) tb _ -> return (leftAst, partialTokens) -- R -> R Rn -- -> Rn parseR :: [Token] -> ParserResult parseR tokens = do (aa, ta) <- parseRn tokens -- There should be at least one Rn -- parseRnMaybe gets implicitly called twice for each Rn. I hope ghc -- optimizes this... (ab, tb) <- many ta parseRn (\t -> isNothing $ parseRnMaybe t) return (buildTree (aa : ab), tb) where buildTree subList = if length subList == 1 then head subList else AstGamma (buildTree $ init subList) (last subList) -- Rn -> '<IDENTIFIER>' -- -> '<INTEGER>' -- -> '<STRING>' -- -> 'true' -- -> 'false' -- -> 'nil' -- -> '(' E ')' -- -> 'dummy' parseRnMaybe :: [Token] -> Maybe ParserResult parseRnMaybe (TokenKeyword "true" : tokens) = Just $ return (AstTrue, tokens) parseRnMaybe (TokenKeyword "false" : tokens) = Just $ return (AstFalse, tokens) parseRnMaybe (TokenKeyword "nil" : tokens) = Just $ return (AstNil, tokens) parseRnMaybe (TokenKeyword "dummy" : tokens) = Just $ return (AstDummy, tokens) parseRnMaybe (TokenIdentifier idName : tokens) = Just $ return (AstIdentifier idName, tokens) parseRnMaybe (TokenInteger intValue : tokens) = Just $ return (AstInteger intValue, tokens) parseRnMaybe (TokenString strValue : tokens) = Just $ return (AstString strValue, tokens) parseRnMaybe (TokenPunction "(" : tokens) = Just $ do (aa, ta) <- parseE tokens tb <- consume ta $ TokenPunction ")" return (aa, tb) parseRnMaybe _ = Nothing parseRn :: [Token] -> ParserResult parseRn tokens = case parseRnMaybe tokens of Just r -> r Nothing -> notFound ("true, false, nil, dummy, integer, identifier, string or " ++ "parenthesized expression") tokens -- D -> Da 'within' D -- -> Da parseD :: [Token] -> ParserResult parseD tokens = rightRecursive tokens parseDa (TokenKeyword "within") AstWithin -- Da -> Dr ( 'and' Dr )+ -- -> Dr parseDa :: [Token] -> ParserResult parseDa tokens = do (aa, ta) <- manySep tokens parseDr (TokenKeyword "and") return (if length aa > 1 then AstAnd aa else head aa, ta) -- Dr -> 'rec' Db -- -> Db parseDr :: [Token] -> ParserResult parseDr (TokenKeyword "rec" : tokens) = do (aa, ta) <- parseDb tokens return (AstRec aa, ta) parseDr tokens = parseDb tokens -- Db -> Vl '=' E -- -> '<IDENTIFIER>' Vb+ '=' E -- -> '(' D ')' -- -- This grammar is potentially ambiguous. The reference parser actually parses -- this *wrong*. The input `let a, b, c d e f = dummy in dummy` should fail, as -- you cannot have `Db -> Vl Vb+ = E`. The reference parser accepts it as such. -- -- We can solve this by performing a small non-LL(1) lookahead. We should look -- at the first *two* tokens in the stream (it should always exist): -- id '=' -> Parse with first rule -- id ',' -> Parse with first rule -- id '(' -> Parse with second rule -- id id -> Parse with second rule -- '(' _ -> Parse with third rule parseDb :: [Token] -> ParserResult parseDb (ta:tb:tc) = case (ta, tb) of (TokenIdentifier _, TokenOperator "=") -> parseDbFirst $ ta:tb:tc (TokenIdentifier _, TokenPunction ",") -> parseDbFirst $ ta:tb:tc (TokenIdentifier _, TokenPunction "(") -> parseDbSecond $ ta:tb:tc (TokenIdentifier _, TokenIdentifier _ ) -> parseDbSecond $ ta:tb:tc (TokenPunction "(", _ ) -> parseDbThird $ ta:tb:tc _ -> parseDb $ [ta] -- error parseDb tokens = notFound ("variable list, function form, or parenthesized " ++ "expression") tokens parseDbFirst :: [Token] -> ParserResult parseDbFirst tokens = do (aa, ta) <- parseVl tokens tb <- consume ta $ TokenOperator "=" (ac, tc) <- parseE tb return (AstDef aa ac, tc) parseDbSecond :: [Token] -> ParserResult parseDbSecond (TokenIdentifier idName : tokens) = do (aa, ta) <- many tokens parseVb (\t -> head t == TokenOperator "=") tb <- consume ta $ TokenOperator "=" (ac, tc) <- parseE tb return (AstFcnForm (AstIdentifier idName) aa ac, tc) parseDbSecond tokens = notFound "identifier" tokens parseDbThird :: [Token] -> ParserResult parseDbThird (TokenPunction "(" : tokens) = do (aa, ta) <- parseD tokens tb <- consume ta $ TokenPunction ")" return (aa, tb) parseDbThird tokens = notFound "open parenthesis" tokens -- Vb -> '<IDENTIFIER>' -- -> '(' Vl ')' -- -> '(' ')' parseVb :: [Token] -> ParserResult parseVb (TokenPunction "(" : TokenPunction ")" : tokens) = return (AstEmpty, tokens) parseVb (TokenPunction "(" : tokens) = do (aa, ta) <- parseVl tokens tb <- consume ta $ TokenPunction ")" return (aa, tb) parseVb (TokenIdentifier idName : tokens) = return (AstIdentifier idName, tokens) parseVb tokens = notFound "open parenthesis or identifier" tokens -- Vl -> '<IDENTIFIER>' ( ',' '<IDENTIFIER>' )+ -- -> '<IDENTIFIER>' -- N.B. I didn't like how the grammar words this definition, so I reworded it parseVl :: [Token] -> ParserResult parseVl tokens = do (aa, ta) <- manySep tokens parseIdentifier (TokenPunction ",") return (if length aa > 1 then AstComma aa else head aa, ta) where parseIdentifier (TokenIdentifier idName : t) = return (AstIdentifier idName, t) parseIdentifier t = notFound "identifier" t
bgw/hs-rpal
src/Parser.hs
gpl-3.0
11,824
0
16
3,609
3,422
1,750
1,672
233
13
import Network.HaskellNet.IMAP.SSL import System.Environment (getArgs) import System.Directory (getHomeDirectory) main = connectIMAP' >>= authenticate' >>= getUnreadBoxes >>= printCounts isVerbose = getArgs >>= \a -> return (not (null a) && head a == "-v") getAuth = getHomeDirectory >>= \hd -> readFile (hd ++ "/.mailauth") >>= split' split' x = case x of [] -> fail "Failed to parse config"; otherwise -> return (words x) connectIMAP' = getAuth >>= connectIMAPSSL . head authenticate' c = getAuth >>= \(_:u:p:_) -> authenticate c PLAIN u p >> return c getUnreadBoxes c = lsub c >>= mapM (filterUnseen c . snd) . filterSelectable filterUnseen c b = select c b >> search c [NOTs (FLAG Seen)] >>= \a -> return (b, length a) filterSelectable = filter (notElem Noselect . fst) printCounts x = isVerbose >>= \isV -> if isV then printVerbose x else print . sum $ map snd x printVerbose = mapM_ (\x -> putStrLn $ fst x ++ ": " ++ show (snd x)) . filter (\x -> snd x /= 0)
Reyu/MailCheck
Split.hs
gpl-3.0
967
0
13
169
423
215
208
14
2
-- this is from ghc/syslib-ghc originally, module CharSeq ( CSeq, cNil, cAppend, cIndent, cNL, cStr, cPStr, cCh, cInt, cLength, cShows, cShow ) where cShow :: CSeq -> [Char] -- not used in GHC cShows :: CSeq -> ShowS cLength :: CSeq -> Int cNil :: CSeq cAppend :: CSeq -> CSeq -> CSeq cIndent :: Int -> CSeq -> CSeq cNL :: CSeq cStr :: [Char] -> CSeq cPStr :: String -> CSeq cCh :: Char -> CSeq cInt :: Int -> CSeq data CSeq = CNil | CAppend CSeq CSeq | CIndent Int CSeq | CNewline -- Move to start of next line, unless we're -- already at the start of a line. | CStr [Char] | CCh Char | CInt Int -- equiv to "CStr (show the_int)" cNil = CNil -- cAppend CNil cs2 = cs2 -- cAppend cs1 CNil = cs1 cAppend cs1 cs2 = CAppend cs1 cs2 cIndent n cs = CIndent n cs cNL = CNewline cStr = CStr cCh = CCh cInt = CInt cPStr = CStr cShow seq = flatten (0) True seq [] cShows seq rest = cShow seq ++ rest cLength seq = length (cShow seq) -- *not* the best way to do this! data WorkItem = WI Int CSeq -- indentation, and sequence flatten :: Int -- Indentation -> Bool -- True => just had a newline -> CSeq -- Current seq to flatten -> [WorkItem] -- Work list with indentation -> String flatten n nlp CNil seqs = flattenS nlp seqs flatten n nlp (CAppend seq1 seq2) seqs = flatten n nlp seq1 ((WI n seq2) : seqs) flatten n nlp (CIndent (n2) seq) seqs = flatten (n2 + n) nlp seq seqs flatten n False CNewline seqs = '\n' : flattenS True seqs flatten n True CNewline seqs = flattenS True seqs -- Already at start of line flatten n False (CStr s) seqs = s ++ flattenS False seqs flatten n False (CCh c) seqs = c : flattenS False seqs flatten n False (CInt i) seqs = show i ++ flattenS False seqs flatten n True (CStr s) seqs = mkIndent n (s ++ flattenS False seqs) flatten n True (CCh c) seqs = mkIndent n (c : flattenS False seqs) flatten n True (CInt i) seqs = mkIndent n (show i ++ flattenS False seqs) flattenS :: Bool -> [WorkItem] -> String flattenS nlp [] = "" flattenS nlp ((WI col seq):seqs) = flatten col nlp seq seqs mkIndent :: Int -> String -> String mkIndent (0) s = s mkIndent n s = if (n >= (8)) then '\t' : mkIndent (n - (8)) s else ' ' : mkIndent (n - (1)) s -- Hmm.. a little Unix-y.
jwaldmann/rx
src/CharSeq.hs
gpl-3.0
2,310
56
10
582
917
486
431
62
2
module Test.StandOff.TestSetup where import Data.Map as Map hiding (drop) import Data.UUID.Types (UUID, fromString, toString) import StandOff.AnnotationTypeDefs as A import StandOff.DomTypeDefs as X import StandOff.LineOffsets as L pos :: Int -> L.Position pos p = L.Position {L.pos_offset=p, L.pos_line=1, L.pos_column=1} elm :: String -> Int -> Int -> [XML] -> XML elm n s e c = (Element { name = n , X.attributes = [] , startOpenTag = pos s , endOpenTag = pos (s + openTagLength - 1) , startCloseTag = pos (e - openTagLength) , endCloseTag = pos e , content = c }) where openTagLength = 2 + (length n) -- For easy setup of (uu)ids for unit tests: testUUID = "00000000-0000-0000-0000-000000000000" mkTestUUID :: String -> UUID mkTestUUID start = case fromString strUuid of Nothing -> error ("Invalid UUID: " ++ strUuid) (Just u) -> u where strUuid = start ++ (drop (length start) testUUID) mRng :: String -> String -> String -> Int -> Int -> A.Annotation mRng rid mid typ s e = (A.MarkupRange { A.rangeId = Just $ mkTestUUID rid , A.elementId = mkTestUUID mid , A.markupType = typ , A.startOffset = s , A.endOffset = e , A.text = Just "" , A.attributes = Map.empty })
lueck/standoff-tools
testsuite/Test/StandOff/TestSetup.hs
gpl-3.0
1,556
0
11
588
445
253
192
32
2
{-# LANGUAGE ExistentialQuantification #-} module Hastistics.Types where import Text.Printf (printf) data HSValue = HSString String | HSInt Int | HSInteger Integer | HSDouble Double | None deriving(Eq) instance Ord HSValue where (<=) (HSString a) (HSString b) = a <= b (<=) (HSString a) (HSInt b) = a <= show b (<=) (HSString a) (HSInteger b) = a <= show b (<=) (HSString a) (HSDouble b) = a <= show b (<=) (HSInt a) (HSInt b) = a <= b (<=) (HSInt a) (HSString b) = show a <= b (<=) (HSInt a) (HSInteger b) = (fromIntegral a) <= b (<=) (HSInt a) (HSDouble b) = (fromIntegral a) <= b (<=) (HSInteger a) (HSInteger b) = a <= b (<=) (HSInteger a) (HSString b) = (show a) <= b (<=) (HSInteger a) (HSInt b) = a <= (fromIntegral b) (<=) (HSInteger a) (HSDouble b) = (fromIntegral a) <= b (<=) (HSDouble a) (HSDouble b) = a <= b (<=) (HSDouble a) (HSString b) = (show a) <= b (<=) (HSDouble a) (HSInteger b) = a <= (fromIntegral b) (<=) (HSDouble a) (HSInt b) = a <= (fromIntegral b) (<=) None None = True (<=) None _ = True (<=) _ None = False instance Show HSValue where show (HSString s) = s show (HSInt i) = show i show (HSInteger i) = show i show (HSDouble d) = printf "%f" d show None = "None" type Key = String type ValueParser = (String -> HSValue) {-| Cast String to HSString -} toHSString :: ValueParser toHSString = HSString {-| Cast String to HSInt -} toHSInt :: ValueParser toHSInt = HSInt . read {-| Cast String to HSInteger -} toHSInteger :: ValueParser toHSInteger = HSInteger . read {-| Cast String to HSDouble -} toHSDouble :: ValueParser toHSDouble = HSDouble . read {-| Cast HSString to String -} fromHSStringToString :: HSValue -> String fromHSStringToString (HSString s) = s fromHSStringToString _ = "" {-| Cast HSInt to Int -} fromHSIntToInt :: HSValue -> Int fromHSIntToInt (HSInt i) = i fromHSIntToInt _ = 0 {-| Cast HSInteger to Integer -} fromHSIntegerToInteger :: HSValue -> Integer fromHSIntegerToInteger (HSInteger i) = i fromHSIntegerToInteger _ = 0 {-| Cast HSDouble to Double -} fromHSDoubleToDouble :: HSValue -> Double fromHSDoubleToDouble (HSDouble d) = d fromHSDoubleToDouble _ = 0 {-| Definitions for arithmetic operations on HSValues -} (+) :: HSValue -> HSValue -> HSValue (+) (HSDouble da) (HSDouble db) = HSDouble (da Prelude.+ db) (+) (HSDouble da) (HSInt ib) = HSDouble (da Prelude.+ (fromIntegral ib)) (+) (HSDouble da) (HSInteger ib) = HSDouble (da Prelude.+ (fromIntegral ib)) (+) (HSDouble da) (HSString sb) = HSString ((show da) Prelude.++ sb) (+) (HSInt ia) (HSDouble db) = HSDouble ((fromIntegral ia) Prelude.+ db) (+) (HSInt ia) (HSInt ib) = HSInt (ia Prelude.+ ib) (+) (HSInt ia) (HSInteger ib) = HSInteger ((fromIntegral ia) Prelude.+ ib) (+) (HSInt ia) (HSString sb) = HSString ((show ia) Prelude.++ sb) (+) (HSInteger ia) (HSDouble db) = HSDouble ((fromIntegral ia) Prelude.+ db) (+) (HSInteger ia) (HSInt ib) = HSInteger (ia Prelude.+ (fromIntegral ib)) (+) (HSInteger ia) (HSInteger ib) = HSInteger (ia Prelude.+ ib) (+) (HSInteger ia) (HSString sb) = HSString ((show ia) Prelude.++ sb) (+) (HSString sa) (HSDouble db) = HSString (sa Prelude.++ (show db)) (+) (HSString sa) (HSInt ib) = HSString (sa Prelude.++ (show ib)) (+) (HSString sa) (HSInteger ib) = HSString (sa Prelude.++ (show ib)) (+) (HSString sa) (HSString sb) = HSString (sa Prelude.++ sb) (+) _ _ = None (-) :: HSValue -> HSValue -> HSValue (-) (HSDouble da) (HSDouble db) = HSDouble (da Prelude.- db) (-) (HSDouble da) (HSInt ib) = HSDouble (da Prelude.- (fromIntegral ib)) (-) (HSDouble da) (HSInteger ib) = HSDouble (da Prelude.- (fromIntegral ib)) (-) (HSInt ia) (HSDouble db) = HSDouble ((fromIntegral ia) Prelude.- db) (-) (HSInt ia) (HSInt ib) = HSInt (ia Prelude.- ib) (-) (HSInt ia) (HSInteger ib) = HSInteger ((fromIntegral ia) Prelude.- ib) (-) (HSInteger ia) (HSDouble db) = HSDouble ((fromIntegral ia) Prelude.- db) (-) (HSInteger ia) (HSInt ib) = HSInteger (ia Prelude.- (fromIntegral ib)) (-) (HSInteger ia) (HSInteger ib) = HSInteger (ia Prelude.- ib) (-) _ _ = None (/) :: HSValue -> HSValue -> HSValue (/) _ (HSDouble 0) = None (/) _ (HSInt 0) = None (/) _ (HSInteger 0) = None (/) (HSDouble 0) _ = HSDouble 0 (/) (HSInt 0) _ = HSInt 0 (/) (HSInteger 0) _ = HSInteger 0 (/) (HSDouble da) (HSDouble db) = HSDouble (da Prelude./ db) (/) (HSDouble da) (HSInt ib) = HSDouble (da Prelude./ (fromIntegral ib)) (/) (HSDouble da) (HSInteger ib) = HSDouble (da Prelude./ (fromIntegral ib)) (/) (HSInt ia) (HSDouble db) = HSDouble ((fromIntegral ia) Prelude./ db) (/) (HSInt ia) (HSInt ib) = HSDouble ((fromIntegral ia) Prelude./ (fromIntegral ib)) (/) (HSInt ia) (HSInteger ib) = HSDouble ((fromIntegral ia) Prelude./ (fromIntegral ib)) (/) (HSInteger ia) (HSDouble db) = HSDouble ((fromIntegral ia) Prelude./ db) (/) (HSInteger ia) (HSInt ib) = HSDouble ((fromIntegral ia) Prelude./ (fromIntegral ib)) (/) (HSInteger ia) (HSInteger ib) = HSDouble ((fromIntegral ia) Prelude./ (fromIntegral ib)) (/) _ _ = None (*) :: HSValue -> HSValue -> HSValue (*) _ (HSDouble 0) = HSDouble 0 (*) _ (HSInt 0) = HSInt 0 (*) _ (HSInteger 0) = HSInteger 0 (*) (HSDouble 0) _ = HSDouble 0 (*) (HSInt 0) _ = HSInt 0 (*) (HSInteger 0) _ = HSInteger 0 (*) (HSDouble da) (HSDouble db) = HSDouble (da Prelude.* db) (*) (HSDouble da) (HSInt ib) = HSDouble (da Prelude.* (fromIntegral ib)) (*) (HSDouble da) (HSInteger ib) = HSDouble (da Prelude.* (fromIntegral ib)) (*) (HSInt ia) (HSDouble db) = HSDouble ((fromIntegral ia) Prelude.* db) (*) (HSInt ia) (HSInt ib) = HSDouble ((fromIntegral ia) Prelude.* (fromIntegral ib)) (*) (HSInt ia) (HSInteger ib) = HSDouble ((fromIntegral ia) Prelude.* (fromIntegral ib)) (*) (HSInteger ia) (HSDouble db) = HSDouble ((fromIntegral ia) Prelude.* db) (*) (HSInteger ia) (HSInt ib) = HSDouble ((fromIntegral ia) Prelude.* (fromIntegral ib)) (*) (HSInteger ia) (HSInteger ib) = HSDouble ((fromIntegral ia) Prelude.* (fromIntegral ib)) (*) _ _ = None class (Show f) => HSField f where val :: f -> HSValue meta :: f -> String meta _ = "" update :: f -> HSRow -> f update fi _ = fi {-| get the value of the HSField and cast it to String -} showField :: (HSField a) => a -> String showField = show . val data HSFieldHolder = forall a. HSField a => HSFieldHolder a instance Show HSFieldHolder where show (HSFieldHolder f) = show f pack :: HSField a => a -> HSFieldHolder pack = HSFieldHolder {- |Row in a table. Consists of a list of columns -} data HSRow = HSValueRow [Key] [HSFieldHolder] instance Show HSRow where show = showRow . valuesOf rowFields :: HSRow -> [HSFieldHolder] rowFields (HSValueRow _ f) = f rowHeaders :: HSRow -> [Key] rowHeaders (HSValueRow hs _ ) = hs {- |Get the values out of a HSRow. -} valuesOf :: HSRow -> [HSValue] valuesOf (HSValueRow _ vs) = [val v | (HSFieldHolder v) <- vs] fieldValueOf :: String -> HSRow -> HSValue fieldValueOf _ (HSValueRow _ []) = None fieldValueOf _ (HSValueRow [] _) = None fieldValueOf col (HSValueRow (h:hs) ((HSFieldHolder v):vs)) | h == col = val v | otherwise = fieldValueOf col (HSValueRow hs vs) {- |Type class defining the interface to a Table implementation. Use this type class if you want to define your own data sources for the Hastistics framework. -} class (Show t) => HSTable t where headersOf :: t -> [Key] dataOf :: t -> [HSRow] lookup :: Key -> HSValue -> t -> [HSRow] lookup k v t = [r | r <- (dataOf t), (fieldValueOf k r) == v] colWidth :: Int colWidth = 20 showBorder :: (Show a) => [a] -> String showBorder [] = "+" showBorder (_:ks) = "+" ++ take (colWidth Prelude.+ 2) (repeat '-') ++ showBorder ks showHeader :: (Show a) => [a] -> String showHeader ks = (showBorder ks) ++ "\n" ++ (showRow ks) ++ "\n" ++ (showBorder ks) showRow :: (Show a) => [a] -> String showRow [] = "|" showRow (k:ks) = "| " ++ v ++ space ++ " " ++ showRow ks where v = take colWidth (show k) space = take (colWidth Prelude.- (length v)) (repeat ' ') showRows :: [HSRow] -> String showRows [] = "" showRows (r:rs) = showRow (valuesOf r) ++ "\n" ++ showRows rs showTable :: HSTable t => t -> String showTable t | length (headersOf t) == 0 = "" | otherwise = showHeader (headersOf t) ++ "\n" ++ showRows (dataOf t) ++ showBorder (headersOf t)
fluescher/hastistics
src/Hastistics/Types.hs
lgpl-3.0
9,594
2
11
2,882
3,991
2,106
1,885
176
1
module Main where import Data.Maybe (fromJust) import Data.List (findIndex) fib :: [Integer] fib = 1 : 1 : zipWith (+) fib (tail fib) main :: IO () main = print . (+ 1) . fromJust . findIndex ((>= 1000) . length . show) $ fib
AlexLusitania/ProjectEuler
025-fibonacci-number/Main.hs
unlicense
228
0
11
47
113
64
49
7
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} -- Type definitions to avoid circular imports. module Language.K3.Codegen.CPP.Materialization.Hints where import Control.DeepSeq import Data.Binary import Data.Hashable import Data.Serialize import Data.Typeable import GHC.Generics (Generic) data Method = ConstReferenced | Referenced | Moved | Copied | Forwarded deriving (Eq, Ord, Read, Show, Typeable, Generic) defaultMethod :: Method defaultMethod = Copied data Direction = In | Ex deriving (Eq, Ord, Read, Show, Typeable, Generic) {- Typeclass Instances -} instance NFData Method instance NFData Direction instance Binary Method instance Binary Direction instance Serialize Method instance Serialize Direction instance Hashable Method instance Hashable Direction
DaMSL/K3
src/Language/K3/Codegen/CPP/Materialization/Hints.hs
apache-2.0
805
0
6
117
198
109
89
27
1
module Str.String where import Prelude hiding (null) import qualified Prelude as P type Str = String null :: Str -> Bool null = P.null singleton :: Char -> Str singleton c = [c] splits :: Str -> [(Str, Str)] splits [] = [([], [])] splits (c:cs) = ([], c:cs):[(c:s1,s2) | (s1,s2) <- splits cs] parts :: Str -> [[Str]] parts [] = [[]] parts [c] = [[[c]]] parts (c:cs) = concat [[(c:p):ps, [c]:p:ps] | p:ps <- parts cs]
DanielG/cabal-helper
tests/bkpregex/str-impls/Str/String.hs
apache-2.0
423
0
10
84
279
160
119
15
1
module IndentInBracesAgain where f = r{ render = do make return f }
Atsky/haskell-idea-plugin
data/indentTests/IndentInBracesAgain.hs
apache-2.0
87
0
10
32
27
14
13
3
1
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings ( widgetFile , PersistConfig , staticRoot , staticDir , Extra (..) , parseExtra ) where import Prelude import Text.Shakespeare.Text (st) import Language.Haskell.TH.Syntax import Database.Persist.Sqlite (SqliteConf) import Yesod.Default.Config import qualified Yesod.Default.Util import Data.Text (Text) import Data.Yaml import Control.Applicative import Settings.Development import Network.HTTP.Types (Ascii) -- | Which Persistent backend this site is using. type PersistConfig = SqliteConf -- Static setting below. Changing these requires a recompile -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticDir :: FilePath staticDir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticRoot :: AppConfig DefaultEnv x -> Text staticRoot conf = [st|#{appRoot conf}/static|] -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = if development then Yesod.Default.Util.widgetFileReload else Yesod.Default.Util.widgetFileNoReload data Extra = Extra { extraCopyright :: Text , extraAnalytics :: Maybe Text -- ^ Google Analytics , extraFacebookAppName :: Ascii , extraFacebookAppId :: Integer , extraFacebookSecret :: Ascii } deriving Show parseExtra :: DefaultEnv -> Object -> Parser Extra parseExtra _ o = Extra <$> o .: "copyright" <*> o .:? "analytics" <*> o .: "facebookAppName" <*> o .: "facebookAppId" <*> o .: "facebookSecret"
tmiw/4peas
Settings.hs
bsd-2-clause
2,645
0
14
490
320
202
118
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QGraphicsSceneHelpEvent.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QGraphicsSceneHelpEvent ( qGraphicsSceneHelpEvent_delete ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.QEvent import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QscenePos (QGraphicsSceneHelpEvent a) (()) where scenePos x0 () = withPointFResult $ \cpointf_ret_x cpointf_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_scenePos_qth cobj_x0 cpointf_ret_x cpointf_ret_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_scenePos_qth" qtc_QGraphicsSceneHelpEvent_scenePos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr CDouble -> Ptr CDouble -> IO () instance QqscenePos (QGraphicsSceneHelpEvent a) (()) where qscenePos x0 () = withQPointFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_scenePos cobj_x0 foreign import ccall "qtc_QGraphicsSceneHelpEvent_scenePos" qtc_QGraphicsSceneHelpEvent_scenePos :: Ptr (TQGraphicsSceneHelpEvent a) -> IO (Ptr (TQPointF ())) instance QscreenPos (QGraphicsSceneHelpEvent a) (()) where screenPos x0 () = withPointResult $ \cpoint_ret_x cpoint_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_screenPos_qth cobj_x0 cpoint_ret_x cpoint_ret_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_screenPos_qth" qtc_QGraphicsSceneHelpEvent_screenPos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr CInt -> Ptr CInt -> IO () instance QqscreenPos (QGraphicsSceneHelpEvent a) (()) where qscreenPos x0 () = withQPointResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_screenPos cobj_x0 foreign import ccall "qtc_QGraphicsSceneHelpEvent_screenPos" qtc_QGraphicsSceneHelpEvent_screenPos :: Ptr (TQGraphicsSceneHelpEvent a) -> IO (Ptr (TQPoint ())) instance QsetScenePos (QGraphicsSceneHelpEvent a) ((PointF)) where setScenePos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QGraphicsSceneHelpEvent_setScenePos_qth cobj_x0 cpointf_x1_x cpointf_x1_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScenePos_qth" qtc_QGraphicsSceneHelpEvent_setScenePos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> CDouble -> CDouble -> IO () instance QqsetScenePos (QGraphicsSceneHelpEvent a) ((QPointF t1)) where qsetScenePos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsSceneHelpEvent_setScenePos cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScenePos" qtc_QGraphicsSceneHelpEvent_setScenePos :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr (TQPointF t1) -> IO () instance QsetScreenPos (QGraphicsSceneHelpEvent a) ((Point)) where setScreenPos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QGraphicsSceneHelpEvent_setScreenPos_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScreenPos_qth" qtc_QGraphicsSceneHelpEvent_setScreenPos_qth :: Ptr (TQGraphicsSceneHelpEvent a) -> CInt -> CInt -> IO () instance QqsetScreenPos (QGraphicsSceneHelpEvent a) ((QPoint t1)) where qsetScreenPos x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsSceneHelpEvent_setScreenPos cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsSceneHelpEvent_setScreenPos" qtc_QGraphicsSceneHelpEvent_setScreenPos :: Ptr (TQGraphicsSceneHelpEvent a) -> Ptr (TQPoint t1) -> IO () qGraphicsSceneHelpEvent_delete :: QGraphicsSceneHelpEvent a -> IO () qGraphicsSceneHelpEvent_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsSceneHelpEvent_delete cobj_x0 foreign import ccall "qtc_QGraphicsSceneHelpEvent_delete" qtc_QGraphicsSceneHelpEvent_delete :: Ptr (TQGraphicsSceneHelpEvent a) -> IO ()
keera-studios/hsQt
Qtc/Gui/QGraphicsSceneHelpEvent.hs
bsd-2-clause
4,319
0
12
568
987
509
478
-1
-1
{-# LANGUAGE TupleSections #-} {-| Auto-repair tool for Ganeti. -} {- Copyright (C) 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.Program.Harep ( main , arguments , options) where import Control.Exception (bracket) import Control.Monad import Data.Function import Data.List import Data.Maybe import Data.Ord import System.Time import qualified Data.Map as Map import Ganeti.BasicTypes import Ganeti.Common import Ganeti.Errors import Ganeti.Jobs import Ganeti.OpCodes import Ganeti.OpParams import Ganeti.Types import Ganeti.Utils import qualified Ganeti.Constants as C import qualified Ganeti.Luxi as L import qualified Ganeti.Path as Path import Ganeti.HTools.CLI import Ganeti.HTools.Loader import Ganeti.HTools.ExtLoader import Ganeti.HTools.Types import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Node as Node -- | Options list and functions. options :: IO [OptType] options = do luxi <- oLuxiSocket return [ luxi , oJobDelay ] arguments :: [ArgCompletion] arguments = [] data InstanceData = InstanceData { arInstance :: Instance.Instance , arState :: AutoRepairStatus , tagsToRemove :: [String] } deriving (Eq, Show) -- | Parse a tag into an 'AutoRepairData' record. -- -- @Nothing@ is returned if the tag is not an auto-repair tag, or if it's -- malformed. parseInitTag :: String -> Maybe AutoRepairData parseInitTag tag = let parsePending = do subtag <- chompPrefix C.autoRepairTagPending tag case sepSplit ':' subtag of [rtype, uuid, ts, jobs] -> makeArData rtype uuid ts jobs _ -> fail ("Invalid tag: " ++ show tag) parseResult = do subtag <- chompPrefix C.autoRepairTagResult tag case sepSplit ':' subtag of [rtype, uuid, ts, result, jobs] -> do arData <- makeArData rtype uuid ts jobs result' <- autoRepairResultFromRaw result return arData { arResult = Just result' } _ -> fail ("Invalid tag: " ++ show tag) makeArData rtype uuid ts jobs = do rtype' <- autoRepairTypeFromRaw rtype ts' <- tryRead "auto-repair time" ts jobs' <- mapM makeJobIdS $ sepSplit '+' jobs return AutoRepairData { arType = rtype' , arUuid = uuid , arTime = TOD ts' 0 , arJobs = jobs' , arResult = Nothing , arTag = tag } in parsePending `mplus` parseResult -- | Return the 'AutoRepairData' element of an 'AutoRepairStatus' type. getArData :: AutoRepairStatus -> Maybe AutoRepairData getArData status = case status of ArHealthy (Just d) -> Just d ArFailedRepair d -> Just d ArPendingRepair d -> Just d ArNeedsRepair d -> Just d _ -> Nothing -- | Return a short name for each auto-repair status. -- -- This is a more concise representation of the status, because the default -- "Show" formatting includes all the accompanying auto-repair data. arStateName :: AutoRepairStatus -> String arStateName status = case status of ArHealthy _ -> "Healthy" ArFailedRepair _ -> "Failure" ArPendingRepair _ -> "Pending repair" ArNeedsRepair _ -> "Needs repair" -- | Return a new list of tags to remove that includes @arTag@ if present. delCurTag :: InstanceData -> [String] delCurTag instData = let arData = getArData $ arState instData rmTags = tagsToRemove instData in case arData of Just d -> arTag d : rmTags Nothing -> rmTags -- | Set the initial auto-repair state of an instance from its auto-repair tags. -- -- The rules when there are multiple tags is: -- -- * the earliest failure result always wins -- -- * two or more pending repairs results in a fatal error -- -- * a pending result from id X and a success result from id Y result in error -- if Y is newer than X -- -- * if there are no pending repairs, the newest success result wins, -- otherwise the pending result is used. setInitialState :: Instance.Instance -> Result InstanceData setInitialState inst = let arData = mapMaybe parseInitTag $ Instance.allTags inst -- Group all the AutoRepairData records by id (i.e. by repair task), and -- present them from oldest to newest. arData' = sortBy (comparing arUuid) arData arGroups = groupBy ((==) `on` arUuid) arData' arGroups' = sortBy (comparing $ minimum . map arTime) arGroups in foldM arStatusCmp (InstanceData inst (ArHealthy Nothing) []) arGroups' -- | Update the initial status of an instance with new repair task tags. -- -- This function gets called once per repair group in an instance's tag, and it -- determines whether to set the status of the instance according to this new -- group, or to keep the existing state. See the documentation for -- 'setInitialState' for the rules to be followed when determining this. arStatusCmp :: InstanceData -> [AutoRepairData] -> Result InstanceData arStatusCmp instData arData = let curSt = arState instData arData' = sortBy (comparing keyfn) arData keyfn d = (arResult d, arTime d) newData = last arData' newSt = case arResult newData of Just ArSuccess -> ArHealthy $ Just newData Just ArEnoperm -> ArHealthy $ Just newData Just ArFailure -> ArFailedRepair newData Nothing -> ArPendingRepair newData in case curSt of ArFailedRepair _ -> Ok instData -- Always keep the earliest failure. ArHealthy _ -> Ok instData { arState = newSt , tagsToRemove = delCurTag instData } ArPendingRepair d -> Bad ( "An unfinished repair was found in instance " ++ Instance.name (arInstance instData) ++ ": found tag " ++ show (arTag newData) ++ ", but older pending tag " ++ show (arTag d) ++ "exists.") ArNeedsRepair _ -> Bad "programming error: ArNeedsRepair found as an initial state" -- | Query jobs of a pending repair, returning the new instance data. processPending :: L.Client -> InstanceData -> IO InstanceData processPending client instData = case arState instData of (ArPendingRepair arData) -> do sts <- L.queryJobsStatus client $ arJobs arData time <- getClockTime case sts of Bad e -> exitErr $ "could not check job status: " ++ formatError e Ok sts' -> if any (<= JOB_STATUS_RUNNING) sts' then return instData -- (no change) else do let iname = Instance.name $ arInstance instData srcSt = arStateName $ arState instData destSt = arStateName arState' putStrLn ("Moving " ++ iname ++ " from " ++ show srcSt ++ " to " ++ show destSt) commitChange client instData' where instData' = instData { arState = arState' , tagsToRemove = delCurTag instData } arState' = if all (== JOB_STATUS_SUCCESS) sts' then ArHealthy $ Just (updateTag $ arData { arResult = Just ArSuccess , arTime = time }) else ArFailedRepair (updateTag $ arData { arResult = Just ArFailure , arTime = time }) _ -> return instData -- | Update the tag of an 'AutoRepairData' record to match all the other fields. updateTag :: AutoRepairData -> AutoRepairData updateTag arData = let ini = [autoRepairTypeToRaw $ arType arData, arUuid arData, clockTimeToString $ arTime arData] end = [intercalate "+" . map (show . fromJobId) $ arJobs arData] (pfx, middle) = case arResult arData of Nothing -> (C.autoRepairTagPending, []) Just rs -> (C.autoRepairTagResult, [autoRepairResultToRaw rs]) in arData { arTag = pfx ++ intercalate ":" (ini ++ middle ++ end) } -- | Apply and remove tags from an instance as indicated by 'InstanceData'. -- -- If the /arState/ of the /InstanceData/ record has an associated -- 'AutoRepairData', add its tag to the instance object. Additionally, if -- /tagsToRemove/ is not empty, remove those tags from the instance object. The -- returned /InstanceData/ object always has an empty /tagsToRemove/. commitChange :: L.Client -> InstanceData -> IO InstanceData commitChange client instData = do let iname = Instance.name $ arInstance instData arData = getArData $ arState instData rmTags = tagsToRemove instData execJobsWaitOk' opcodes = do res <- execJobsWaitOk [map wrapOpCode opcodes] client case res of Ok _ -> return () Bad e -> exitErr e when (isJust arData) $ do let tag = arTag $ fromJust arData putStrLn (">>> Adding the following tag to " ++ iname ++ ":\n" ++ show tag) execJobsWaitOk' [OpTagsSet TagKindInstance [tag] (Just iname)] unless (null rmTags) $ do putStr (">>> Removing the following tags from " ++ iname ++ ":\n" ++ unlines (map show rmTags)) execJobsWaitOk' [OpTagsDel TagKindInstance rmTags (Just iname)] return instData { tagsToRemove = [] } -- | Detect brokenness with an instance and suggest repair type and jobs to run. detectBroken :: Node.List -> Instance.Instance -> Maybe (AutoRepairType, [OpCode]) detectBroken nl inst = let disk = Instance.diskTemplate inst iname = Instance.name inst offPri = Node.offline $ Container.find (Instance.pNode inst) nl offSec = Node.offline $ Container.find (Instance.sNode inst) nl in case disk of DTDrbd8 | offPri && offSec -> Just ( ArReinstall, [ OpInstanceRecreateDisks { opInstanceName = iname , opInstanceUuid = Nothing , opRecreateDisksInfo = RecreateDisksAll , opNodes = [] -- FIXME: there should be a better way to -- specify opcode parameters than abusing -- mkNonEmpty in this way (using the fact -- that Maybe is used both for optional -- fields, and to express failure). , opNodeUuids = Nothing , opIallocator = mkNonEmpty "hail" } , OpInstanceReinstall { opInstanceName = iname , opInstanceUuid = Nothing , opOsType = Nothing , opTempOsParams = Nothing , opForceVariant = False } ]) | offPri -> Just ( ArFailover, [ OpInstanceFailover { opInstanceName = iname , opInstanceUuid = Nothing -- FIXME: ditto, see above. , opShutdownTimeout = fromJust $ mkNonNegative C.defaultShutdownTimeout , opIgnoreConsistency = False , opTargetNode = Nothing , opTargetNodeUuid = Nothing , opIgnoreIpolicy = False , opIallocator = Nothing , opMigrationCleanup = False } ]) | offSec -> Just ( ArFixStorage, [ OpInstanceReplaceDisks { opInstanceName = iname , opInstanceUuid = Nothing , opReplaceDisksMode = ReplaceNewSecondary , opReplaceDisksList = [] , opRemoteNode = Nothing -- FIXME: ditto, see above. , opRemoteNodeUuid = Nothing , opIallocator = mkNonEmpty "hail" , opEarlyRelease = False , opIgnoreIpolicy = False } ]) | otherwise -> Nothing DTPlain | offPri -> Just ( ArReinstall, [ OpInstanceRecreateDisks { opInstanceName = iname , opInstanceUuid = Nothing , opRecreateDisksInfo = RecreateDisksAll , opNodes = [] -- FIXME: ditto, see above. , opNodeUuids = Nothing , opIallocator = mkNonEmpty "hail" } , OpInstanceReinstall { opInstanceName = iname , opInstanceUuid = Nothing , opOsType = Nothing , opTempOsParams = Nothing , opForceVariant = False } ]) | otherwise -> Nothing _ -> Nothing -- Other cases are unimplemented for now: DTDiskless, -- DTFile, DTSharedFile, DTBlock, DTRbd, DTExt. -- | Perform the suggested repair on an instance if its policy allows it. doRepair :: L.Client -- ^ The Luxi client -> Double -- ^ Delay to insert before the first repair opcode -> InstanceData -- ^ The instance data -> (AutoRepairType, [OpCode]) -- ^ The repair job to perform -> IO InstanceData -- ^ The updated instance data doRepair client delay instData (rtype, opcodes) = let inst = arInstance instData ipol = Instance.arPolicy inst iname = Instance.name inst in case ipol of ArEnabled maxtype -> if rtype > maxtype then do uuid <- newUUID time <- getClockTime let arState' = ArNeedsRepair ( updateTag $ AutoRepairData rtype uuid time [] (Just ArEnoperm) "") instData' = instData { arState = arState' , tagsToRemove = delCurTag instData } putStrLn ("Not performing a repair of type " ++ show rtype ++ " on " ++ iname ++ " because only repairs up to " ++ show maxtype ++ " are allowed") commitChange client instData' -- Adds "enoperm" result label. else do putStrLn ("Executing " ++ show rtype ++ " repair on " ++ iname) -- After submitting the job, we must write an autorepair:pending tag, -- that includes the repair job IDs so that they can be checked later. -- One problem we run into is that the repair job immediately grabs -- locks for the affected instance, and the subsequent TAGS_SET job is -- blocked, introducing an unnecessary delay for the end-user. One -- alternative would be not to wait for the completion of the TAGS_SET -- job, contrary to what commitChange normally does; but we insist on -- waiting for the tag to be set so as to abort in case of failure, -- because the cluster is left in an invalid state in that case. -- -- The proper solution (in 2.9+) would be not to use tags for storing -- autorepair data, or make the TAGS_SET opcode not grab an instance's -- locks (if that's deemed safe). In the meantime, we introduce an -- artificial delay in the repair job (via a TestDelay opcode) so that -- once we have the job ID, the TAGS_SET job can complete before the -- repair job actually grabs the locks. (Please note that this is not -- about synchronization, but merely about speeding up the execution of -- the harep tool. If this TestDelay opcode is removed, the program is -- still correct.) let opcodes' = if delay > 0 then OpTestDelay { opDelayDuration = delay , opDelayOnMaster = True , opDelayOnNodes = [] , opDelayOnNodeUuids = Nothing , opDelayRepeat = fromJust $ mkNonNegative 0 , opDelayNoLocks = False } : opcodes else opcodes uuid <- newUUID time <- getClockTime jids <- submitJobs [map wrapOpCode opcodes'] client case jids of Bad e -> exitErr e Ok jids' -> let arState' = ArPendingRepair ( updateTag $ AutoRepairData rtype uuid time jids' Nothing "") instData' = instData { arState = arState' , tagsToRemove = delCurTag instData } in commitChange client instData' -- Adds "pending" label. otherSt -> do putStrLn ("Not repairing " ++ iname ++ " because it's in state " ++ show otherSt) return instData -- | Main function. main :: Options -> [String] -> IO () main opts args = do unless (null args) $ exitErr "this program doesn't take any arguments." luxiDef <- Path.defaultLuxiSocket let master = fromMaybe luxiDef $ optLuxi opts opts' = opts { optLuxi = Just master } (ClusterData _ nl il _ _) <- loadExternalData opts' let iniDataRes = mapM setInitialState $ Container.elems il iniData <- exitIfBad "when parsing auto-repair tags" iniDataRes -- First step: check all pending repairs, see if they are completed. iniData' <- bracket (L.getClient master) L.closeClient $ forM iniData . processPending -- Second step: detect any problems. let repairs = map (detectBroken nl . arInstance) iniData' -- Third step: create repair jobs for broken instances that are in ArHealthy. let maybeRepair c (i, r) = maybe (return i) (repairHealthy c i) r jobDelay = optJobDelay opts repairHealthy c i = case arState i of ArHealthy _ -> doRepair c jobDelay i _ -> const (return i) repairDone <- bracket (L.getClient master) L.closeClient $ forM (zip iniData' repairs) . maybeRepair -- Print some stats and exit. let states = map ((, 1 :: Int) . arStateName . arState) repairDone counts = Map.fromListWith (+) states putStrLn "---------------------" putStrLn "Instance status count" putStrLn "---------------------" putStr . unlines . Map.elems $ Map.mapWithKey (\k v -> k ++ ": " ++ show v) counts
apyrgio/snf-ganeti
src/Ganeti/HTools/Program/Harep.hs
bsd-2-clause
20,587
0
23
7,211
3,568
1,867
1,701
320
7
{-# LANGUAGE OverloadedStrings #-} module CurrentCmd where import Data.Text (Text) import qualified Data.Text as T import Text.Printf -- friends import Time import Record import RecordSet -- This command doesn't actually use any command line arguments -- but still respects the spec. currentCmd :: ZonedTime -> [String] -> IO () currentCmd zt _ = do mbRecord <- readCurrentRecord case mbRecord of Just r -> printf "Description: %s\nStarted: %s\n" (T.unpack $ crecDescr r) (prettyTime (zonedTimeZone zt) (crecStart r)) Nothing -> printf "There is no current record.\n"
sseefried/task
src/CurrentCmd.hs
bsd-3-clause
627
0
14
143
142
77
65
16
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Myo.WebSockets.Types ( EventType(..) , MyoID , Version(..) , EMG(..) , Pose(..) , Orientation(..) , Accelerometer(..) , Gyroscope(..) , Arm(..) , Direction(..) , Frame(..) , Event(..) , Command , CommandData(..) , Vibration(..) , StreamEMGStatus(..) , UnlockMode(..) , UserAction(..) , LockingPolicy(..) -- * Lenses , mye_type , mye_timestamp , mye_myo , mye_arm , mye_x_direction , mye_version , mye_warmup_result , mye_rssi , mye_pose , mye_emg , mye_orientation , mye_accelerometer , mye_gyroscope , myv_major , myv_minor , myv_patch , myv_hardware -- * Smart constructors , newCommand ) where import Data.Aeson.TH import Data.Int import Data.Monoid import Data.Scientific import Data.Aeson.Types hiding (Result) import Data.Char import Control.Monad import Control.Applicative import Lens.Family2.TH import qualified Data.Vector as V import qualified Data.Text as T import qualified Data.HashMap.Strict as HM ------------------------------------------------------------------------------- data EventType = EVT_Paired | EVT_Battery_Level | EVT_Locked | EVT_Unlocked | EVT_Warmup_Completed | EVT_Connected | EVT_Disconnected | EVT_Arm_Synced | EVT_Arm_Unsynced | EVT_Orientation | EVT_Pose | EVT_RSSI | EVT_EMG deriving (Show, Eq) ------------------------------------------------------------------------------- newtype MyoID = MyoID Integer deriving (Show, Eq) ------------------------------------------------------------------------------- data Version = Version { _myv_major :: !Integer , _myv_minor :: !Integer , _myv_patch :: !Integer , _myv_hardware :: !Integer } deriving (Show, Eq) ------------------------------------------------------------------------------- -- It's an 8 bit integer data EMG = EMG Int8 deriving (Show, Eq) ------------------------------------------------------------------------------- data Pose = Rest | Fist | Wave_In | Wave_Out | Fingers_Spread | Double_Tap | Unknown deriving (Show, Eq) data Orientation = Orientation { _ori_x :: !Double , _ori_y :: !Double , _ori_z :: !Double , _ori_w :: !Double } deriving (Show, Eq) data Accelerometer = Accelerometer { _acc_x :: !Double , _acc_y :: !Double , _acc_z :: !Double } deriving (Show, Eq) data Gyroscope = Gyroscope { _gyr_x :: !Double , _gyr_y :: !Double , _gyr_z :: !Double } deriving (Show, Eq) ------------------------------------------------------------------------------- data Arm = Arm_Left | Arm_Right deriving (Show, Eq) ------------------------------------------------------------------------------- data Direction = Toward_wrist | Toward_elbow deriving (Show, Eq) ------------------------------------------------------------------------------- data Frame = Evt Event | Cmd Command | Ack Acknowledgement deriving (Show, Eq) instance FromJSON Frame where parseJSON a@(Array v) = case V.toList v of [String "event", o@(Object _)] -> Evt <$> parseJSON o [String "acknowledgement", o@(Object _)] -> Ack <$> parseJSON o [String "command", o@(Object b)] -> case HM.lookup "result" b of Nothing -> Cmd <$> parseJSON o Just _ -> Ack <$> parseJSON o _ -> typeMismatch "Frame: Unexpected payload in Array." a parseJSON v = typeMismatch "Frame: Expecting an Array of frames." v ------------------------------------------------------------------------------- -- TODO: Break down this `Event` type into a mandatory section (type, timestamp, myo) -- and a payload specific field, so that we do not have all this proliferation of -- Maybe. The `FromJSON` instance will need to be written manually, but it's not -- too bad. data Event = Event { _mye_type :: !EventType , _mye_timestamp :: !T.Text , _mye_myo :: !MyoID , _mye_arm :: !(Maybe Arm) , _mye_x_direction :: !(Maybe Direction) , _mye_version :: !(Maybe Version) , _mye_warmup_result :: !(Maybe Result) , _mye_rssi :: !(Maybe Int) , _mye_pose :: !(Maybe Pose) , _mye_emg :: !(Maybe EMG) , _mye_orientation :: !(Maybe Orientation) , _mye_accelerometer :: !(Maybe Accelerometer) , _mye_gyroscope :: !(Maybe Gyroscope) } deriving (Show, Eq) data Acknowledgement = Acknowledgement { _ack_command :: AcknowledgedCommand , _ack_result :: Result } deriving (Show, Eq) data AcknowledgedCommand = ACC_set_locking_policy | ACC_set_stream_emg deriving (Show, Eq) ------------------------------------------------------------------------------- data Result = Success | Fail deriving (Show, Eq) ------------------------------------------------------------------------------- data CommandData = Vibrate Vibration | Set_Stream_EMG StreamEMGStatus | Unlock UnlockMode | Notify_User_Action UserAction | Set_Locking_Policy LockingPolicy | Request_RSSI | Lock deriving (Show, Eq) instance ToJSON CommandData where toJSON cd = case cd of Vibrate v -> object ["command" .= String "vibrate", "type" .= toJSON v] Set_Stream_EMG v -> object ["command" .= String "set_stream_emg", "type" .= toJSON v] Unlock v -> object ["command" .= String "unlock", "type" .= toJSON v] Notify_User_Action v -> object ["command" .= String "notify_user_action", "type" .= toJSON v] Set_Locking_Policy v -> object ["command" .= String "set_locking_policy", "type" .= toJSON v] Lock -> object ["command" .= String "lock"] Request_RSSI -> object ["command" .= String "request_rssi"] instance FromJSON CommandData where parseJSON (Object o) = do (cmd :: T.Text) <- o .: "command" typ <- o .: "type" case cmd of "vibrate" -> Vibrate <$> parseJSON typ "request_rssi" -> pure Request_RSSI "set_stream_emg" -> Set_Stream_EMG <$> parseJSON typ "set_locking_policy" -> Set_Locking_Policy <$> parseJSON typ "unlock" -> Unlock <$> parseJSON typ "lock" -> pure Lock "notify_user_action" -> Notify_User_Action <$> parseJSON typ t -> fail $ "FromJSON CommandData: invalid 'command' found: " <> show t parseJSON t = typeMismatch ("CommandData, expected Object, found " <> show t) t ------------------------------------------------------------------------------- data Vibration = VIB_short | VIB_medium | VIB_long deriving (Show, Eq) ------------------------------------------------------------------------------- data UserAction = UAC_single deriving (Show, Eq) ------------------------------------------------------------------------------- data LockingPolicy = LKP_standard | LKP_none deriving (Show, Eq) ------------------------------------------------------------------------------- data UnlockMode = UMD_timed | UMD_hold deriving (Show, Eq) ------------------------------------------------------------------------------- data StreamEMGStatus = SES_enabled | SES_disabled deriving (Show, Eq) ------------------------------------------------------------------------------- data Command = Command { _myc_myo :: !MyoID , _myc_info :: CommandData } deriving (Show, Eq) instance FromJSON Command where parseJSON v@(Object o) = Command <$> o .: "myo" <*> parseJSON v parseJSON v = fail $ "FromJSON Command, expected Object, found " <> show v instance ToJSON Command where toJSON (Command mid cd) = case toJSON cd of Object b -> object $ ["myo" .= mid] <> HM.toList b v -> error $ "Command: toJSON of CommandData failed, found " <> show v -------------------------------------------------------------------------------- -- | Creates a new `Command`, to be sent to the Myo armband. newCommand :: MyoID -> CommandData -> Command newCommand mid cd = Command mid cd ------------------------------------------------------------------------------- instance FromJSON Version where parseJSON (Array v) = do let lst = V.toList v case liftM2 (,) (Just $ length lst) (mapM toNumber lst) of Just (4, x) -> case mapM floatingOrInteger x of Right [ma, mi, pa, ha] -> return $ Version ma mi pa ha _ -> mzero _ -> mzero parseJSON v = typeMismatch "Version: Expecting an Array like [major, minor, patch, hardware]" v ------------------------------------------------------------------------------- toNumber :: Value -> Maybe Scientific toNumber (Number v) = Just v toNumber _ = Nothing ------------------------------------------------------------------------------- -- TODO: Create an Int8 in a better way than this one! instance FromJSON EMG where parseJSON (Array v) = do let lst = V.toList v case liftM2 (,) (Just $ length lst) (mapM toNumber lst) of Just (8, x) -> case mapM floatingOrInteger x of Right res -> return . EMG . read $ concatMap show res _ -> mzero _ -> mzero parseJSON v = typeMismatch "EMG: Expecting an Array of size 8." v instance FromJSON Gyroscope where parseJSON (Array v) = case V.toList v of [Number x, Number y, Number z] -> return $ Gyroscope (toRealFloat x) (toRealFloat y) (toRealFloat z) _ -> mzero parseJSON v = typeMismatch "Gyroscope: Expecting an Array of Double like [x,y,z]" v instance FromJSON Accelerometer where parseJSON (Array v) = case V.toList v of [Number x, Number y, Number z] -> return $ Accelerometer (toRealFloat x) (toRealFloat y) (toRealFloat z) _ -> mzero parseJSON v = typeMismatch "Accelerometer: Expecting an Array of Double like [x,y,z]" v ------------------------------------------------------------------------------- -- -- JSON instances -- deriveJSON defaultOptions ''MyoID deriveFromJSON defaultOptions { fieldLabelModifier = drop 5 } ''Event deriveFromJSON defaultOptions { constructorTagModifier = map toLower } ''Result deriveJSON defaultOptions { constructorTagModifier = drop 4 . map toLower } ''Vibration deriveJSON defaultOptions { constructorTagModifier = drop 4 . map toLower } ''StreamEMGStatus deriveJSON defaultOptions { constructorTagModifier = drop 4 . map toLower } ''LockingPolicy deriveJSON defaultOptions { constructorTagModifier = map toLower } ''UserAction deriveJSON defaultOptions { constructorTagModifier = map toLower } ''UnlockMode deriveFromJSON defaultOptions { fieldLabelModifier = drop 5 } ''Orientation deriveFromJSON defaultOptions { constructorTagModifier = map toLower . drop 4 } ''EventType deriveFromJSON defaultOptions { constructorTagModifier = map toLower } ''Pose deriveFromJSON defaultOptions { constructorTagModifier = map toLower } ''Direction deriveFromJSON defaultOptions { constructorTagModifier = map toLower . drop 4 } ''Arm deriveFromJSON defaultOptions { fieldLabelModifier = drop 5 } ''Acknowledgement deriveFromJSON defaultOptions { constructorTagModifier = drop 4 } ''AcknowledgedCommand ------------------------------------------------------------------------------- -- -- Lenses -- makeLenses ''Event makeLenses ''Version
adinapoli/myo
src/Myo/WebSockets/Types.hs
bsd-3-clause
11,449
0
16
2,108
2,774
1,485
1,289
308
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} module Test.Tasty.Hspec ( -- * Test testSpec -- * Options -- | === Re-exported from <https://hackage.haskell.org/package/tasty-smallcheck tasty-smallcheck> , SmallCheckDepth(..) -- | === Re-exported from <https://hackage.haskell.org/package/tasty-quickcheck tasty-quickcheck> , QuickCheckMaxRatio(..) , QuickCheckMaxSize(..) , QuickCheckReplay(..) , QuickCheckTests(..) -- * Hspec re-export , module Test.Hspec ) where import Control.Applicative ((<$>)) import Data.Proxy import Data.Typeable (Typeable) import qualified Test.Hspec as H import qualified Test.Hspec.Core.Spec as H import qualified Test.QuickCheck as QC import qualified Test.Tasty as T import qualified Test.Tasty.SmallCheck as TSC import qualified Test.Tasty.Options as T import qualified Test.Tasty.Providers as T import qualified Test.Tasty.QuickCheck as TQC import qualified Test.Tasty.Runners as T -- For re-export. import Test.Hspec import Test.Tasty.SmallCheck (SmallCheckDepth(..)) import Test.Tasty.QuickCheck (QuickCheckMaxRatio(..), QuickCheckMaxSize(..) , QuickCheckReplay(..), QuickCheckTests(..)) -- | Create a <https://hackage.haskell.org/package/tasty tasty> 'T.TestTree' from an -- <https://hackage.haskell.org/package/hspec Hspec> 'H.Spec'. testSpec :: T.TestName -> H.Spec -> IO T.TestTree testSpec name spec = T.testGroup name . map specTreeToTestTree <$> H.runSpecM spec specTreeToTestTree :: H.SpecTree () -> T.TestTree specTreeToTestTree (H.Node name spec_trees) = T.testGroup name (map specTreeToTestTree spec_trees) specTreeToTestTree (H.NodeWithCleanup cleanup spec_trees) = let test_tree = specTreeToTestTree (H.Node "(unnamed)" spec_trees) in T.WithResource (T.ResourceSpec (return ()) cleanup) (const test_tree) specTreeToTestTree (H.Leaf item) = T.singleTest (H.itemRequirement item) (Item item) hspecResultToTastyResult :: H.Result -> T.Result hspecResultToTastyResult H.Success = T.testPassed "" hspecResultToTastyResult (H.Pending mstr) = T.testFailed ("test pending" ++ maybe "" (": " ++) mstr) hspecResultToTastyResult (H.Fail str) = T.testFailed str newtype Item = Item (H.Item ()) deriving Typeable instance T.IsTest Item where run opts (Item (H.Item _ _ _ ex)) progress = hspecResultToTastyResult <$> ex params ($ ()) hprogress where params :: H.Params params = H.Params { H.paramsQuickCheckArgs = qc_args , H.paramsSmallCheckDepth = sc_depth } where qc_args :: QC.Args qc_args = let TQC.QuickCheckTests num_tests = T.lookupOption opts TQC.QuickCheckReplay replay = T.lookupOption opts TQC.QuickCheckMaxSize max_size = T.lookupOption opts TQC.QuickCheckMaxRatio max_ratio = T.lookupOption opts in QC.stdArgs { QC.chatty = False , QC.maxDiscardRatio = max_ratio , QC.maxSize = max_size , QC.maxSuccess = num_tests , QC.replay = replay } sc_depth :: Int sc_depth = let TSC.SmallCheckDepth depth = T.lookupOption opts in depth hprogress :: H.Progress -> IO () hprogress (x,y) = progress $ T.Progress { T.progressText = "" , T.progressPercent = fromIntegral x / fromIntegral y } testOptions = return [ T.Option (Proxy :: Proxy TQC.QuickCheckTests) , T.Option (Proxy :: Proxy TQC.QuickCheckReplay) , T.Option (Proxy :: Proxy TQC.QuickCheckMaxSize) , T.Option (Proxy :: Proxy TQC.QuickCheckMaxRatio) , T.Option (Proxy :: Proxy TSC.SmallCheckDepth) ]
markus1189/tasty-hspec
Test/Tasty/Hspec.hs
bsd-3-clause
3,986
0
15
1,075
968
540
428
71
1
{- - Claq (c) 2013 NEC Laboratories America, Inc. All rights reserved. - - This file is part of Claq. - Claq is distributed under the 3-clause BSD license. - See the LICENSE file for more details. -} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} module Data.ClassicalCircuit (ClaGate(..), ClaCircuit(..)) where import Data.Foldable (Foldable) import Data.Traversable (Traversable) import Data.DAG (DAG) import qualified Data.DAG as DAG import Data.ExitF data ClaGate a = GConst Bool | GNot a | GAnd a a | GOr a a | GXor a a deriving (Eq, Show, Functor, Foldable, Traversable) newtype ClaCircuit inp = ClaCircuit (DAG (ExitF inp ClaGate)) instance Functor ClaCircuit where fmap f (ClaCircuit g) = ClaCircuit $ DAG.mapDAG (mapExitF f) g
ti1024/claq
src/Data/ClassicalCircuit.hs
bsd-3-clause
805
0
9
140
192
112
80
14
0
module Graphics.UI.SDL.Basic ( -- * Initialization and Shutdown init, initSubSystem, quit, quitSubSystem, setMainReady, wasInit, -- * Configuration Variables addHintCallback, clearHints, delHintCallback, getHint, setHint, setHintWithPriority, -- * Error Handling clearError, getError, setError, -- * Log Handling log, logCritical, logDebug, logError, logGetOutputFunction, logGetPriority, logInfo, logMessage, logResetPriorities, logSetAllPriority, logSetOutputFunction, logSetPriority, logVerbose, logWarn, -- * Assertions -- | Use Haskell's own assertion primitives rather than SDL's. -- * Querying SDL Version getRevision, getRevisionNumber, getVersion ) where import Data.Word import Foreign.C.String import Foreign.C.Types import Foreign.Ptr import Graphics.UI.SDL.Enum import Graphics.UI.SDL.Types import Prelude hiding (init, log) foreign import ccall "SDL.h SDL_Init" init :: InitFlag -> IO CInt foreign import ccall "SDL.h SDL_InitSubSystem" initSubSystem :: InitFlag -> IO CInt foreign import ccall "SDL.h SDL_Quit" quit :: IO () foreign import ccall "SDL.h SDL_QuitSubSystem" quitSubSystem :: InitFlag -> IO () foreign import ccall "SDL.h SDL_SetMainReady" setMainReady :: IO () foreign import ccall "SDL.h SDL_WasInit" wasInit :: InitFlag -> IO Word32 foreign import ccall "SDL.h SDL_AddHintCallback" addHintCallback :: CString -> HintCallback -> Ptr () -> IO () foreign import ccall "SDL.h SDL_ClearHints" clearHints :: IO () foreign import ccall "SDL.h SDL_DelHintCallback" delHintCallback :: CString -> HintCallback -> Ptr () -> IO () foreign import ccall "SDL.h SDL_GetHint" getHint :: CString -> IO CString foreign import ccall "SDL.h SDL_SetHint" setHint :: CString -> CString -> IO Bool foreign import ccall "SDL.h SDL_SetHintWithPriority" setHintWithPriority :: CString -> CString -> HintPriority -> IO Bool foreign import ccall "SDL.h SDL_ClearError" clearError :: IO () foreign import ccall "SDL.h SDL_GetError" getError :: IO CString foreign import ccall "sdlhelper.c SDLHelper_SetError" setError :: CString -> IO CInt foreign import ccall "SDL.h SDL_LogGetOutputFunction" logGetOutputFunction :: Ptr LogOutputFunction -> Ptr (Ptr ()) -> IO () foreign import ccall "SDL.h SDL_LogGetPriority" logGetPriority :: CInt -> IO LogPriority foreign import ccall "sdlhelper.c SDLHelper_LogMessage" logMessage :: CInt -> LogPriority -> CString -> IO () foreign import ccall "SDL.h SDL_LogResetPriorities" logResetPriorities :: IO () foreign import ccall "SDL.h SDL_LogSetAllPriority" logSetAllPriority :: LogPriority -> IO () foreign import ccall "SDL.h SDL_LogSetOutputFunction" logSetOutputFunction :: LogOutputFunction -> Ptr () -> IO () foreign import ccall "SDL.h SDL_LogSetPriority" logSetPriority :: CInt -> LogPriority -> IO () foreign import ccall "SDL.h SDL_GetRevision" getRevision :: IO CString foreign import ccall "SDL.h SDL_GetRevisionNumber" getRevisionNumber :: IO CInt foreign import ccall "SDL.h SDL_GetVersion" getVersion :: Ptr Version -> IO () log :: CString -> IO () log = logMessage SDL_LOG_CATEGORY_APPLICATION SDL_LOG_PRIORITY_INFO logCritical :: CInt -> CString -> IO () logCritical category = logMessage category SDL_LOG_PRIORITY_CRITICAL logDebug :: CInt -> CString -> IO () logDebug category = logMessage category SDL_LOG_PRIORITY_DEBUG logError :: CInt -> CString -> IO () logError category = logMessage category SDL_LOG_PRIORITY_ERROR logInfo :: CInt -> CString -> IO () logInfo category = logMessage category SDL_LOG_PRIORITY_INFO logVerbose :: CInt -> CString -> IO () logVerbose category = logMessage category SDL_LOG_PRIORITY_VERBOSE logWarn :: CInt -> CString -> IO () logWarn category = logMessage category SDL_LOG_PRIORITY_WARN
ekmett/sdl2
Graphics/UI/SDL/Basic.hs
bsd-3-clause
3,737
64
11
531
986
529
457
79
1
module EarleyExampleSpec where import EarleyExample (grammar, NumberWord, Expected) import qualified Text.Earley as E import qualified Data.List.NonEmpty as NonEmpty import Test.Hspec (Spec, hspec, describe, it, shouldMatchList) -- | Required for auto-discovery. spec :: Spec spec = describe "EarleyExample" $ do it "returns all possible parses of number words" $ do let (result, _) = parseNumberWord 1234 map NonEmpty.toList result `shouldMatchList` ["ABCD", "AWD", "LCD"] parseNumberWord :: Integer -> ([NumberWord], E.Report Expected String) parseNumberWord = E.fullParses (E.parser grammar) . show main :: IO () main = hspec spec
FranklinChen/twenty-four-days2015-of-hackage
test/EarleyExampleSpec.hs
bsd-3-clause
665
0
14
116
194
110
84
16
1
module Consts where import Data.Text -- | TODO: move to SDL module type WindowName = Text mainWindowName :: WindowName mainWindowName = "mainWindow"
Teaspot-Studio/gore-and-ash-game
src/client/Consts.hs
bsd-3-clause
153
0
4
26
26
17
9
5
1
{-# LANGUAGE TypeFamilies, ExistentialQuantification, FlexibleInstances, UndecidableInstances, FlexibleContexts, ScopedTypeVariables, MultiParamTypeClasses #-} -- | The Signal module serves as a representation for the combined shallow and -- deep embeddings of sequential circuits. The shallow portion is reprented as a -- stream, the deep portion as a (typed) entity. To allow for multiple clock -- domains, the Signal type includes an extra type parameter. The type alias 'Seq' -- is for sequential logic in some implicit global clock domain. module Language.KansasLava.Signal where import Control.Applicative import Control.Monad (liftM, liftM2, liftM3) import Data.List as List import Data.Bits import Data.Sized.Ix import Data.Sized.Matrix as M -- import Language.KansasLava.Comb import Language.KansasLava.Rep --import Language.KansasLava.Signal import qualified Language.KansasLava.Stream as S import Language.KansasLava.Types ----------------------------------------------------------------------------------------------- -- | These are sequences of values over time. -- We assume edge triggered logic (checked at (typically) rising edge of clock) -- This clock is assumed known, based on who is consuming the list. -- Right now, it is global, but we think we can support multiple clocks with a bit of work. data Signal (c :: *) a = Signal (S.Stream (X a)) (D a) -- | Signal in some implicit clock domain. type Seq a = Signal CLK a -- | Extract the shallow portion of a 'Signal'. shallowS :: Signal c a -> S.Stream (X a) shallowS (Signal a _) = a -- | Extract the deep portion of a 'Signal'. deepS :: Signal c a -> D a deepS (Signal _ d) = d deepMapS :: (D a -> D a) -> Signal c a -> Signal c a deepMapS f (Signal a d) = (Signal a (f d)) shallowMapS :: (S.Stream (X a) -> S.Stream (X a)) -> Signal c a -> Signal c a shallowMapS f (Signal a d) = (Signal (f a) d) -- | A pure 'Signal'. pureS :: (Rep a) => a -> Signal i a pureS a = Signal (pure (pureX a)) (D $ Lit $ toRep $ pureX a) -- | A 'Signal' witness identity function. Useful when typing things. witnessS :: (Rep a) => Witness a -> Signal i a -> Signal i a witnessS (Witness) = id -- | Inject a deep value into a Signal. The shallow portion of the Signal will be an -- error, if it is every used. mkDeepS :: D a -> Signal c a mkDeepS = Signal (error "incorrect use of shallow Signal") -- | Inject a shallow value into a Signal. The deep portion of the Signal will be an -- Error if it is ever used. mkShallowS :: (Clock c) => S.Stream (X a) -> Signal c a mkShallowS s = Signal s (D $ Error "incorrect use of deep Signal") -- | Create a Signal with undefined for both the deep and shallow elements. undefinedS :: forall a sig clk . (Rep a, sig ~ Signal clk) => sig a undefinedS = Signal (pure $ (unknownX :: X a)) (D $ Lit $ toRep (unknownX :: X a)) -- | Attach a comment to a 'Signal'. commentS :: forall a sig clk . (Rep a, sig ~ Signal clk) => String -> sig a -> sig a commentS msg = idS (Comment [msg]) ----------------------------------------------------------------------- -- primitive builders -- | 'idS' create an identity function, with a given 'Id' tag. idS :: forall a sig clk . (Rep a, sig ~ Signal clk) => Id -> sig a -> sig a idS id' (Signal a ae) = Signal a $ D $ Port "o0" $ E $ Entity id' [("o0",repType (Witness :: Witness a))] [("i0",repType (Witness :: Witness a),unD $ ae)] -- | create a zero-arity Signal value from an 'X' value. primXS :: (Rep a) => X a -> String -> Signal i a primXS a nm = Signal (pure a) (entityD nm) -- | create an arity-1 Signal function from an 'X' function. primXS1 :: forall a b i . (Rep a, Rep b) => (X a -> X b) -> String -> Signal i a -> Signal i b primXS1 f nm (Signal a1 ae1) = Signal (fmap f a1) (entityD1 nm ae1) -- | create an arity-2 Signal function from an 'X' function. primXS2 :: forall a b c i . (Rep a, Rep b, Rep c) => (X a -> X b -> X c) -> String -> Signal i a -> Signal i b -> Signal i c primXS2 f nm (Signal a1 ae1) (Signal a2 ae2) = Signal (S.zipWith f a1 a2) (entityD2 nm ae1 ae2) -- | create an arity-3 Signal function from an 'X' function. primXS3 :: forall a b c d i . (Rep a, Rep b, Rep c, Rep d) => (X a -> X b -> X c -> X d) -> String -> Signal i a -> Signal i b -> Signal i c -> Signal i d primXS3 f nm (Signal a1 ae1) (Signal a2 ae2) (Signal a3 ae3) = Signal (S.zipWith3 f a1 a2 a3) (entityD3 nm ae1 ae2 ae3) -- | create a zero-arity Signal value from a value. primS :: (Rep a) => a -> String -> Signal i a primS a nm = primXS (pureX a) nm -- | create an arity-1 Signal function from a function. primS1 :: (Rep a, Rep b) => (a -> b) -> String -> Signal i a -> Signal i b primS1 f nm = primXS1 (\ a -> optX $ liftM f (unX a)) nm -- | create an arity-2 Signal function from a function. primS2 :: (Rep a, Rep b, Rep c) => (a -> b -> c) -> String -> Signal i a -> Signal i b -> Signal i c primS2 f nm = primXS2 (\ a b -> optX $ liftM2 f (unX a) (unX b)) nm -- | create an arity-3 Signal function from a function. primS3 :: (Rep a, Rep b, Rep c, Rep d) => (a -> b -> c -> d) -> String -> Signal i a -> Signal i b -> Signal i c -> Signal i d primS3 f nm = primXS3 (\ a b c -> optX $ liftM3 f (unX a) (unX b) (unX c)) nm --------------------------------------------------------------------------------- instance (Rep a, Show a) => Show (Signal c a) where show (Signal vs _) = concat [ showRep x ++ " " | x <- take 20 $ S.toList vs ] ++ "..." instance (Rep a, Eq a) => Eq (Signal c a) where -- Silly question; never True; can be False. (Signal _ _) == (Signal _ _) = error "undefined: Eq over a Signal" instance (Num a, Rep a) => Num (Signal i a) where s1 + s2 = primS2 (+) "+" s1 s2 s1 - s2 = primS2 (-) "-" s1 s2 s1 * s2 = primS2 (*) "*" s1 s2 negate s1 = primS1 (negate) "negate" s1 abs s1 = primS1 (abs) "abs" s1 signum s1 = primS1 (signum) "signum" s1 fromInteger n = pureS (fromInteger n) instance (Bounded a, Rep a) => Bounded (Signal i a) where minBound = pureS $ minBound maxBound = pureS $ maxBound instance (Show a, Bits a, Rep a) => Bits (Signal i a) where s1 .&. s2 = primS2 (.&.) ".&." s1 s2 s1 .|. s2 = primS2 (.|.) ".|." s1 s2 s1 `xor` s2 = primS2 (xor) ".^." s1 s2 s1 `shiftL` n = primS2 (shiftL) "shiftL" s1 (pureS n) s1 `shiftR` n = primS2 (shiftR) "shiftR" s1 (pureS n) s1 `rotateL` n = primS2 (rotateL) "rotateL" s1 (pureS n) s1 `rotateR` n = primS2 (rotateR) "rotateR" s1 (pureS n) complement s = primS1 (complement) "complement" s bitSize s = typeWidth (typeOfS s) isSigned s = isTypeSigned (typeOfS s) instance (Eq a, Show a, Fractional a, Rep a) => Fractional (Signal i a) where s1 / s2 = primS2 (/) "/" s1 s2 recip s1 = primS1 (recip) "recip" s1 -- This should just fold down to the raw bits. fromRational r = pureS (fromRational r :: a) instance (Rep a, Enum a) => Enum (Signal i a) where toEnum = error "toEnum not supported" fromEnum = error "fromEnum not supported" instance (Ord a, Rep a) => Ord (Signal i a) where compare _ _ = error "compare not supported for Comb" (<) _ _ = error "(<) not supported for Comb" (>=) _ _ = error "(>=) not supported for Comb" (>) _ _ = error "(>) not supported for Comb" (<=)_ _ = error "(<=) not supported for Comb" s1 `max` s2 = primS2 max "max" s1 s2 s1 `min` s2 = primS2 max "min" s1 s2 instance (Rep a, Real a) => Real (Signal i a) where toRational = error "toRational not supported for Comb" instance (Rep a, Integral a) => Integral (Signal i a) where quot num dom = primS2 quot "quot" num dom rem num dom = primS2 rem "rem" num dom div num dom = primS2 div "div" num dom mod num dom = primS2 mod "mod" num dom quotRem num dom = (quot num dom, rem num dom) divMod num dom = (div num dom, mod num dom) toInteger = error "toInteger (Signal {})" ---------------------------------------------------------------------------------------------------- -- Small DSL's for declaring signals -- | Convert a list of values into a Signal. The shallow portion of the resulting -- Signal will begin with the input list, then an infinite stream of X unknowns. toS :: (Clock c, Rep a) => [a] -> Signal c a toS xs = mkShallowS (S.fromList (map optX (map Just xs ++ repeat Nothing))) -- | Convert a list of values into a Signal. The input list is wrapped with a -- Maybe, and any Nothing elements are mapped to X's unknowns. toS' :: (Clock c, Rep a) => [Maybe a] -> Signal c a toS' xs = mkShallowS (S.fromList (map optX (xs ++ repeat Nothing))) -- | Convert a list of X values to a Signal. Pad the end with an infinite list of X unknowns. toSX :: forall a c . (Clock c, Rep a) => [X a] -> Signal c a toSX xs = mkShallowS (S.fromList (xs ++ map (optX :: Maybe a -> X a) (repeat Nothing))) -- | Convert a Signal of values into a list of Maybe values. fromS :: (Rep a) => Signal c a -> [Maybe a] fromS = fmap unX . S.toList . shallowS -- | Convret a Signal of values into a list of representable values. fromSX :: (Rep a) => Signal c a -> [X a] fromSX = S.toList . shallowS -- | Compare the first depth elements of two Signals. cmpSignalRep :: forall a c . (Rep a) => Int -> Signal c a -> Signal c a -> Bool cmpSignalRep depth s1 s2 = and $ take depth $ S.toList $ S.zipWith cmpRep (shallowS s1) (shallowS s2) ----------------------------------------------------------------------------------- instance Dual (Signal c a) where dual c d = Signal (shallowS c) (deepS d) -- | Return the Lava type of a representable signal. typeOfS :: forall w clk sig . (Rep w, sig ~ Signal clk) => sig w -> Type typeOfS _ = repType (Witness :: Witness w) -- | The Pack class allows us to move between signals containing compound data -- and signals containing the elements of the compound data. This is done by -- commuting the signal type constructor with the type constructor representing -- the compound data. For example, if we have a value x :: Signal sig => sig -- (a,b), then 'unpack x' converts this to a (sig a, sig b). Dually, pack takes -- (sig a,sig b) to sig (a,b). class Pack clk a where type Unpacked clk a -- ^ Pull the sig type *out* of the compound data type. pack :: Unpacked clk a -> Signal clk a -- ^ Push the sign type *into* the compound data type. unpack :: Signal clk a -> Unpacked clk a -- | Given a function over unpacked (composite) signals, turn it into a function -- over packed signals. mapPacked :: (Pack i a, Pack i b, sig ~ Signal i) => (Unpacked i a -> Unpacked i b) -> sig a -> sig b mapPacked f = pack . f . unpack -- | Lift a binary function operating over unpacked signals into a function over a pair of packed signals. zipPacked :: (Pack i a, Pack i b, Pack i c, sig ~ Signal i) => (Unpacked i a -> Unpacked i b -> Unpacked i c) -> sig a -> sig b -> sig c zipPacked f x y = pack $ f (unpack x) (unpack y) instance (Rep a, Rep b) => Pack i (a,b) where type Unpacked i (a,b) = (Signal i a,Signal i b) pack (a,b) = primS2 (,) "pair" a b unpack ab = ( primS1 (fst) "fst" ab , primS1 (snd) "snd" ab ) instance (Rep a, Rep b, Rep c) => Pack i (a,b,c) where type Unpacked i (a,b,c) = (Signal i a,Signal i b, Signal i c) pack (a,b,c) = primS3 (,,) "triple" a b c unpack abc = ( primS1 (\(x,_,_) -> x) "fst3" abc , primS1 (\(_,x,_) -> x) "snd3" abc , primS1 (\(_,_,x) -> x) "thd3" abc ) instance (Rep a) => Pack i (Maybe a) where type Unpacked i (Maybe a) = (Signal i Bool, Signal i a) pack (a,b) = primXS2 (\ a' b' -> case unX a' of Nothing -> optX Nothing Just False -> optX $ Just Nothing Just True -> optX (Just (unX b'))) "pair" a b unpack ma = ( primXS1 (\ a -> case unX a of Nothing -> optX Nothing Just Nothing -> optX (Just False) Just (Just _) -> optX (Just True)) "fst" ma , primXS1 (\ a -> case unX a of Nothing -> optX Nothing Just Nothing -> optX Nothing Just (Just v) -> optX (Just v)) "snd" ma ) {- instance (Rep a, Rep b, Rep c, Signal sig) => Pack sig (a,b,c) where type Unpacked sig (a,b,c) = (sig a, sig b,sig c) pack (a,b,c) = liftS3 (\ (Comb a' ae) (Comb b' be) (Comb c' ce) -> Comb (XTriple (a',b',c')) (entity3 (Prim "triple") ae be ce)) a b c unpack abc = ( liftS1 (\ (Comb (XTriple (a,_b,_)) abce) -> Comb a (entity1 (Prim "fst3") abce)) abc , liftS1 (\ (Comb (XTriple (_,b,_)) abce) -> Comb b (entity1 (Prim "snd3") abce)) abc , liftS1 (\ (Comb (XTriple (_,_,c)) abce) -> Comb c (entity1 (Prim "thd3") abce)) abc ) -} unpackMatrix :: (Rep a, Size x, sig ~ Signal clk) => sig (M.Matrix x a) -> M.Matrix x (sig a) unpackMatrix a = unpack a packMatrix :: (Rep a, Size x, sig ~ Signal clk) => M.Matrix x (sig a) -> sig (M.Matrix x a) packMatrix a = pack a instance (Rep a, Size ix) => Pack clk (Matrix ix a) where type Unpacked clk (Matrix ix a) = Matrix ix (Signal clk a) pack m = Signal shallow deep where shallow :: (S.Stream (X (Matrix ix a))) shallow = id $ S.fromList -- Stream (X (Matrix ix a)) $ fmap XMatrix -- [(X (Matrix ix a))] $ fmap M.fromList -- [Matrix ix (X a)] $ List.transpose -- [[X a]] $ fmap S.toList -- [[X a]] $ fmap shallowS -- [Stream (X a)] $ M.toList -- [sig a] $ m -- Matrix ix (sig a) deep :: D (Matrix ix a) deep = D $ Port "o0" $ E $ Entity (Prim "concat") [("o0",repType (Witness :: Witness (Matrix ix a)))] [ ("i" ++ show i,repType (Witness :: Witness a),unD $ deepS $ x) | (x,i) <- zip (M.toList m) ([0..] :: [Int]) ] unpack ms = forAll $ \ i -> Signal (shallow i) (deep i) where mx :: (Size ix) => Matrix ix Integer mx = matrix (Prelude.zipWith (\ _ b -> b) (M.indices mx) [0..]) deep i = D $ Port "o0" $ E $ Entity (Prim "index") [("o0",repType (Witness :: Witness a))] [("i0",GenericTy,Generic (mx ! i)) ,("i1",repType (Witness :: Witness (Matrix ix a)),unD $ deepS ms) ] shallow i = fmap (liftX (M.! i)) (shallowS ms) ---------------------------------------------------------------- -- | a delay is a register with no defined default / initial value. delay :: forall a clk . (Rep a, Clock clk) => Signal clk a -> Signal clk a delay ~(Signal line eline) = res where def = optX $ Nothing -- rep = toRep def res = Signal sres1 (D $ Port ("o0") $ E $ entity) sres0 = line sres1 = S.Cons def sres0 entity = Entity (Prim "delay") [("o0", typeOfS res)] [("i0", typeOfS res, unD eline), ("clk",ClkTy, Pad "clk"), ("rst",B, Pad "rst") ] -- | delays generates a serial sequence of n delays. delays :: forall a clk . (Rep a, Clock clk) => Int -> Signal clk a -> Signal clk a delays n ss = iterate delay ss !! n -- | A register is a state element with a reset. The reset is supplied by the clock domain in the Signal. register :: forall a clk . (Rep a, Clock clk) => a -> Signal clk a -> Signal clk a register first ~(Signal line eline) = res where def = optX $ Just first rep = toRep def res = Signal sres1 (D $ Port ("o0") $ E $ entity) sres0 = line sres1 = S.Cons def sres0 entity = Entity (Prim "register") [("o0", typeOfS res)] [("i0", typeOfS res, unD eline), ("def",GenericTy,Generic (fromRepToInteger rep)), ("clk",ClkTy, Pad "clk"), ("rst",B, Pad "rst") ] -- | registers generates a serial sequence of n registers, all with the same initial value. registers :: forall a clk . (Rep a, Clock clk) => Int -> a -> Signal clk a -> Signal clk a registers n def ss = iterate (register def) ss !! n ----------------------------------------------------------------------------------- -- The 'deep' combinators, used to build the deep part of a signal. entityD :: forall a . (Rep a) => String -> D a entityD nm = D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))] [] entityD1 :: forall a1 a . (Rep a, Rep a1) => String -> D a1 -> D a entityD1 nm (D a1) = D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))] [("i0",repType (Witness :: Witness a1),a1)] entityD2 :: forall a1 a2 a . (Rep a, Rep a1, Rep a2) => String -> D a1 -> D a2 -> D a entityD2 nm (D a1) (D a2) = D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))] [("i0",repType (Witness :: Witness a1),a1) ,("i1",repType (Witness :: Witness a2),a2)] entityD3 :: forall a1 a2 a3 a . (Rep a, Rep a1, Rep a2, Rep a3) => String -> D a1 -> D a2 -> D a3 -> D a entityD3 nm (D a1) (D a2) (D a3) = D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))] [("i0",repType (Witness :: Witness a1),a1) ,("i1",repType (Witness :: Witness a2),a2) ,("i2",repType (Witness :: Witness a3),a3)] pureD :: (Rep a) => a -> D a pureD a = pureXD (pureX a) pureXD :: (Rep a) => X a -> D a pureXD a = D $ Lit $ toRep a
andygill/kansas-lava
Language/KansasLava/Signal.hs
bsd-3-clause
18,502
177
15
5,530
6,300
3,284
3,016
258
1
{-# LANGUAGE MultiParamTypeClasses #-} -- Standard modules. import Control.Monad import Control.Monad.Trans import Data.List import qualified Data.Map as M import Data.Maybe import System.Random -- Modules provided by this library. import Control.Monad.Dist import Control.Monad.Maybe import Control.Monad.Perhaps import Data.Prob -- ======================================================================== -- Spam Filtering -- -- Inspired by <http://www.paulgraham.com/spam.html> and -- <http://www.mathpages.com/home/kmath267.htm>. -- Each message is spam (junk mail) or "ham" (good mail). data MsgType = Spam | Ham deriving (Show, Eq, Enum, Bounded) hasWord :: String -> FDist' MsgType -> FDist' MsgType hasWord word prior = do msgType <- prior wordPresent <- wordPresentIn msgType word condition wordPresent return msgType -- > bayes msgTypePrior -- [Perhaps Spam 64.2%,Perhaps Ham 35.8%] -- > bayes (hasWord "free" msgTypePrior) -- [Perhaps Spam 90.5%,Perhaps Ham 9.5%] wordPresentIn msgType word = boolDist (Prob (n/total)) where wordCounts = findWordCounts word n = entryFor msgType wordCounts total = entryFor msgType msgCounts boolDist :: Prob -> FDist' Bool boolDist (Prob p) = weighted [(True, p), (False, 1-p)] msgCounts = [102, 57] wordCountTable = M.fromList [("free", [57, 6]), -- Lots of words... ("bayes", [1, 10]), ("monad", [0, 22])] entryFor :: Enum a => a -> [b] -> b entryFor x ys = ys !! fromEnum x findWordCounts word = M.findWithDefault [0,0] word wordCountTable msgTypePrior :: Dist d => d MsgType msgTypePrior = weighted (zipWith (,) [Spam,Ham] msgCounts) -- > bayes (hasWord "bayes" msgTypePrior) -- [Perhaps Spam 9.1%,Perhaps Ham 90.9%] hasWords [] prior = prior hasWords (w:ws) prior = do hasWord w (hasWords ws prior) -- > bayes (hasWords ["free","bayes"] msgTypePrior) -- [Perhaps Spam 34.7%,Perhaps Ham 65.3%] uniformAll :: (Dist d,Enum a,Bounded a) => d a uniformAll = uniform allValues allValues :: (Enum a,Bounded a) => [a] allValues = enumFromTo minBound maxBound -- > bayes (uniformAll :: FDist' MsgType) -- [Perhaps Spam 50.0%,Perhaps Ham 50.0%] characteristic f = f uniformAll -- > bayes (characteristic (hasWord "free")) -- [Perhaps Spam 84.1%,Perhaps Ham 15.9%] score f = distance (characteristic f) uniformAll distance :: (Eq a, Enum a, Bounded a) => FDist' a -> FDist' a -> Double distance dist1 dist2 = sum (map (^2) (zipWith (-) ps1 ps2)) where ps1 = vectorFromDist dist1 ps2 = vectorFromDist dist2 vectorFromDist dist = map doubleFromProb (probsFromDist dist) probsFromDist dist = map (\x -> (sumProbs . matching x) (bayes dist)) allValues where matching x = filter ((==x) . perhapsValue) sumProbs = sum . map perhapsProb adjustMinimums xs = map (/ total) adjusted where adjusted = map (max 0.01) xs total = sum adjusted adjustedProbsFromDist dist = adjustMinimums (probsFromDist dist) classifierProbs f = adjustedProbsFromDist (characteristic f) --applyProbs :: (Enum a) => [Prob] -> FDist' a -> FDist' a applyProbs probs prior = do msgType <- prior applyProb (entryFor msgType probs) return msgType -- Will need LaTeX PNG to explain. applyProb :: Prob -> FDist' () applyProb p = do b <- boolDist p condition b -- > bayes (hasWord "free" msgTypePrior) -- [Perhaps Spam 90.5%,Perhaps Ham 9.5%] -- > let probs = classifierProbs (hasWord "free") -- > bayes (applyProbs probs msgTypePrior) -- [Perhaps Spam 90.5%,Perhaps Ham 9.5%] data Classifier = Classifier Double [Prob] deriving Show classifier f = Classifier (score f) (classifierProbs f) applyClassifier (Classifier _ probs) = applyProbs probs instance Eq Classifier where (Classifier s1 _) == (Classifier s2 _) = s1 == s2 instance Ord Classifier where compare (Classifier s1 _) (Classifier s2 _) = compare s2 s1 -- > classifier (hasWord "free") -- Classifier 0.23 [84.1%,15.9%] classifiers :: M.Map String Classifier classifiers = M.mapWithKey toClassifier wordCountTable where toClassifier w _ = classifier (hasWord w) findClassifier :: String -> Maybe Classifier findClassifier w = M.lookup w classifiers findClassifiers n ws = take n (sort classifiers) where classifiers = catMaybes (map findClassifier ws) hasTokens ws prior = foldr applyClassifier prior (findClassifiers 15 ws) -- > bayes (hasTokens ["bayes", "free"] -- msgTypePrior) -- [Perhaps Spam 34.7%,Perhaps Ham 65.3%] -- ======================================================================== -- Robot localization -- -- Example based on "Bayesian Filters for Location Estimation", Fox et al., -- 2005. Available online at: -- -- http://seattle.intel-research.net/people/jhightower/pubs/fox2003bayesian/fox2003bayesian.pdf -- The hallway extends from 0 to 299, and -- it contains three doors. doorAtPosition :: Int -> Bool doorAtPosition pos -- Doors 1, 2 and 3. | 26 <= pos && pos < 58 = True | 82 <= pos && pos < 114 = True | 192 <= pos && pos < 224 = True | otherwise = False localizeRobot :: WPS Int localizeRobot = do -- Pick a random starting location -- to use as a hypothesis. pos1 <- uniform [0..299] -- We know we're at a door. Hypotheses -- which agree with this fact get a -- weight of 1, others get 0. if doorAtPosition pos1 then weight 1 else weight 0 -- Drive forward a bit. let pos2 = pos1 + 28 -- We know we're not at a door. if not (doorAtPosition pos2) then weight 1 else weight 0 -- Drive forward some more. let pos3 = pos2 + 28 if doorAtPosition pos3 then weight 1 else weight 0 -- Our final hypothesis. return pos3 -- > runRand (runWPS localizeRobot 10) -- [Perhaps 106 100.0%, -- never,never,never,never,never, -- Perhaps 93 100.0%, -- never,never,never] -- > runWPS' localizeRobot 10 -- [97,109,93] -- ======================================================================== -- Random sampling -- -- Heavily inspired by Sungwoo Park and colleagues' $\lambda_{\bigcirc}$ -- caculus <http://citeseer.ist.psu.edu/752237.html>. -- -- See <http://www.randomhacks.net/articles/2007/02/21/randomly-sampled-distributions>. histogram :: Ord a => [a] -> [Int] histogram = map length . group . sort -- ======================================================================== -- Particle System newtype PS a = PS { runPS :: Int -> Rand [a] } liftRand :: Rand a -> PS a liftRand r = PS (sample r) instance Functor PS where fmap f ps = PS mapped where mapped n = liftM (map f) (runPS ps n) instance Monad PS where return = liftRand . return ps >>= f = joinPS (fmap f ps) joinPS :: PS (PS a) -> PS a joinPS psps = PS (joinPS' psps) joinPS' :: PS (PS a) -> Int -> Rand [a] joinPS' psps n = do pss <- (runPS psps n) xs <- sequence (map sample1 pss) return (concat xs) -- TODO: Can we base on Rand's join? where sample1 ps = runPS ps 1 instance Dist PS where weighted = liftRand . weighted type WPS = PerhapsT PS instance Dist (PerhapsT PS) where weighted = PerhapsT . weighted . map liftWeighted where liftWeighted (x,w) = (Perhaps x 1,w) weight :: Prob -> WPS () weight p = PerhapsT (return (Perhaps () p)) runWPS wps n = runPS (runPerhapsT wps) n runWPS' wps n = (runRand . liftM catPossible) (runWPS wps n) catPossible (ph:phs) | impossible ph = catPossible phs catPossible (Perhaps x p:phs) = x:(catPossible phs) catPossible [] = []
emk/haskell-probability-monads
examples/Probability.hs
bsd-3-clause
7,598
0
11
1,588
2,033
1,055
978
161
4
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module DB.Schema where import Database.Persist import Data.Time import Data.Aeson (FromJSON, ToJSON) import GHC.Generics (Generic) import Database.Persist.TH import Database.Persist.Postgresql import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader import DB.Config share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| User json email String UniqueEmail email username String UniqueUsername username passwordHash String deriving Show Generic SessionToken json userId UserId token String UniqueToken token expiration UTCTime deriving Show Generic |] doMigrations :: SqlPersistT IO () doMigrations = runMigration migrateAll runDb :: (MonadReader Config m, MonadIO m) => SqlPersistT IO b -> m b runDb query = do pool <- asks getPool liftIO $ runSqlPool query pool
AlexaDeWit/haskellsandboxserver
src/db/Schema.hs
bsd-3-clause
1,356
0
8
310
194
112
82
29
1
{-# LANGUAGE CPP, DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Language.Python.Common.SrcLocation -- Copyright : (c) 2009 Bernie Pope -- License : BSD-style -- Maintainer : bjpop@csse.unimelb.edu.au -- Stability : experimental -- Portability : ghc -- -- Source location information for the Python lexer and parser. This module -- provides single-point locations and spans, and conversions between them. ----------------------------------------------------------------------------- module Language.JavaScript.Parser.SrcLocation ( -- * Construction AlexPosn (..), AlexSpan, alexStartPos, alexSpanEmpty, SrcLocation (..), SrcSpan (..), Span (..), toSrcSpan, spanning, mkSrcSpan, combineSrcSpans, initialSrcLocation, spanStartPoint, -- * Modification incColumn, decColumn, incLine, incTab, -- endCol, -- * Projection of components of a span -- endRow, -- startCol, -- startRow ) where import Data.Data import Prelude hiding (span) -- | `Posn' records the location of a token in the input text. It has three -- fields: the address (number of characters preceding the token), line number -- and column of a token within the file. `start_pos' gives the position of the -- start of the file and `eof_pos' a standard encoding for the end of file. -- `move_pos' calculates the new position after traversing a given character, -- assuming the usual eight character tab stops. data AlexPosn = AlexPn !Int -- address (number of characters preceding the token) !Int -- line number !Int -- column deriving (Eq,Show) alexStartPos :: AlexPosn alexStartPos = AlexPn 0 1 1 -- AZ bringing this in as SrcSpan replacement. type AlexSpan = (AlexPosn, Char, String) alexSpanEmpty :: AlexSpan alexSpanEmpty = (alexStartPos, '\n', "") -- | A location for a syntactic entity from the source code. -- The location is specified by its filename, and starting row -- and column. data SrcLocation = Sloc { sloc_filename :: !String , sloc_address :: {-# UNPACK #-} !Int -- address (number of characters preceding the token) , sloc_row :: {-# UNPACK #-} !Int , sloc_column :: {-# UNPACK #-} !Int } | NoLocation deriving (Eq,Ord,Show,Typeable,Data) {- instance Pretty SrcLocation where pretty = pretty . getSpan -} -- | Types which have a span. class Span a where getSpan :: a -> SrcSpan getSpan _x = SpanEmpty -- | Create a new span which encloses two spanned things. spanning :: (Span a, Span b) => a -> b -> SrcSpan spanning x y = combineSrcSpans (getSpan x) (getSpan y) instance Span a => Span [a] where getSpan [] = SpanEmpty getSpan [x] = getSpan x getSpan list@(x:_xs) = combineSrcSpans (getSpan x) (getSpan (last list)) instance Span a => Span (Maybe a) where getSpan Nothing = SpanEmpty getSpan (Just x) = getSpan x instance (Span a, Span b) => Span (Either a b) where getSpan (Left x) = getSpan x getSpan (Right x) = getSpan x instance (Span a, Span b) => Span (a, b) where getSpan (x,y) = spanning x y instance Span SrcSpan where getSpan = id -- ++AZ++ adding this instance Span AlexPosn where getSpan ap = toSrcSpan (ap,'\n',"") toSrcSpan :: AlexSpan -> SrcSpan toSrcSpan ((AlexPn _addr line col),_,_) = SpanPoint { span_filename = "", span_row = line, span_column = col} -- ++AZ++ end -- | Construct the initial source location for a file. initialSrcLocation :: String -> SrcLocation initialSrcLocation filename = Sloc { sloc_filename = filename , sloc_address = 1 , sloc_row = 1 , sloc_column = 1 } -- | Decrement the column of a location, only if they are on the same row. decColumn :: Int -> SrcLocation -> SrcLocation decColumn n loc | n < col = loc { sloc_column = col - n } | otherwise = loc where col = sloc_column loc -- | Increment the column of a location. incColumn :: Int -> SrcLocation -> SrcLocation incColumn n loc@(Sloc { sloc_column = col }) = loc { sloc_column = col + n } incColumn _ NoLocation = NoLocation -- | Increment the column of a location by one tab stop. incTab :: SrcLocation -> SrcLocation incTab loc@(Sloc { sloc_column = col }) = loc { sloc_column = newCol } where newCol = col + 8 - (col - 1) `mod` 8 incTab NoLocation = NoLocation -- | Increment the line number (row) of a location by one. incLine :: Int -> SrcLocation -> SrcLocation incLine n loc@(Sloc { sloc_row = row }) = loc { sloc_column = 1, sloc_row = row + n } incLine _ NoLocation = NoLocation {- Inspired heavily by compiler/basicTypes/SrcLoc.lhs A SrcSpan delimits a portion of a text file. -} -- | Source location spanning a contiguous section of a file. data SrcSpan -- | A span which starts and ends on the same line. = SpanCoLinear { span_filename :: !String , span_row :: {-# UNPACK #-} !Int , span_start_column :: {-# UNPACK #-} !Int , span_end_column :: {-# UNPACK #-} !Int } -- | A span which starts and ends on different lines. | SpanMultiLine { span_filename :: !String , span_start_row :: {-# UNPACK #-} !Int , span_start_column :: {-# UNPACK #-} !Int , span_end_row :: {-# UNPACK #-} !Int , span_end_column :: {-# UNPACK #-} !Int } -- | A span which is actually just one point in the file. | SpanPoint { span_filename :: !String , span_row :: {-# UNPACK #-} !Int , span_column :: {-# UNPACK #-} !Int } -- | No span information. | SpanEmpty deriving (Eq,Ord,Show,Read,Typeable,Data) {- instance Show SrcSpan where show (s@(SpanCoLinear filename row start end)) = -- showChar '('.showString filename.shows row.shows start.shows end.showChar ')' -- ("foo.txt" 12 4 5) showChar '(' . showChar ')' -- ("foo.txt" 12 4 5) show (s@(SpanMultiLine filename sr sc er ec)) = showChar '('.showString filename.shows sr.shows sc.shows er.shows ec.showChar ')' -- ("foo.txt" 12 4 13 5) show (s@(SpanPoint filename r c)) = showChar '('.showString filename.shows r.shows c.showChar ')' -- ("foo.txt" 12 4) show (SpanEmpty) = showString "()" -- () -} --instance Read SrcSpan where -- readsPrec _ str = [ {- instance Read a => Read Tree a where readsPrec _ str = [(Leave x, t’) | ("Leave", t) <- reads str, (x, t’) <- reads t] ++ [((Node i r d), t’’’) | ("Node", t) <- reads str, (i, t’) <- reads t, (r, t’’) <- reads t’, (d, t’’’) <- reads t’’] -} instance Span SrcLocation where getSpan loc@(Sloc {}) = SpanPoint { span_filename = sloc_filename loc , span_row = sloc_row loc , span_column = sloc_column loc } getSpan NoLocation = SpanEmpty -- | Make a point span from the start of a span spanStartPoint :: SrcSpan -> SrcSpan spanStartPoint SpanEmpty = SpanEmpty spanStartPoint span = SpanPoint { span_filename = span_filename span , span_row = startRow span , span_column = startCol span } -- | Make a span from two locations. Assumption: either the -- arguments are the same, or the left one preceeds the right one. mkSrcSpan :: SrcLocation -> SrcLocation -> SrcSpan mkSrcSpan NoLocation _ = SpanEmpty mkSrcSpan _ NoLocation = SpanEmpty mkSrcSpan loc1 loc2 | line1 == line2 = if col2 <= col1 then SpanPoint file line1 col1 else SpanCoLinear file line1 col1 col2 | otherwise = SpanMultiLine file line1 col1 line2 col2 where line1 = sloc_row loc1 line2 = sloc_row loc2 col1 = sloc_column loc1 col2 = sloc_column loc2 file = sloc_filename loc1 -- | Combines two 'SrcSpan' into one that spans at least all the characters -- within both spans. Assumes the "file" part is the same in both inputs combineSrcSpans :: SrcSpan -> SrcSpan -> SrcSpan combineSrcSpans SpanEmpty r = r -- this seems more useful combineSrcSpans l SpanEmpty = l combineSrcSpans start end = case row1 `compare` row2 of EQ -> case col1 `compare` col2 of EQ -> SpanPoint file row1 col1 LT -> SpanCoLinear file row1 col1 col2 GT -> SpanCoLinear file row1 col2 col1 LT -> SpanMultiLine file row1 col1 row2 col2 GT -> SpanMultiLine file row2 col2 row1 col1 where row1 = startRow start col1 = startCol start row2 = endRow end col2 = endCol end file = span_filename start -- | Get the row of the start of a span. startRow :: SrcSpan -> Int startRow (SpanCoLinear { span_row = row }) = row startRow (SpanMultiLine { span_start_row = row }) = row startRow (SpanPoint { span_row = row }) = row startRow SpanEmpty = error "startRow called on empty span" -- | Get the row of the end of a span. endRow :: SrcSpan -> Int endRow (SpanCoLinear { span_row = row }) = row endRow (SpanMultiLine { span_end_row = row }) = row endRow (SpanPoint { span_row = row }) = row endRow SpanEmpty = error "endRow called on empty span" -- | Get the column of the start of a span. startCol :: SrcSpan -> Int startCol (SpanCoLinear { span_start_column = col }) = col startCol (SpanMultiLine { span_start_column = col }) = col startCol (SpanPoint { span_column = col }) = col startCol SpanEmpty = error "startCol called on empty span" -- | Get the column of the end of a span. endCol :: SrcSpan -> Int endCol (SpanCoLinear { span_end_column = col }) = col endCol (SpanMultiLine { span_end_column = col }) = col endCol (SpanPoint { span_column = col }) = col endCol SpanEmpty = error "endCol called on empty span"
jb55/language-javascript
src/Language/JavaScript/Parser/SrcLocation.hs
bsd-3-clause
9,900
0
11
2,494
1,939
1,081
858
182
5
module Data.Name.Iso where import Data.Name import Control.Lens import qualified Language.Haskell.TH as TH nameIso :: Iso String String (Maybe Name) Name nameIso = iso nameMay unName -- | unsafe -- >>> "hello" ^. nameIso' -- hello nameIso' :: Iso' String Name nameIso' = iso toName unName -- | there are lack of info a little thNameIso :: Iso' Name TH.Name thNameIso = iso (TH.mkName . unName) (toName . show)
kmyk/proof-haskell
Data/Name/Iso.hs
mit
414
0
8
72
118
67
51
10
1
module Model ( AgentId , SugAgentState (..) , SugAgentObservable (..) , SugEnvCellOccupier (..) , SugEnvCell (..) , SugEnvironment , SugContext (..) , SugAgent , SugAgentMonad , SugAgentIn (..) , SugAgentOut (..) , nextAgentId , getEnvironment , (<Β°>) , sugarGrowbackUnits , sugarCapacityRange , sugarEndowmentRange , sugarEndowmentRangeStandard , sugarMetabolismRange , visionRange , visionRangeStandard ) where import Control.Monad.Random import Control.Monad.Reader import Control.Concurrent.STM import FRP.BearRiver import Discrete ------------------------------------------------------------------------------------------------------------------------ -- DOMAIN-SPECIFIC AGENT-DEFINITIONS ------------------------------------------------------------------------------------------------------------------------ type AgentId = Int data SugAgentState = SugAgentState { sugAgCoord :: Discrete2dCoord , sugAgSugarMetab :: Double -- this amount of sugar will be consumed by the agent in each time-step , sugAgVision :: Int -- the vision of the agent: strongly depends on the type of the environment: Int because its 2d discrete , sugAgSugarLevel :: Double -- the current sugar holdings of the agent, if 0 then the agent starves to death , sugAgSugarInit :: Double -- agent is fertile only when its sugarlevel is GE than its initial endowment } deriving (Show) data SugAgentObservable = SugAgentObservable { sugObsCoord :: Discrete2dCoord , sugObsVision :: Int } deriving (Show) data SugEnvCellOccupier = SugEnvCellOccupier { sugEnvOccId :: AgentId , sugEnvOccWealth :: Double } deriving (Show) data SugEnvCell = SugEnvCell { sugEnvSugarCapacity :: Double , sugEnvSugarLevel :: Double , sugEnvOccupier :: Maybe SugEnvCellOccupier } deriving (Show) type SugEnvironment = Discrete2d SugEnvCell data SugAgentIn = SugAgentIn data SugAgentOut g = SugAgentOut { sugAoKill :: !(Event ()) , sugAoNew :: ![(AgentId, SugAgent g)] , sugAoObservable :: !(Maybe SugAgentObservable) } data SugContext = SugContext { sugCtxEnv :: SugEnvironment , sugCtxNextAid :: TVar AgentId } type SugAgentMonad g = ReaderT SugContext (RandT g STM) type SugAgent g = SF (SugAgentMonad g) SugAgentIn (SugAgentOut g) nextAgentId :: RandomGen g => (SugAgentMonad g) AgentId nextAgentId = do ctx <- ask let aidVar = sugCtxNextAid ctx aid <- lift $ lift $ readTVar aidVar _ <- lift $ lift $ writeTVar aidVar (aid + 1) return aid getEnvironment :: RandomGen g => (SugAgentMonad g) SugEnvironment getEnvironment = do ctx <- ask return $ sugCtxEnv ctx (<Β°>) :: SugAgentOut g -> SugAgentOut g -> SugAgentOut g (<Β°>) ao1 ao2 = SugAgentOut { sugAoKill = mergeBy (\_ _ -> ()) (sugAoKill ao1) (sugAoKill ao2) , sugAoNew = sugAoNew ao1 ++ sugAoNew ao2 , sugAoObservable = decideMaybe (sugAoObservable ao1) (sugAoObservable ao2) } where decideMaybe :: Maybe a -> Maybe a -> Maybe a decideMaybe Nothing Nothing = Nothing decideMaybe (Just a) Nothing = Just a decideMaybe Nothing (Just a) = Just a decideMaybe _ _ = error "Can't decide between two Maybes" ------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------ -- CHAPTER II: Life And Death On The Sugarscape ------------------------------------------------------------------------------------------------------------------------ -- NOTE: < 0 is treated as grow back to max sugarGrowbackUnits :: Double sugarGrowbackUnits = 1.0 sugarCapacityRange :: (Double, Double) sugarCapacityRange = (0.0, 4.0) sugarEndowmentRange :: (Double, Double) sugarEndowmentRange = sugarEndowmentRangeStandard -- NOTE: this is specified in book page 33 where the initial endowments are set to 5-25 sugarEndowmentRangeStandard :: (Double, Double) sugarEndowmentRangeStandard = (5.0, 25.0) sugarMetabolismRange :: (Double, Double) sugarMetabolismRange = (1.0, 5.0) visionRange :: (Int, Int) visionRange = visionRangeStandard -- NOTE: set to 1-6 on page 24 visionRangeStandard :: (Int, Int) visionRangeStandard = (1, 6)
thalerjonathan/phd
thesis/code/concurrent/sugarscape/SugarScapeSTMTArray/src/Model.hs
gpl-3.0
4,511
0
12
941
895
515
380
107
4
{- Copyright 2019 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. -} {-| Snap helper functions -} module CodeWorld.Auth.Util ( getRequiredParam , hoistEither , hoistMaybe , m , withSnapExcept ) where import CodeWorld.Auth.Http import CodeWorld.Auth.Types import Control.Monad.Trans.Except (ExceptT(..), runExceptT, throwE) import Data.ByteString (ByteString) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap (fromList) import Snap.Core (Snap, finishWith, getParam) getRequiredParam :: ByteString -> Snap ByteString getRequiredParam name = do mbValue <- getParam name case mbValue of Nothing -> finishWith badRequest400 Just value -> return value m :: [(String, String)] -> HashMap String String m = HashMap.fromList hoistMaybe :: Monad m => e -> Maybe a -> ExceptT e m a hoistMaybe e mb = maybe (throwE e) return mb hoistEither :: Monad m => Either e a -> ExceptT e m a hoistEither = ExceptT . return withSnapExcept :: SnapExcept a withSnapExcept action = runExceptT action >>= either id return
alphalambda/codeworld
codeworld-auth/src/CodeWorld/Auth/Util.hs
apache-2.0
1,685
0
10
364
317
173
144
27
2
{-| Module : Base Description : Base/radix module for the MPL DSL Copyright : (c) Rohit Jha, 2015 License : BSD2 Maintainer : rohit305jha@gmail.com Stability : Stable Functionality for: * Converting decimal numbers to binary, octal, hexadecimal or any other base/radix * Converting numbers from binary, octal, hexadecimal or any other base/radix to decimal base/radix -} module Base ( toBase, toBin, toOct, toDec, toHex, fromBase, fromBin, fromOct, fromDec, fromHex, toAlpha, fromAlpha ) where import Data.List import Data.Char {-| The 'toBase' function converts a number from decimal base to a specified base in the form of digits. The function takes two arguments, both of type Integer. Below are a few examples: >>> toBase 8 37 [4,5] >>> toBase 100 233243 [23,32,43] >>> toBase 9 233243 [3,8,4,8,4,8] >>> toBase 35 233243 [5,15,14,3] -} toBase :: Integer -> Integer -> [Integer] toBase b v = toBase' [] v where toBase' a 0 = a toBase' a v = toBase' (r:a) q where (q,r) = v `divMod` b {-| The 'toBin' function converts a decimal number to its binary equivalent. The function takes one argument of type Integer, which is the decimal number. Below are a few examples: >>> toBin 11 [1,0,1,1] >>> toBin 32 [1,0,0,0,0,0] >>> toBin (3^(-1)) *** Exception: Negative exponent -} toBin :: Integer -> [Integer] toBin = toBase 2 {-| The 'toOct' function converts a decimal number to its octal equivalent. The function takes one argument of type Integer, which is the decimal number. Below are a few examples: >>> toOct 11 [1,3] >>> toOct 100 [1,4,4] -} toOct :: Integer -> [Integer] toOct = toBase 8 {-| The 'toDec' function converts a decimal number to its decimal equivalent. The function returns a list of digits of the decimal number. The function takes one argument of type Integer, which is the decimal number. Below are a few examples: >>> toDec 15 [1,5] >>> toDec 123 [1,2,3] -} toDec :: Integer -> [Integer] toDec = toBase 10 {-| The 'toHex' function converts a decimal number to its hexadecimal equivalent. The function takes one argument of type Integer, which is the decimal number. Below are a few examples: >>> toHex 15 [15] >>> toHex 1200 [4,11,0] -} toHex :: Integer -> [Integer] toHex = toBase 16 {-| The 'fromBase' function converts a number from a specified base to decimal in the form of a list of digits. The function takes two arguments, the first of type Integer and the second of type [Integer]. Below are a few examples: >>> fromBase 16 [15,15,15] 4095 >>> fromBase 100 [21,12,1] 211201 >>> fromBase 2 [1,0,1] 5 -} fromBase :: Integer -> [Integer] -> Integer fromBase b ds = foldl' (\n k -> n * b + k) 0 ds {-| The 'fromBin' function converts a number from binary (in the form of a list of digits) to decimal. The function takes two arguments, the first of type Integer and the second of type [Integer]. Below are a few examples: >>> fromBin [1,0,1,0] 10 >>> fromBin (toBin 12345) 12345 -} fromBin :: [Integer] -> Integer fromBin = fromBase 2 {-| The 'fromOct' function converts a number from octal (in the form of a list of digits) to decimal. The function takes two arguments, the first of type Integer and the second of type [Integer]. Below are a few examples: >>> fromOct [6,3,7] 415 >>> fromOct (toOct 1234) 1234 -} fromOct :: [Integer] -> Integer fromOct = fromBase 8 {-| The 'fromDec' function converts a number from decimal (in the form of a list of digits) to decimal. The function takes two arguments, the first of type Integer and the second of type [Integer]. Below are a few examples: >>> fromDec [1,5,8,2,2] 15822 >>> fromDec (toDec 635465) 635465 -} fromDec :: [Integer] -> Integer fromDec = fromBase 10 {-| The 'fromHex' function converts a number from hexadecimal (in the form of a list of digits) to decimal. The function takes two arguments, the first of type Integer and the second of type [Integer]. Below are a few examples: >>> fromHex [14,15,8,2,0] 981024 >>> fromHex (toHex 0234) 234 -} fromHex :: [Integer] -> Integer fromHex = fromBase 16 {-| The 'toAlpha' function converts a number from a list of Integer to corresponding String representation. The function takes one argument of type [Integer], which contains the list of digits. Below are a few examples: >>> toAlpha $ toBase 16 23432 "5b88" >>> toAlpha $ toBase 16 255 "ff" >>> toAlpha [38,12,1] "}c1" >>> toAlpha [21,12,1] "lc1" -} toAlpha :: [Integer] -> String toAlpha = map convert where convert n | n < 10 = chr (fromInteger n + ord '0') | otherwise = chr (fromInteger n + ord 'a' - 10) {-| The 'from AlphaDigits' function converts a String to list of Integer digits. The function takes only one argument of type String. Below are a few examples: >>> fromAlpha "j43hbrh" [19,4,3,17,11,27,17] >>> fromAlpha "ffff" [15,15,15,15] -} fromAlpha :: String -> [Integer] fromAlpha = map convert where convert c | isDigit c = toInteger (ord c - ord '0') | isUpper c = toInteger (ord c - ord 'A' + 10) | isLower c = toInteger (ord c - ord 'a' + 10)
rohitjha/DiMPL
src/Base.hs
bsd-2-clause
5,416
0
12
1,337
567
302
265
47
2
{-# LANGUAGE ScopedTypeVariables #-} module Properties.Layout.Tall where import Test.QuickCheck import Instances import Utils import XMonad.StackSet hiding (filter) import XMonad.Core import XMonad.Layout import Graphics.X11.Xlib.Types (Rectangle(..)) import Data.Maybe import Data.List (sort) import Data.Ratio ------------------------------------------------------------------------ -- The Tall layout -- 1 window should always be tiled fullscreen prop_tile_fullscreen rect = tile pct rect 1 1 == [rect] where pct = 1/2 -- multiple windows prop_tile_non_overlap rect windows nmaster = noOverlaps (tile pct rect nmaster windows) where _ = rect :: Rectangle pct = 3 % 100 -- splitting horizontally yields sensible results prop_split_horizontal (NonNegative n) x = (noOverflows (+) (rect_x x) (rect_width x)) ==> sum (map rect_width xs) == rect_width x && all (== rect_height x) (map rect_height xs) && (map rect_x xs) == (sort $ map rect_x xs) where xs = splitHorizontally n x -- splitting vertically yields sensible results prop_split_vertical (r :: Rational) x = rect_x x == rect_x a && rect_x x == rect_x b && rect_width x == rect_width a && rect_width x == rect_width b where (a,b) = splitVerticallyBy r x -- pureLayout works. prop_purelayout_tall n r1 r2 rect = do x <- (arbitrary :: Gen T) `suchThat` (isJust . peek) let layout = Tall n r1 r2 st = fromJust . stack . workspace . current $ x ts = pureLayout layout rect st return $ length ts == length (index x) && noOverlaps (map snd ts) && description layout == "Tall" -- Test message handling of Tall -- what happens when we send a Shrink message to Tall prop_shrink_tall (NonNegative n) (NonZero (NonNegative delta)) (NonNegative frac) = n == n' && delta == delta' -- these state components are unchanged && frac' <= frac && (if frac' < frac then frac' == 0 || frac' == frac - delta else frac == 0 ) -- remaining fraction should shrink where l1 = Tall n delta frac Just l2@(Tall n' delta' frac') = l1 `pureMessage` (SomeMessage Shrink) -- pureMessage :: layout a -> SomeMessage -> Maybe (layout a) -- what happens when we send a Shrink message to Tall prop_expand_tall (NonNegative n) (NonZero (NonNegative delta)) (NonNegative n1) (NonZero (NonNegative d1)) = n == n' && delta == delta' -- these state components are unchanged && frac' >= frac && (if frac' > frac then frac' == 1 || frac' == frac + delta else frac == 1 ) -- remaining fraction should shrink where frac = min 1 (n1 % d1) l1 = Tall n delta frac Just l2@(Tall n' delta' frac') = l1 `pureMessage` (SomeMessage Expand) -- pureMessage :: layout a -> SomeMessage -> Maybe (layout a) -- what happens when we send an IncMaster message to Tall prop_incmaster_tall (NonNegative n) (NonZero (NonNegative delta)) (NonNegative frac) (NonNegative k) = delta == delta' && frac == frac' && n' == n + k where l1 = Tall n delta frac Just l2@(Tall n' delta' frac') = l1 `pureMessage` (SomeMessage (IncMasterN k)) -- pureMessage :: layout a -> SomeMessage -> Maybe (layout a) -- toMessage LT = SomeMessage Shrink -- toMessage EQ = SomeMessage Expand -- toMessage GT = SomeMessage (IncMasterN 1) prop_desc_mirror n r1 r2 = description (Mirror $! t) == "Mirror Tall" where t = Tall n r1 r2
Happy-Ferret/xmonad
tests/Properties/Layout/Tall.hs
bsd-3-clause
3,761
0
13
1,100
1,013
531
482
67
2
{-| Module : Fit Copyright : Copyright 2014-2015, Matt Giles License : Modified BSD License Maintainer : matt.w.giles@gmail.com Stability : experimental -} module Fit ( -- * Messages API -- $messages readMessages, readFileMessages, parseMessages, Messages(..), Message(..), Field(..), Value(..), SingletonValue(..), ArrayValue(..), -- ** Lenses for the Messages API messages, message, messageNumber, fields, field, fieldNumber, fieldValue, int, real, text, byte, ints, reals, bytestring ) where import Fit.Messages import Fit.Messages.Lens -- $messages -- A high-level view of a FIT file as a sequence of data messages. This is the -- recommended API for pulling information out of a FIT file, but if you need -- access to the exact structure of the file you can use the API in "Fit.Internal.FitFile" and "Fit.Internal.Parse". -- -- Some basic lenses are also provided for working with the Messages API. These -- can make it much easier to extract information from a FIT file, especially -- since you usually know what sort of data you're expecting to find. -- -- For example, from the FIT global profile we can find that the global message -- number for 'record' messages is 20, and within a `record` message the 'speed' -- field has field number 6. The following code gets the `speed` field from all -- 'record' messages in the file: -- -- @ -- Right fit <- readFileMessages "file.fit" -- let speeds = fit ^.. message 20 . field 6 . int -- -- speeds :: [Int] -- @ -- -- Note that this package doesn't provide any lens combinators (like @(^..)@), -- so you'll need to use ones from a lens package.
bitemyapp/fit
src/Fit.hs
bsd-3-clause
1,671
0
5
337
136
101
35
26
0
module Data.Tiled ( module X , module Data.Tiled ) where import Data.Tiled.Load as X import Data.Tiled.Types as X import Data.Vector (Vector, force, slice) -- | Yield a slice of the tile vectors without copying it. -- -- The vectors must be at least x+w wide and y+h tall. sliceTileVectors :: Int -- ^ X -> Int -- ^ Y -> Int -- ^ Width -> Int -- ^ Height -> Vector (Vector (Maybe TileIndex)) -> Vector (Vector (Maybe TileIndex)) sliceTileVectors x y w h = (slice x w <$>) . slice y h -- | Yield the argument but force it not to retain any extra memory, -- possibly by copying it. -- -- Useful after slicing huge tile vectors. forceTileVectors :: Vector (Vector (Maybe TileIndex)) -> Vector (Vector (Maybe TileIndex)) forceTileVectors = force . fmap force
chrra/htiled
src/Data/Tiled.hs
bsd-3-clause
822
0
14
204
199
113
86
18
1
{-# LANGUAGE FlexibleInstances #-} module Kalium.Nucleus.Vector.Show where import Kalium.Prelude import Kalium.Nucleus.Vector.Program deriving instance Show NameSpecial deriving instance Show Literal instance Show Name where show = \case NameSpecial op -> show op NameGen n -> "_" ++ show n instance Show Expression where show = \case AppOp2 OpPair x y -> "(" ++ show x ++ "," ++ show y ++ ")" Access name -> show name Primary lit -> show lit Lambda p a -> "(Ξ»" ++ show p ++ "." ++ show a ++ ")" Beta a b -> show a ++ "(" ++ show b ++ ")" Ext ext -> absurd ext instance Show Pattern where show = \case PUnit -> "()" PWildCard -> "_" PAccess name _ -> show name PTuple p1 p2 -> "(" ++ show p1 ++ "," ++ show p2 ++ ")" PExt pext -> absurd pext deriving instance Show Type deriving instance Show Func deriving instance Show Program
rscprof/kalium
src/Kalium/Nucleus/Vector/Show.hs
bsd-3-clause
952
0
13
277
338
162
176
-1
-1
module Data.IP.Op where import Data.Bits import Data.IP.Addr import Data.IP.Mask import Data.IP.Range ---------------------------------------------------------------- {-| >>> toIPv4 [127,0,2,1] `masked` intToMask 7 126.0.0.0 -} class Eq a => Addr a where {-| The 'masked' function takes an 'Addr' and a contiguous mask and returned a masked 'Addr'. -} masked :: a -> a -> a {-| The 'intToMask' function takes an 'Int' representing the number of bits to be set in the returned contiguous mask. When this integer is positive the bits will be starting from the MSB and from the LSB otherwise. >>> intToMask 16 :: IPv4 255.255.0.0 >>> intToMask (-16) :: IPv4 0.0.255.255 >>> intToMask 16 :: IPv6 ffff:: >>> intToMask (-16) :: IPv6 ::ffff -} intToMask :: Int -> a instance Addr IPv4 where masked = maskedIPv4 intToMask = maskIPv4 instance Addr IPv6 where masked = maskedIPv6 intToMask = maskIPv6 ---------------------------------------------------------------- {-| The >:> operator takes two 'AddrRange'. It returns 'True' if the first 'AddrRange' contains the second 'AddrRange'. Otherwise, it returns 'False'. >>> makeAddrRange ("127.0.2.1" :: IPv4) 8 >:> makeAddrRange "127.0.2.1" 24 True >>> makeAddrRange ("127.0.2.1" :: IPv4) 24 >:> makeAddrRange "127.0.2.1" 8 False >>> makeAddrRange ("2001:DB8::1" :: IPv6) 16 >:> makeAddrRange "2001:DB8::1" 32 True >>> makeAddrRange ("2001:DB8::1" :: IPv6) 32 >:> makeAddrRange "2001:DB8::1" 16 False -} (>:>) :: Addr a => AddrRange a -> AddrRange a -> Bool a >:> b = mlen a <= mlen b && (addr b `masked` mask a) == addr a {-| The 'toMatchedTo' function take an 'Addr' address and an 'AddrRange', and returns 'True' if the range contains the address. >>> ("127.0.2.0" :: IPv4) `isMatchedTo` makeAddrRange "127.0.2.1" 24 True >>> ("127.0.2.0" :: IPv4) `isMatchedTo` makeAddrRange "127.0.2.1" 32 False >>> ("2001:DB8::1" :: IPv6) `isMatchedTo` makeAddrRange "2001:DB8::1" 32 True >>> ("2001:DB8::" :: IPv6) `isMatchedTo` makeAddrRange "2001:DB8::1" 128 False -} isMatchedTo :: Addr a => a -> AddrRange a -> Bool isMatchedTo a r = a `masked` mask r == addr r {-| The 'makeAddrRange' functions takes an 'Addr' address and a mask length. It creates a bit mask from the mask length and masks the 'Addr' address, then returns 'AddrRange' made of them. >>> makeAddrRange (toIPv4 [127,0,2,1]) 8 127.0.0.0/8 >>> makeAddrRange (toIPv6 [0x2001,0xDB8,0,0,0,0,0,1]) 8 2000::/8 -} makeAddrRange :: Addr a => a -> Int -> AddrRange a makeAddrRange ad len = AddrRange adr msk len where msk = intToMask len adr = ad `masked` msk -- | Convert IPv4 range to IPV4-embedded-in-IPV6 range ipv4RangeToIPv6 :: AddrRange IPv4 -> AddrRange IPv6 ipv4RangeToIPv6 range = makeAddrRange (toIPv6 [0,0,0,0,0,0xffff, (i1 `shift` 8) .|. i2, (i3 `shift` 8) .|. i4]) (masklen + 96) where (ip, masklen) = addrRangePair range [i1,i2,i3,i4] = fromIPv4 ip {-| The 'unmakeAddrRange' functions take a 'AddrRange' and returns the network address and a mask length. >>> addrRangePair ("127.0.0.0/8" :: AddrRange IPv4) (127.0.0.0,8) >>> addrRangePair ("2000::/8" :: AddrRange IPv6) (2000::,8) -} addrRangePair :: Addr a => AddrRange a -> (a, Int) addrRangePair (AddrRange adr _ len) = (adr, len)
greydot/iproute
Data/IP/Op.hs
bsd-3-clause
3,378
0
11
675
477
259
218
29
1
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "Control/Concurrent/STM/TBQueue.hs" #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# LANGUAGE CPP, DeriveDataTypeable #-} {-# LANGUAGE Trustworthy #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent.STM.TBQueue -- Copyright : (c) The University of Glasgow 2012 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (requires STM) -- -- 'TBQueue' is a bounded version of 'TQueue'. The queue has a maximum -- capacity set when it is created. If the queue already contains the -- maximum number of elements, then 'writeTBQueue' blocks until an -- element is removed from the queue. -- -- The implementation is based on the traditional purely-functional -- queue representation that uses two lists to obtain amortised /O(1)/ -- enqueue and dequeue operations. -- -- @since 2.4 ----------------------------------------------------------------------------- module Control.Concurrent.STM.TBQueue ( -- * TBQueue TBQueue, newTBQueue, newTBQueueIO, readTBQueue, tryReadTBQueue, peekTBQueue, tryPeekTBQueue, writeTBQueue, unGetTBQueue, isEmptyTBQueue, isFullTBQueue, ) where import Data.Typeable import GHC.Conc -- | 'TBQueue' is an abstract type representing a bounded FIFO channel. -- -- @since 2.4 data TBQueue a = TBQueue {-# UNPACK #-} !(TVar Int) -- CR: read capacity {-# UNPACK #-} !(TVar [a]) -- R: elements waiting to be read {-# UNPACK #-} !(TVar Int) -- CW: write capacity {-# UNPACK #-} !(TVar [a]) -- W: elements written (head is most recent) deriving Typeable instance Eq (TBQueue a) where TBQueue a _ _ _ == TBQueue b _ _ _ = a == b -- Total channel capacity remaining is CR + CW. Reads only need to -- access CR, writes usually need to access only CW but sometimes need -- CR. So in the common case we avoid contention between CR and CW. -- -- - when removing an element from R: -- CR := CR + 1 -- -- - when adding an element to W: -- if CW is non-zero -- then CW := CW - 1 -- then if CR is non-zero -- then CW := CR - 1; CR := 0 -- else **FULL** -- |Build and returns a new instance of 'TBQueue' newTBQueue :: Int -- ^ maximum number of elements the queue can hold -> STM (TBQueue a) newTBQueue size = do read <- newTVar [] write <- newTVar [] rsize <- newTVar 0 wsize <- newTVar size return (TBQueue rsize read wsize write) -- |@IO@ version of 'newTBQueue'. This is useful for creating top-level -- 'TBQueue's using 'System.IO.Unsafe.unsafePerformIO', because using -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't -- possible. newTBQueueIO :: Int -> IO (TBQueue a) newTBQueueIO size = do read <- newTVarIO [] write <- newTVarIO [] rsize <- newTVarIO 0 wsize <- newTVarIO size return (TBQueue rsize read wsize write) -- |Write a value to a 'TBQueue'; blocks if the queue is full. writeTBQueue :: TBQueue a -> a -> STM () writeTBQueue (TBQueue rsize _read wsize write) a = do w <- readTVar wsize if (w /= 0) then do writeTVar wsize (w - 1) else do r <- readTVar rsize if (r /= 0) then do writeTVar rsize 0 writeTVar wsize (r - 1) else retry listend <- readTVar write writeTVar write (a:listend) -- |Read the next value from the 'TBQueue'. readTBQueue :: TBQueue a -> STM a readTBQueue (TBQueue rsize read _wsize write) = do xs <- readTVar read r <- readTVar rsize writeTVar rsize (r + 1) case xs of (x:xs') -> do writeTVar read xs' return x [] -> do ys <- readTVar write case ys of [] -> retry _ -> do let (z:zs) = reverse ys -- NB. lazy: we want the transaction to be -- short, otherwise it will conflict writeTVar write [] writeTVar read zs return z -- | A version of 'readTBQueue' which does not retry. Instead it -- returns @Nothing@ if no value is available. tryReadTBQueue :: TBQueue a -> STM (Maybe a) tryReadTBQueue c = fmap Just (readTBQueue c) `orElse` return Nothing -- | Get the next value from the @TBQueue@ without removing it, -- retrying if the channel is empty. peekTBQueue :: TBQueue a -> STM a peekTBQueue c = do x <- readTBQueue c unGetTBQueue c x return x -- | A version of 'peekTBQueue' which does not retry. Instead it -- returns @Nothing@ if no value is available. tryPeekTBQueue :: TBQueue a -> STM (Maybe a) tryPeekTBQueue c = do m <- tryReadTBQueue c case m of Nothing -> return Nothing Just x -> do unGetTBQueue c x return m -- |Put a data item back onto a channel, where it will be the next item read. -- Blocks if the queue is full. unGetTBQueue :: TBQueue a -> a -> STM () unGetTBQueue (TBQueue rsize read wsize _write) a = do r <- readTVar rsize if (r > 0) then do writeTVar rsize (r - 1) else do w <- readTVar wsize if (w > 0) then writeTVar wsize (w - 1) else retry xs <- readTVar read writeTVar read (a:xs) -- |Returns 'True' if the supplied 'TBQueue' is empty. isEmptyTBQueue :: TBQueue a -> STM Bool isEmptyTBQueue (TBQueue _rsize read _wsize write) = do xs <- readTVar read case xs of (_:_) -> return False [] -> do ys <- readTVar write case ys of [] -> return True _ -> return False -- |Returns 'True' if the supplied 'TBQueue' is full. -- -- @since 2.4.3 isFullTBQueue :: TBQueue a -> STM Bool isFullTBQueue (TBQueue rsize _read wsize _write) = do w <- readTVar wsize if (w > 0) then return False else do r <- readTVar rsize if (r > 0) then return False else return True
phischu/fragnix
tests/packages/scotty/Control.Concurrent.STM.TBQueue.hs
bsd-3-clause
6,106
0
21
1,692
1,290
647
643
119
3
{-# LANGUAGE OverloadedStrings #-} -- Module : Network.AWS.Internal.Log -- Copyright : (c) 2013-2015 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- | Types and functions for optional logging machinery used during the -- request, response, and signing life-cycles. module Network.AWS.Internal.Log where import Control.Monad import Control.Monad.IO.Class import Data.ByteString.Builder import Data.Monoid import Network.AWS.Data import Network.AWS.Types import System.IO -- | This is a primitive logger which can be used to log messages to a 'Handle'. -- A more sophisticated logging library such as tinylog or FastLogger should be -- used in production code. newLogger :: MonadIO m => LogLevel -> Handle -> m Logger newLogger x hd = liftIO $ do hSetBinaryMode hd True hSetBuffering hd LineBuffering return $ \y b -> when (x >= y) $ hPutBuilder hd (b <> "\n") info :: (MonadIO m, ToBuilder a) => Logger -> a -> m () info f = liftIO . f Info . build {-# INLINE info #-} debug :: (MonadIO m, ToBuilder a) => Logger -> a -> m () debug f = liftIO . f Debug . build {-# INLINE debug #-} trace :: (MonadIO m, ToBuilder a) => Logger -> a -> m () trace f = liftIO . f Trace . build {-# INLINE trace #-}
romanb/amazonka
amazonka/src/Network/AWS/Internal/Log.hs
mpl-2.0
1,623
0
13
356
315
172
143
25
1
{-# LANGUAGE CPP #-} -- | Groups black-box tests of cabal-install and configures them to test -- the correct binary. -- -- This file should do nothing but import tests from other modules and run -- them with the path to the correct cabal-install binary. module Main where -- Modules from Cabal. import Distribution.Compat.CreatePipe (createPipe) import Distribution.Compat.Environment (setEnv) import Distribution.Compat.Internal.TempFile (createTempDirectory) import Distribution.Simple.Configure (findDistPrefOrDefault) import Distribution.Simple.Program.Builtin (ghcPkgProgram) import Distribution.Simple.Program.Db (defaultProgramDb, requireProgram, setProgramSearchPath) import Distribution.Simple.Program.Find (ProgramSearchPathEntry(ProgramSearchPathDir), defaultProgramSearchPath) import Distribution.Simple.Program.Types ( Program(..), simpleProgram, programPath) import Distribution.Simple.Setup ( Flag(..) ) import Distribution.Simple.Utils ( findProgramVersion, copyDirectoryRecursive ) import Distribution.Verbosity (normal) -- Third party modules. import Control.Concurrent.Async (withAsync, wait) import Control.Exception (bracket) import Data.Maybe (fromMaybe) import System.Directory ( canonicalizePath , findExecutable , getDirectoryContents , getTemporaryDirectory , doesDirectoryExist , removeDirectoryRecursive , doesFileExist ) import System.FilePath import Test.Tasty (TestTree, defaultMain, testGroup) import Test.Tasty.HUnit (testCase, Assertion, assertFailure) import Control.Monad ( filterM, forM, unless, when ) import Data.List (isPrefixOf, isSuffixOf, sort) import Data.IORef (newIORef, writeIORef, readIORef) import System.Exit (ExitCode(..)) import System.IO (withBinaryFile, IOMode(ReadMode)) import System.Process (runProcess, waitForProcess) import Text.Regex.Posix ((=~)) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C8 import Data.ByteString (ByteString) #if MIN_VERSION_base(4,6,0) import System.Environment ( getExecutablePath ) #endif -- | Test case. data TestCase = TestCase { tcName :: String -- ^ Name of the shell script , tcBaseDirectory :: FilePath , tcCategory :: String , tcShouldX :: String , tcStdOutPath :: Maybe FilePath -- ^ File path of "golden standard output" , tcStdErrPath :: Maybe FilePath -- ^ File path of "golden standard error" } -- | Test result. data TestResult = TestResult { trExitCode :: ExitCode , trStdOut :: ByteString , trStdErr :: ByteString , trWorkingDirectory :: FilePath } -- | Cabal executable cabalProgram :: Program cabalProgram = (simpleProgram "cabal") { programFindVersion = findProgramVersion "--numeric-version" id } -- | Convert test result to string. testResultToString :: TestResult -> String testResultToString testResult = exitStatus ++ "\n" ++ workingDirectory ++ "\n\n" ++ stdOut ++ "\n\n" ++ stdErr where exitStatus = "Exit status: " ++ show (trExitCode testResult) workingDirectory = "Working directory: " ++ (trWorkingDirectory testResult) stdOut = "<stdout> was:\n" ++ C8.unpack (trStdOut testResult) stdErr = "<stderr> was:\n" ++ C8.unpack (trStdErr testResult) -- | Returns the command that was issued, the return code, and the output text run :: FilePath -> String -> [String] -> IO TestResult run cwd path args = do -- path is relative to the current directory; canonicalizePath makes it -- absolute, so that runProcess will find it even when changing directory. path' <- canonicalizePath path (pid, hReadStdOut, hReadStdErr) <- do -- Create pipes for StdOut and StdErr (hReadStdOut, hWriteStdOut) <- createPipe (hReadStdErr, hWriteStdErr) <- createPipe -- Run the process pid <- runProcess path' args (Just cwd) Nothing Nothing (Just hWriteStdOut) (Just hWriteStdErr) -- Return the pid and read ends of the pipes return (pid, hReadStdOut, hReadStdErr) -- Read subprocess output using asynchronous threads; we need to -- do this aynchronously to avoid deadlocks due to buffers filling -- up. withAsync (B.hGetContents hReadStdOut) $ \stdOutAsync -> do withAsync (B.hGetContents hReadStdErr) $ \stdErrAsync -> do -- Wait for the subprocess to terminate exitcode <- waitForProcess pid -- We can now be sure that no further output is going to arrive, -- so we wait for the results of the asynchronous reads. stdOut <- wait stdOutAsync stdErr <- wait stdErrAsync -- Done return $ TestResult exitcode stdOut stdErr cwd -- | Get a list of all names in a directory, excluding all hidden or -- system files/directories such as '.', '..' or any files/directories -- starting with a '.'. listDirectory :: FilePath -> IO [String] listDirectory directory = do fmap (filter notHidden) $ getDirectoryContents directory where notHidden = not . isHidden isHidden name = "." `isPrefixOf` name -- | List a directory as per 'listDirectory', but return an empty list -- in case the directory does not exist. listDirectoryLax :: FilePath -> IO [String] listDirectoryLax directory = do d <- doesDirectoryExist directory if d then listDirectory directory else return [ ] pathIfExists :: FilePath -> IO (Maybe FilePath) pathIfExists p = do e <- doesFileExist p if e then return $ Just p else return Nothing fileMatchesString :: FilePath -> ByteString -> IO Bool fileMatchesString p s = do withBinaryFile p ReadMode $ \h -> do expected <- (C8.lines . normalizeLinebreaks) `fmap` B.hGetContents h -- Strict let actual = C8.lines $ normalizeLinebreaks s return $ length expected == length actual && and (zipWith matches expected actual) where matches :: ByteString -> ByteString -> Bool matches pattern line | C8.pack "RE:" `B.isPrefixOf` pattern = line =~ C8.drop 3 pattern | otherwise = line == pattern -- This is a bit of a hack, but since we're comparing -- *text* output, we should be OK. normalizeLinebreaks = B.filter (not . ((==) 13)) mustMatch :: TestResult -> String -> ByteString -> Maybe FilePath -> Assertion mustMatch _ _ _ Nothing = return () mustMatch testResult handleName actual (Just expected) = do m <- fileMatchesString expected actual unless m $ assertFailure $ "<" ++ handleName ++ "> did not match file '" ++ expected ++ "'.\n" ++ testResultToString testResult discoverTestCategories :: FilePath -> IO [String] discoverTestCategories directory = do names <- listDirectory directory fmap sort $ filterM (\name -> doesDirectoryExist $ directory </> name) names discoverTestCases :: FilePath -> String -> String -> IO [TestCase] discoverTestCases baseDirectory category shouldX = do -- Find the names of the shell scripts names <- fmap (filter isTestCase) $ listDirectoryLax directory -- Fill in TestCase for each script forM (sort names) $ \name -> do stdOutPath <- pathIfExists $ directory </> name `replaceExtension` ".out" stdErrPath <- pathIfExists $ directory </> name `replaceExtension` ".err" return $ TestCase { tcName = name , tcBaseDirectory = baseDirectory , tcCategory = category , tcShouldX = shouldX , tcStdOutPath = stdOutPath , tcStdErrPath = stdErrPath } where directory = baseDirectory </> category </> shouldX isTestCase name = ".sh" `isSuffixOf` name createTestCases :: [TestCase] -> (TestCase -> Assertion) -> IO [TestTree] createTestCases testCases mk = return $ (flip map) testCases $ \tc -> testCase (tcName tc ++ suffix tc) $ mk tc where suffix tc = case (tcStdOutPath tc, tcStdErrPath tc) of (Nothing, Nothing) -> " (ignoring stdout+stderr)" (Just _ , Nothing) -> " (ignoring stderr)" (Nothing, Just _ ) -> " (ignoring stdout)" (Just _ , Just _ ) -> "" runTestCase :: (TestResult -> Assertion) -> TestCase -> IO () runTestCase assertResult tc = do doRemove <- newIORef False bracket createWorkDirectory (removeWorkDirectory doRemove) $ \workDirectory -> do -- Run let scriptDirectory = workDirectory </> tcShouldX tc sh <- fmap (fromMaybe $ error "Cannot find 'sh' executable") $ findExecutable "sh" testResult <- run scriptDirectory sh [ "-e", tcName tc] -- Assert that we got what we expected assertResult testResult mustMatch testResult "stdout" (trStdOut testResult) (tcStdOutPath tc) mustMatch testResult "stderr" (trStdErr testResult) (tcStdErrPath tc) -- Only remove working directory if test succeeded writeIORef doRemove True where createWorkDirectory = do -- Create the temporary directory tempDirectory <- getTemporaryDirectory workDirectory <- createTempDirectory tempDirectory "cabal-install-test" -- Copy all the files from the category into the working directory. copyDirectoryRecursive normal (tcBaseDirectory tc </> tcCategory tc) workDirectory -- Done return workDirectory removeWorkDirectory doRemove workDirectory = do remove <- readIORef doRemove when remove $ removeDirectoryRecursive workDirectory makeShouldXTests :: FilePath -> String -> String -> (TestResult -> Assertion) -> IO [TestTree] makeShouldXTests baseDirectory category shouldX assertResult = do testCases <- discoverTestCases baseDirectory category shouldX createTestCases testCases $ \tc -> runTestCase assertResult tc makeShouldRunTests :: FilePath -> String -> IO [TestTree] makeShouldRunTests baseDirectory category = do makeShouldXTests baseDirectory category "should_run" $ \testResult -> do case trExitCode testResult of ExitSuccess -> return () -- We're good ExitFailure _ -> assertFailure $ "Unexpected exit status.\n\n" ++ testResultToString testResult makeShouldFailTests :: FilePath -> String -> IO [TestTree] makeShouldFailTests baseDirectory category = do makeShouldXTests baseDirectory category "should_fail" $ \testResult -> do case trExitCode testResult of ExitSuccess -> assertFailure $ "Unexpected exit status.\n\n" ++ testResultToString testResult ExitFailure _ -> return () -- We're good discoverCategoryTests :: FilePath -> String -> IO [TestTree] discoverCategoryTests baseDirectory category = do srTests <- makeShouldRunTests baseDirectory category sfTests <- makeShouldFailTests baseDirectory category return [ testGroup "should_run" srTests , testGroup "should_fail" sfTests ] main :: IO () main = do -- Find executables and build directories, etc. distPref <- guessDistDir buildDir <- canonicalizePath (distPref </> "build/cabal") let programSearchPath = ProgramSearchPathDir buildDir : defaultProgramSearchPath (cabal, _) <- requireProgram normal cabalProgram (setProgramSearchPath programSearchPath defaultProgramDb) (ghcPkg, _) <- requireProgram normal ghcPkgProgram defaultProgramDb baseDirectory <- canonicalizePath $ "tests" </> "IntegrationTests" -- Set up environment variables for test scripts setEnv "GHC_PKG" $ programPath ghcPkg setEnv "CABAL" $ programPath cabal -- Define default arguments setEnv "CABAL_ARGS" $ "--config-file=config-file" setEnv "CABAL_ARGS_NO_CONFIG_FILE" " " -- Discover all the test caregories categories <- discoverTestCategories baseDirectory -- Discover tests in each category tests <- forM categories $ \category -> do categoryTests <- discoverCategoryTests baseDirectory category return (category, categoryTests) -- Map into a test tree let testTree = map (\(category, categoryTests) -> testGroup category categoryTests) tests -- Run the tests defaultMain $ testGroup "Integration Tests" $ testTree -- See this function in Cabal's PackageTests. If you update this, -- update its copy in cabal-install. (Why a copy here? I wanted -- to try moving this into the Cabal library, but to do this properly -- I'd have to BC'ify getExecutablePath, and then it got hairy, so -- I aborted and did something simple.) guessDistDir :: IO FilePath guessDistDir = do #if MIN_VERSION_base(4,6,0) exe_path <- canonicalizePath =<< getExecutablePath let dist0 = dropFileName exe_path </> ".." </> ".." b <- doesFileExist (dist0 </> "setup-config") #else let dist0 = error "no path" b = False #endif -- Method (2) if b then canonicalizePath dist0 else findDistPrefOrDefault NoFlag >>= canonicalizePath
garetxe/cabal
cabal-install/tests/IntegrationTests.hs
bsd-3-clause
12,691
0
16
2,596
2,826
1,479
1,347
210
4
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module: Web.Twitter.Conduit -- Copyright: (c) 2014 Takahiro Himura -- License: BSD -- Maintainer: Takahiro Himura <taka@himura.jp> -- Stability: experimental -- Portability: portable -- -- A client library for Twitter APIs (see <https://dev.twitter.com/>). module Web.Twitter.Conduit ( -- * How to use this library -- $howto -- * Re-exports module Web.Twitter.Conduit.Api , module Web.Twitter.Conduit.Cursor , module Web.Twitter.Conduit.Parameters , module Web.Twitter.Conduit.Request , module Web.Twitter.Conduit.Response , module Web.Twitter.Conduit.Status , module Web.Twitter.Conduit.Stream , module Web.Twitter.Conduit.Types -- * 'Web.Twitter.Conduit.Base' , TwitterBaseM , call , call' , callWithResponse , callWithResponse' , sourceWithMaxId , sourceWithMaxId' , sourceWithCursor , sourceWithCursor' , sourceWithSearchResult , sourceWithSearchResult' -- * Backward compatibility -- $backward ) where import Web.Twitter.Conduit.Api import Web.Twitter.Conduit.Base import Web.Twitter.Conduit.Cursor import Web.Twitter.Conduit.Parameters import Web.Twitter.Conduit.Request import Web.Twitter.Conduit.Response import Web.Twitter.Conduit.Status import Web.Twitter.Conduit.Stream import Web.Twitter.Conduit.Types -- for haddock import Web.Authenticate.OAuth import Data.Conduit import qualified Data.Conduit.List as CL import qualified Data.Text as T import qualified Data.Text.IO as T import Control.Monad.IO.Class import Control.Lens #ifdef HLINT {-# ANN module "HLint: ignore Use import/export shortcut" #-} #endif -- $howto -- -- The main module of twitter-conduit is "Web.Twitter.Conduit". -- This library cooperate with <http://hackage.haskell.org/package/twitter-types twitter-types>, -- <http://hackage.haskell.org/package/authenticate-oauth authenticate-oauth>, -- and <http://hackage.haskell.org/package/conduit conduit>. -- All of following examples import modules as below: -- -- > {-# LANGUAGE OverloadedStrings #-} -- > -- > import Web.Twitter.Conduit -- > import Web.Twitter.Types.Lens -- > import Web.Authenticate.OAuth -- > import Network.HTTP.Conduit -- > import Data.Conduit -- > import qualified Data.Conduit.List as CL -- > import qualified Data.Text as T -- > import qualified Data.Text.IO as T -- > import Control.Monad.IO.Class -- > import Control.Lens -- -- First, you should obtain consumer token and secret from <https://apps.twitter.com/ Twitter>, -- and prepare 'OAuth' variables as follows: -- -- @ -- tokens :: 'OAuth' -- tokens = 'twitterOAuth' -- { 'oauthConsumerKey' = \"YOUR CONSUMER KEY\" -- , 'oauthConsumerSecret' = \"YOUR CONSUMER SECRET\" -- } -- @ -- -- Second, you should obtain access token and secret. -- You can find examples obtaining those tokens in -- <https://github.com/himura/twitter-conduit/blob/master/sample sample directry>, -- for instance, -- <https://github.com/himura/twitter-conduit/blob/master/sample/oauth_pin.hs oauth_pin.hs>, and -- <https://github.com/himura/twitter-conduit/blob/master/sample/oauth_callback.hs oauth_callback.hs>. -- If you need more information, see <https://dev.twitter.com/docs/auth/obtaining-access-tokens>. -- -- You should set an access token to 'Credential' variable: -- -- @ -- credential :: 'Credential' -- credential = 'Credential' -- [ (\"oauth_token\", \"YOUR ACCESS TOKEN\") -- , (\"oauth_token_secret\", \"YOUR ACCESS TOKEN SECRET\") -- ] -- @ -- -- You should also set up the 'TWToken' and 'TWInfo' variables as below: -- -- @ -- twInfo :: 'TWInfo' -- twInfo = 'def' -- { 'twToken' = 'def' { 'twOAuth' = tokens, 'twCredential' = credential } -- , 'twProxy' = Nothing -- } -- @ -- -- Or, simply as follows: -- -- > twInfo = setCredential tokens credential def -- -- Twitter API requests are performed by 'call' function. -- For example, <https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline GET statuses/home_timeline> -- could be obtained by: -- -- @ -- timeline \<- 'withManager' $ \\mgr -\> 'call' twInfo mgr 'homeTimeline' -- @ -- -- The response of 'call' function is wrapped by the suitable type of -- <http://hackage.haskell.org/package/twitter-types twitter-types>. -- In this case, /timeline/ has a type of ['Status']. -- If you need /raw/ JSON Value which is parsed by <http://hackage.haskell.org/package/aeson aeson>, -- use 'call'' to obtain it. -- -- By default, the response of <https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline GET statuses/home_timeline> -- includes 20 tweets, and you can change the number of tweets by the /count/ parameter. -- -- @ -- timeline \<- 'withManager' $ \\mgr -\> 'call' twInfo mgr '$' 'homeTimeline' '&' 'count' '?~' 200 -- @ -- -- If you need more statuses, you can obtain those with multiple API requests. -- This library provides the wrapper for multiple requests with conduit interfaces. -- For example, if you intend to fetch the all friends information, -- you may perform multiple API requests with changing cursor parameter, -- or use the conduit wrapper 'sourceWithCursor' as below: -- -- @ -- friends \<- 'withManager' $ \\mgr -\> 'sourceWithCursor' twInfo mgr ('friendsList' ('ScreenNameParam' \"thimura\") '&' 'count' '?~' 200) '$$' 'CL.consume' -- @ -- -- Statuses APIs, for instance, 'homeTimeline', are also wrapped by 'sourceWithMaxId'. -- -- For example, you can print 1000 tweets from your home timeline, as below: -- -- @ -- main :: IO () -- main = withManager $ \mgr -> do -- 'sourceWithMaxId' twInfo mgr 'homeTimeline' -- $= CL.isolate 60 -- $$ CL.mapM_ $ \status -> liftIO $ do -- T.putStrLn $ T.concat [ T.pack . show $ status ^. statusId -- , \": \" -- , status ^. statusUser . userScreenName -- , \": \" -- , status ^. statusText -- ] -- @ -- $backward -- -- In the version below 0.1.0, twitter-conduit provides the TW monad, -- and every Twitter API functions are run in the TW monad. -- -- For backward compatibility, TW monad and the functions are provided in the Web.Twitter.Conduit.Monad module.
johan--/twitter-conduit
Web/Twitter/Conduit.hs
bsd-2-clause
6,423
0
5
1,258
357
295
62
39
0
module Test.Tests where import Test.Framework import Test.AddDays import Test.ClipDates import Test.ConvertBack import Test.LongWeekYears import Test.TestCalendars import Test.TestEaster import Test.TestFormat import Test.TestMonthDay import Test.TestParseDAT import Test.TestParseTime import Test.TestTime import Test.TestTimeZone tests :: [Test] tests = [ addDaysTest , clipDates , convertBack , longWeekYears , testCalendars , testEaster , testFormat , testMonthDay , testParseDAT , testParseTime , testTime , testTimeZone ]
bergmark/time
test/Test/Tests.hs
bsd-3-clause
619
0
5
150
120
75
45
27
1
module RmOneParameter.D2 where {-remove parameter 'ys' from function 'sumSquares'. This refactoring affects module 'D1', and 'A1'. This aims to test removing a parameter from a recursion function-} sumSquares (x:xs) = sq x + sumSquares xs sumSquares [] = 0 sq x = x ^ pow pow =2
RefactoringTools/HaRe
test/testdata/RmOneParameter/D2.expected.hs
bsd-3-clause
289
0
7
57
59
31
28
5
1
-- | This is mostly dummy, JHC does not support inexact exceptions. module Control.Exception where import Prelude hiding(catch) import qualified Prelude as P type IOException = IOError data Exception = IOException IOException -- throw :: Exception -> a assert :: Bool -> a -> a assert True x = x assert False _ = error "assertion failure" throwIO :: Exception -> IO a throwIO (IOException ioe) = ioError ioe catch :: IO a -> (Exception -> IO a) -> IO a catch c h = P.catch c (h . IOException) catchJust :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a catchJust et c h = catch c $ \e -> maybe (throwIO e) h (et e) handle :: (Exception -> IO a) -> IO a -> IO a handle = flip catch handleJust :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a handleJust et h c = catchJust et c h try :: IO a -> IO (Either Exception a) try c = catch (fmap Right c) (return . Left) tryJust :: (Exception -> Maybe b) -> IO a -> IO (Either b a) tryJust et c = catchJust et (fmap Right c) (return . Left) -- FIXME this is wrong! evaluate :: a -> IO a evaluate = return -- mapException ioErrors (IOException _) = True block, unblock :: IO a -> IO a block = id unblock = id bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c bracket before after m = do x <- before rs <- try (m x) after x case rs of Right r -> return r Left e -> throwIO e bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c bracket_ before after m = bracket before after (const m) finally :: IO a -> IO b -> IO a finally cmd end = bracket_ (return ()) (const end) cmd
m-alvarez/jhc
lib/haskell-extras/Control/Exception.hs
mit
1,617
0
10
428
750
372
378
40
2
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..)) import Accumulate (accumulate) import System.Exit (ExitCode(..), exitWith) import Data.Char (toUpper) exitProperly :: IO Counts -> IO () exitProperly m = do counts <- m exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess testCase :: String -> Assertion -> Test testCase label assertion = TestLabel label (TestCase assertion) main :: IO () main = exitProperly $ runTestTT $ TestList [ TestList accumulateTests ] square :: Int -> Int square x = x * x accumulateTests :: [Test] accumulateTests = [ testCase "empty accumulation" $ [] @=? accumulate square [] , testCase "accumulate squares" $ [1, 4, 9] @=? accumulate square [1, 2, 3] , testCase "accumulate upcases" $ ["HELLO", "WORLD"] @=? accumulate (map toUpper) ["hello", "world"] , testCase "accumulate reversed strings" $ ["eht", "kciuq", "nworb", "xof", "cte"] @=? accumulate reverse ["the", "quick", "brown", "fox", "etc"] , testCase "accumulate recursively" $ [["a1", "a2", "a3"], ["b1", "b2", "b3"], ["c1", "c2", "c3"]] @=? accumulate (\c -> accumulate ((c:) . show) ([1, 2, 3] :: [Int])) "abc" , testCase "accumulate non-strict" $ ["nice work!"] @=? take 1 (accumulate id ("nice work!" : error "accumulate should be even lazier, don't use reverse!")) ]
ullet/exercism
haskell/accumulate/accumulate_test.hs
mit
1,400
1
14
281
532
290
242
34
2
import Map import P import Q main = do x <- foo print (mymember 5 x)
mfine/ghc
testsuite/tests/cabal/sigcabal02/Main.hs
bsd-3-clause
78
1
9
25
39
18
21
6
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module T13674 where import Data.Proxy import Data.Kind (Constraint, Type) import GHC.TypeLits import Unsafe.Coerce (unsafeCoerce) data Dict :: Constraint -> Type where Dict :: a => Dict a infixr 9 :- newtype a :- b = Sub (a => Dict b) -- | Given that @a :- b@, derive something that needs a context @b@, using the context @a@ (\\) :: a => (b => r) -> (a :- b) -> r r \\ Sub Dict = r newtype Magic n = Magic (KnownNat n => Dict (KnownNat n)) magic :: forall n m o. (Integer -> Integer -> Integer) -> (KnownNat n, KnownNat m) :- KnownNat o magic f = Sub $ unsafeCoerce (Magic Dict) (natVal (Proxy :: Proxy n) `f` natVal (Proxy :: Proxy m)) type family Lcm :: Nat -> Nat -> Nat where axiom :: forall a b. Dict (a ~ b) axiom = unsafeCoerce (Dict :: Dict (a ~ a)) lcmNat :: forall n m. (KnownNat n, KnownNat m) :- KnownNat (Lcm n m) lcmNat = magic lcm lcmIsIdempotent :: forall n. Dict (n ~ Lcm n n) lcmIsIdempotent = axiom newtype GF (n :: Nat) = GF Integer x :: GF 5 x = GF 3 y :: GF 5 y = GF 4 foo :: (KnownNat m, KnownNat n) => GF m -> GF n -> GF (Lcm m n) foo m@(GF x) n@(GF y) = GF $ (x*y) `mod` (lcm (natVal m) (natVal n)) bar :: (KnownNat m) => GF m -> GF m -> GF m bar (x :: GF m) y = foo x y - foo y x \\ lcmNat @m @m \\ Sub @() (lcmIsIdempotent @m)
sdiehl/ghc
testsuite/tests/indexed-types/should_fail/T13674.hs
bsd-3-clause
1,544
0
11
332
670
360
310
-1
-1
{-# LANGUAGE TemplateHaskell, StandaloneDeriving, GeneralizedNewtypeDeriving, DeriveDataTypeable, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, BangPatterns #-} module Distribution.Server.Features.DownloadCount.State where import Data.Time.Calendar (Day(..)) import Data.Version (Version) import Data.Typeable (Typeable) import Data.Foldable (forM_) import Control.Arrow (first) import Control.Monad (liftM) import Data.List (foldl', groupBy) import Data.Function (on) import Control.Monad.Reader (ask, asks) import Control.Monad.State (get, put) import qualified Data.Map.Lazy as Map import System.FilePath ((</>)) import System.Directory ( getDirectoryContents , createDirectoryIfMissing ) import Control.Applicative ((<$>)) import qualified Data.ByteString.Lazy as BSL import System.IO (withFile, IOMode (..), hPutStr) import System.IO.Unsafe (unsafeInterleaveIO) import Text.CSV (printCSV) import Control.Exception (evaluate) import Data.Acid (Update, Query, makeAcidic) import Data.SafeCopy (base, deriveSafeCopy, safeGet, safePut) import Data.Serialize.Get (runGetLazy) import Data.Serialize.Put (runPutLazy) import Distribution.Package ( PackageId , PackageName , packageName , packageVersion ) import Distribution.Text (simpleParse, display) import Distribution.Simple.Utils (writeFileAtomic) import Distribution.Server.Framework.Instances () import Distribution.Server.Framework.MemSize import Distribution.Server.Util.CountingMap {------------------------------------------------------------------------------ Data types ------------------------------------------------------------------------------} data InMemStats = InMemStats { inMemToday :: !Day , inMemCounts :: !(SimpleCountingMap PackageId) } deriving (Show, Eq, Typeable) newtype OnDiskStats = OnDiskStats { onDiskStats :: NestedCountingMap PackageName OnDiskPerPkg } deriving (Show, Eq, MemSize) instance CountingMap (PackageName, (Day, Version)) OnDiskStats where cmEmpty = OnDiskStats $ cmEmpty cmTotal (OnDiskStats ncm) = cmTotal ncm cmInsert kl n (OnDiskStats ncm) = OnDiskStats $ cmInsert kl n ncm cmFind k (OnDiskStats ncm) = cmFind k ncm cmUnion (OnDiskStats a) (OnDiskStats b) = OnDiskStats (cmUnion a b) cmToList (OnDiskStats ncm) = cmToList ncm cmToCSV (OnDiskStats ncm) = cmToCSV ncm cmInsertRecord r (OnDiskStats ncm) = first OnDiskStats `liftM` cmInsertRecord r ncm newtype OnDiskPerPkg = OnDiskPerPkg { onDiskPerPkgCounts :: NestedCountingMap Day (SimpleCountingMap Version) } deriving (Show, Eq, Ord, MemSize) instance CountingMap (Day, Version) OnDiskPerPkg where cmEmpty = OnDiskPerPkg $ cmEmpty cmTotal (OnDiskPerPkg ncm) = cmTotal ncm cmInsert kl n (OnDiskPerPkg ncm) = OnDiskPerPkg $ cmInsert kl n ncm cmFind k (OnDiskPerPkg ncm) = cmFind k ncm cmUnion (OnDiskPerPkg a) (OnDiskPerPkg b) = OnDiskPerPkg (cmUnion a b) cmToList (OnDiskPerPkg ncm) = cmToList ncm cmToCSV (OnDiskPerPkg ncm) = cmToCSV ncm cmInsertRecord r (OnDiskPerPkg ncm) = first OnDiskPerPkg `liftM` cmInsertRecord r ncm newtype RecentDownloads = RecentDownloads { recentDownloads :: SimpleCountingMap PackageName } deriving (Show, Eq, MemSize) instance CountingMap PackageName RecentDownloads where cmEmpty = RecentDownloads $ cmEmpty cmTotal (RecentDownloads ncm) = cmTotal ncm cmInsert kl n (RecentDownloads ncm) = RecentDownloads $ cmInsert kl n ncm cmFind k (RecentDownloads ncm) = cmFind k ncm cmUnion (RecentDownloads a) (RecentDownloads b) = RecentDownloads (cmUnion a b) cmToList (RecentDownloads ncm) = cmToList ncm cmToCSV (RecentDownloads ncm) = cmToCSV ncm cmInsertRecord r (RecentDownloads ncm) = first RecentDownloads `liftM` cmInsertRecord r ncm newtype TotalDownloads = TotalDownloads { totalDownloads :: SimpleCountingMap PackageName } deriving (Show, Eq, MemSize) instance CountingMap PackageName TotalDownloads where cmEmpty = TotalDownloads $ cmEmpty cmTotal (TotalDownloads ncm) = cmTotal ncm cmInsert kl n (TotalDownloads ncm) = TotalDownloads $ cmInsert kl n ncm cmFind k (TotalDownloads ncm) = cmFind k ncm cmUnion (TotalDownloads a) (TotalDownloads b) = TotalDownloads (cmUnion a b) cmToList (TotalDownloads ncm) = cmToList ncm cmToCSV (TotalDownloads ncm) = cmToCSV ncm cmInsertRecord r (TotalDownloads ncm) = first TotalDownloads `liftM` cmInsertRecord r ncm {------------------------------------------------------------------------------ Initial instances ------------------------------------------------------------------------------} initInMemStats :: Day -> InMemStats initInMemStats day = InMemStats { inMemToday = day , inMemCounts = cmEmpty } type DayRange = (Day, Day) initRecentAndTotalDownloads :: DayRange -> OnDiskStats -> (RecentDownloads, TotalDownloads) initRecentAndTotalDownloads dayRange (OnDiskStats (NCM _ m)) = foldl' (\(recent, total) (pname, pstats) -> let !recent' = accumRecentDownloads dayRange pname pstats recent !total' = accumTotalDownloads pname pstats total in (recent', total')) (emptyRecentDownloads, emptyTotalDownloads) (Map.toList m) emptyRecentDownloads :: RecentDownloads emptyRecentDownloads = RecentDownloads cmEmpty accumRecentDownloads :: DayRange -> PackageName -> OnDiskPerPkg -> RecentDownloads -> RecentDownloads accumRecentDownloads dayRange pkgName (OnDiskPerPkg (NCM _ perDay)) | let rangeTotal = sum (map cmTotal (lookupRange dayRange perDay)) , rangeTotal > 0 = cmInsert pkgName rangeTotal | otherwise = id lookupRange :: Ord k => (k,k) -> Map.Map k a -> [a] lookupRange (l,u) m = let (_,ml,above) = Map.splitLookup l m (middle,mu,_) = Map.splitLookup u above in maybe [] (\x->[x]) ml ++ Map.elems middle ++ maybe [] (\x->[x]) mu emptyTotalDownloads :: TotalDownloads emptyTotalDownloads = TotalDownloads cmEmpty accumTotalDownloads :: PackageName -> OnDiskPerPkg -> TotalDownloads -> TotalDownloads accumTotalDownloads pkgName (OnDiskPerPkg perPkg) = cmInsert pkgName (cmTotal perPkg) {------------------------------------------------------------------------------ Pure updates/queries ------------------------------------------------------------------------------} updateHistory :: InMemStats -> OnDiskStats -> OnDiskStats updateHistory (InMemStats day perPkg) (OnDiskStats (NCM _ m)) = OnDiskStats (NCM 0 (Map.unionWith cmUnion m updatesMap)) where updatesMap :: Map.Map PackageName OnDiskPerPkg updatesMap = Map.fromList [ (pkgname, applyUpdates pkgs) | pkgs <- groupBy ((==) `on` (packageName . fst)) (cmToList perPkg :: [(PackageId, Int)]) , let pkgname = packageName (fst (head pkgs)) ] applyUpdates :: [(PackageId, Int)] -> OnDiskPerPkg applyUpdates pkgs = foldr (.) id [ cmInsert (day, packageVersion pkgId) count | (pkgId, count) <- pkgs ] cmEmpty {------------------------------------------------------------------------------ MemSize ------------------------------------------------------------------------------} instance MemSize InMemStats where memSize (InMemStats a b) = memSize2 a b {------------------------------------------------------------------------------ Serializing on-disk stats ------------------------------------------------------------------------------} readOnDiskStats :: FilePath -> IO OnDiskStats readOnDiskStats stateDir = do createDirectoryIfMissing True stateDir pkgStrs <- getDirectoryContents stateDir OnDiskStats . NCM 0 . Map.fromList <$> sequence [ do onDiskPerPkg <- unsafeInterleaveIO $ either (const cmEmpty) id <$> readOnDiskPerPkg pkgFile return (pkgName, onDiskPerPkg) | Just pkgName <- map simpleParse pkgStrs , let pkgFile = stateDir </> display pkgName ] readOnDiskPerPkg :: FilePath -> IO (Either String OnDiskPerPkg) readOnDiskPerPkg pkgFile = withFile pkgFile ReadMode $ \h -> -- By evaluating the Either result from the parser we force -- all contents to be read evaluate =<< (runGetLazy safeGet <$> BSL.hGetContents h) writeOnDiskStats :: FilePath -> OnDiskStats -> IO () writeOnDiskStats stateDir (OnDiskStats (NCM _ onDisk)) = do createDirectoryIfMissing True stateDir forM_ (Map.toList onDisk) $ \(pkgName, perPkg) -> do let pkgFile = stateDir </> display pkgName writeFileAtomic pkgFile $ runPutLazy (safePut perPkg) {------------------------------------------------------------------------------ The append-only all-time log ------------------------------------------------------------------------------} appendToLog :: FilePath -> InMemStats -> IO () appendToLog stateDir (InMemStats _ inMemStats) = withFile (stateDir </> "log") AppendMode $ \h -> hPutStr h $ printCSV (cmToCSV inMemStats) reconstructLog :: FilePath -> OnDiskStats -> IO () reconstructLog stateDir onDisk = withFile (stateDir </> "log") WriteMode $ \h -> hPutStr h $ printCSV (cmToCSV onDisk) {------------------------------------------------------------------------------ ACID stuff ------------------------------------------------------------------------------} deriveSafeCopy 0 'base ''InMemStats deriveSafeCopy 0 'base ''OnDiskPerPkg getInMemStats :: Query InMemStats InMemStats getInMemStats = ask replaceInMemStats :: InMemStats -> Update InMemStats () replaceInMemStats = put recordedToday :: Query InMemStats Day recordedToday = asks inMemToday registerDownload :: PackageId -> Update InMemStats () registerDownload pkgId = do InMemStats day counts <- get put $ InMemStats day (cmInsert pkgId 1 counts) makeAcidic ''InMemStats [ 'getInMemStats , 'replaceInMemStats , 'recordedToday , 'registerDownload ]
ocharles/hackage-server
Distribution/Server/Features/DownloadCount/State.hs
bsd-3-clause
10,210
0
17
1,971
2,683
1,413
1,270
194
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Program.Strip -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This module provides an library interface to the @strip@ program. module Distribution.Simple.Program.Strip (stripLib, stripExe) where import Distribution.Simple.Program import Distribution.Simple.Utils import Distribution.System import Distribution.Verbosity import Distribution.Version import Control.Monad (unless) import System.FilePath (takeBaseName) runStrip :: Verbosity -> ProgramConfiguration -> FilePath -> [String] -> IO () runStrip verbosity progConf path args = case lookupProgram stripProgram progConf of Just strip -> rawSystemProgram verbosity strip (path:args) Nothing -> unless (buildOS == Windows) $ -- Don't bother warning on windows, we don't expect them to -- have the strip program anyway. warn verbosity $ "Unable to strip executable or library '" ++ (takeBaseName path) ++ "' (missing the 'strip' program)" stripExe :: Verbosity -> Platform -> ProgramConfiguration -> FilePath -> IO () stripExe verbosity (Platform _arch os) conf path = runStrip verbosity conf path args where args = case os of OSX -> ["-x"] -- By default, stripping the ghc binary on at least -- some OS X installations causes: -- HSbase-3.0.o: unknown symbol `_environ'" -- The -x flag fixes that. _ -> [] stripLib :: Verbosity -> Platform -> ProgramConfiguration -> FilePath -> IO () stripLib verbosity (Platform arch os) conf path = do case os of OSX -> -- '--strip-unneeded' is not supported on OS X, iOS, AIX, or -- Solaris. See #1630. return () IOS -> return () AIX -> return () Solaris -> return () Windows -> -- Stripping triggers a bug in 'strip.exe' for -- libraries with lots identically named modules. See -- #1784. return() Linux | arch == I386 -> -- Versions of 'strip' on 32-bit Linux older than 2.18 are -- broken. See #2339. let okVersion = orLaterVersion (Version [2,18] []) in case programVersion =<< lookupProgram stripProgram conf of Just v | withinRange v okVersion -> runStrip verbosity conf path args _ -> warn verbosity $ "Unable to strip library '" ++ (takeBaseName path) ++ "' (version of 'strip' too old; " ++ "requires >= 2.18 on 32-bit Linux)" _ -> runStrip verbosity conf path args where args = ["--strip-unneeded"]
tolysz/prepare-ghcjs
spec-lts8/cabal/Cabal/Distribution/Simple/Program/Strip.hs
bsd-3-clause
2,876
0
20
882
539
281
258
43
8
{-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.DynamicWorkspaceOrder -- Copyright : (c) Brent Yorgey 2009 -- License : BSD-style (see LICENSE) -- -- Maintainer : <byorgey@gmail.com> -- Stability : experimental -- Portability : unportable -- -- Remember a dynamically updateable ordering on workspaces, together -- with tools for using this ordering with "XMonad.Actions.CycleWS" -- and "XMonad.Hooks.DynamicLog". -- ----------------------------------------------------------------------------- module XMonad.Actions.DynamicWorkspaceOrder ( -- * Usage -- $usage getWsCompareByOrder , getSortByOrder , swapWith , moveTo , moveToGreedy , shiftTo , withNthWorkspace ) where import XMonad import qualified XMonad.StackSet as W import qualified XMonad.Util.ExtensibleState as XS import XMonad.Util.WorkspaceCompare (WorkspaceCompare, WorkspaceSort, mkWsSort) import XMonad.Actions.CycleWS (findWorkspace, WSType(..), Direction1D(..), doTo) import qualified Data.Map as M import qualified Data.Set as S import Data.Maybe (fromJust, fromMaybe) import Data.Ord (comparing) -- $usage -- You can use this module by importing it into your ~\/.xmonad\/xmonad.hs file: -- -- > import qualified XMonad.Actions.DynamicWorkspaceOrder as DO -- -- Then add keybindings to swap the order of workspaces (these -- examples use "XMonad.Util.EZConfig" emacs-style keybindings): -- -- > , ("M-C-<R>", DO.swapWith Next NonEmptyWS) -- > , ("M-C-<L>", DO.swapWith Prev NonEmptyWS) -- -- See "XMonad.Actions.CycleWS" for information on the possible -- arguments to 'swapWith'. -- -- However, by itself this will do nothing; 'swapWith' does not change -- the actual workspaces in any way. It simply keeps track of an -- auxiliary ordering on workspaces. Anything which cares about the -- order of workspaces must be updated to use the auxiliary ordering. -- -- To change the order in which workspaces are displayed by -- "XMonad.Hooks.DynamicLog", use 'getSortByOrder' in your -- 'XMonad.Hooks.DynamicLog.ppSort' field, for example: -- -- > ... dynamicLogWithPP $ byorgeyPP { -- > ... -- > , ppSort = DO.getSortByOrder -- > ... -- > } -- -- To use workspace cycling commands like those from -- "XMonad.Actions.CycleWS", use the versions of 'moveTo', -- 'moveToGreedy', and 'shiftTo' exported by this module. For example: -- -- > , ("M-S-<R>", DO.shiftTo Next HiddenNonEmptyWS) -- > , ("M-S-<L>", DO.shiftTo Prev HiddenNonEmptyWS) -- > , ("M-<R>", DO.moveTo Next HiddenNonEmptyWS) -- > , ("M-<L>", DO.moveTo Prev HiddenNonEmptyWS) -- -- For slight variations on these, use the source for examples and -- tweak as desired. -- | Extensible state storage for the workspace order. data WSOrderStorage = WSO { unWSO :: Maybe (M.Map WorkspaceId Int) } deriving (Typeable, Read, Show) instance ExtensionClass WSOrderStorage where initialValue = WSO Nothing extensionType = PersistentExtension -- | Lift a Map function to a function on WSOrderStorage. withWSO :: (M.Map WorkspaceId Int -> M.Map WorkspaceId Int) -> (WSOrderStorage -> WSOrderStorage) withWSO f = WSO . fmap f . unWSO -- | Update the ordering storage: initialize if it doesn't yet exist; -- add newly created workspaces at the end as necessary. updateOrder :: X () updateOrder = do WSO mm <- XS.get case mm of Nothing -> do -- initialize using ordering of workspaces from the user's config ws <- asks (workspaces . config) XS.put . WSO . Just . M.fromList $ zip ws [0..] Just m -> do -- check for new workspaces and add them at the end curWs <- gets (S.fromList . map W.tag . W.workspaces . windowset) let mappedWs = M.keysSet m newWs = curWs `S.difference` mappedWs nextIndex = 1 + maximum (-1 : M.elems m) newWsIxs = zip (S.toAscList newWs) [nextIndex..] XS.modify . withWSO . M.union . M.fromList $ newWsIxs -- | A comparison function which orders workspaces according to the -- stored dynamic ordering. getWsCompareByOrder :: X WorkspaceCompare getWsCompareByOrder = do updateOrder -- after the call to updateOrder we are guaranteed that the dynamic -- workspace order is initialized and contains all existing -- workspaces. WSO (Just m) <- XS.get return $ comparing (fromMaybe 1000 . flip M.lookup m) -- | Sort workspaces according to the stored dynamic ordering. getSortByOrder :: X WorkspaceSort getSortByOrder = mkWsSort getWsCompareByOrder -- | Swap the current workspace with another workspace in the stored -- dynamic order. swapWith :: Direction1D -> WSType -> X () swapWith dir which = findWorkspace getSortByOrder dir which 1 >>= swapWithCurrent -- | Swap the given workspace with the current one. swapWithCurrent :: WorkspaceId -> X () swapWithCurrent w = do cur <- gets (W.currentTag . windowset) swapOrder w cur -- | Swap the two given workspaces in the dynamic order. swapOrder :: WorkspaceId -> WorkspaceId -> X () swapOrder w1 w2 = do io $ print (w1,w2) WSO (Just m) <- XS.get let [i1,i2] = map (fromJust . flip M.lookup m) [w1,w2] XS.modify (withWSO (M.insert w1 i2 . M.insert w2 i1)) windows id -- force a status bar update -- | View the next workspace of the given type in the given direction, -- where \"next\" is determined using the dynamic workspace order. moveTo :: Direction1D -> WSType -> X () moveTo dir t = doTo dir t getSortByOrder (windows . W.view) -- | Same as 'moveTo', but using 'greedyView' instead of 'view'. moveToGreedy :: Direction1D -> WSType -> X () moveToGreedy dir t = doTo dir t getSortByOrder (windows . W.greedyView) -- | Shift the currently focused window to the next workspace of the -- given type in the given direction, using the dynamic workspace order. shiftTo :: Direction1D -> WSType -> X () shiftTo dir t = doTo dir t getSortByOrder (windows . W.shift) -- | Do something with the nth workspace in the dynamic order. The -- callback is given the workspace's tag as well as the 'WindowSet' -- of the workspace itself. withNthWorkspace :: (String -> WindowSet -> WindowSet) -> Int -> X () withNthWorkspace job wnum = do sort <- getSortByOrder ws <- gets (map W.tag . sort . W.workspaces . windowset) case drop wnum ws of (w:_) -> windows $ job w [] -> return ()
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Actions/DynamicWorkspaceOrder.hs
bsd-2-clause
6,450
0
20
1,256
1,139
624
515
74
2
{- Haskell version of ... ! Text of rule base for Boyer benchmark ! ! Started by Tony Kitto on 6th April 1988 ! ! Changes Log ! ! 07-04-88 ADK Corrected errors in rules ! 08-04-88 ADK Modified "or" rule to remove extra final (f) of book definition Haskell version: 23-06-93 JSM initial version -} module Rulebasetext (rules) where rules :: [String] -- Rule base extracted from Gabriel pages 118 to 126 rules = [ "(equal (compile form)\ \(reverse (codegen (optimize form) (nil) ) ) )", "(equal (eqp x y)\ \(equal (fix x)\ \(fix y) ) )", "(equal (greaterp x y)\ \(lessp y x) )", "(equal (lesseqp x y)\ \(not (lessp y x) ) )", "(equal (greatereqp x y)\ \(not (lessp y x) ) )", "(equal (boolean x)\ \(or (equal x (t) )\ \(equal x (f) ) )", "(equal (iff x y)\ \(and (implies x y)\ \(implies y x) ) )", "(equal (even1 x)\ \(if (zerop x)\ \(t)\ \(odd (1- x) ) ) )", "(equal (countps- l pred)\ \(countps-loop l pred (zero) ) )", "(equal (fact- i)\ \(fact-loop i 1) )", "(equal (reverse- x)\ \(reverse-loop x (nil) ) )", "(equal (divides x y)\ \(zerop (remainder y x) ) )", "(equal (assume-true var alist)\ \(cons (cons var (t) )\ \alist) )", "(equal (assume-false var alist)\ \(cons (cons var (f) )\ \alist) )", "(equal (tautology-checker x)\ \(tautologyp (normalize x)\ \(nil) ) )", "(equal (falsify x)\ \(falsify1 (normalize x)\ \(nil) ) )", "(equal (prime x)\ \(and (not (zerop x))\ \(not (equal x (add1 (zero) ) ) )\ \(prime1 x (1- x) ) ) )", "(equal (and p q)\ \(if p (if q (t) (f) ) (f) ) )", "(equal (or p q)\ \(if p (t) (if q (t) (f) ) ) )", -- book has extra (f) "(equal (not p)\ \(if p (f) (t) ) )", "(equal (implies p q)\ \(if p (if q (t) (f) ) (t) ) )", "(equal (fix x)\ \(if (numberp x) x (zero) ) )", "(equal (if (if a b c) d e)\ \(if a (if b d e) (if c d e) ) )", "(equal (zerop x)\ \(or (equal x (zero) )\ \(not (numberp x) ) ) )", "(equal (plus (plus x y) z )\ \(plus x (plus y z) ) )", "(equal (equal (plus a b) (zero ) )\ \(and (zerop a) (zerop b) ) )", "(equal (difference x x)\ \(zero) )", "(equal (equal (plus a b) (plus a c) )\ \(equal (fix b) (fix c) ) )", "(equal (equal (zero) (difference x y) )\ \(not (lessp y x) ) )", "(equal (equal x (difference x y) )\ \(and (numberp x)\ \(or (equal x (zero) )\ \(zerop y) ) ) )", "(equal (meaning (plus-tree (append x y) ) a)\ \(plus (meaning (plus-tree x) a)\ \(meaning (plus-tree y) a) ) )", "(equal (meaning (plus-tree (plus-fringe x) ) a)\ \(fix (meaning x a) ) )", "(equal (append (append x y) z)\ \(append x (append y z) ) )", "(equal (reverse (append a b) )\ \(append (reverse b) (reverse a) ) )", "(equal (times x (plus y z) )\ \(plus (times x y)\ \(times x z) ) )", "(equal (times (times x y) z)\ \(times x (times y z) ) )", "(equal (equal (times x y) (zero) )\ \(or (zerop x)\ \(zerop y) ) )", "(equal (exec (append x y)\ \pds envrn)\ \(exec y (exec x pds envrn)\ \envrn) )", "(equal (mc-flatten x y)\ \(append (flatten x)\ \y) )", "(equal (member x (append a b) )\ \(or (member x a)\ \(member x b) ) )", "(equal (member x (reverse y) )\ \(member x y) )", "(equal (length (reverse x) )\ \(length x) )", "(equal (member a (intersect b c) )\ \(and (member a b)\ \(member a c) ) )", "(equal (nth (zero)\ \i)\ \(zero) )", "(equal (exp i (plus j k) )\ \(times (exp i j)\ \(exp i k) ) )", "(equal (exp i (times j k) )\ \(exp (exp i j)\ \k) )", "(equal (reverse-loop x y)\ \(append (reverse x)\ \y) )", "(equal (reverse-loop x (nil) )\ \(reverse x) )", "(equal (count-list z (sort-lp x y) )\ \(plus (count-list z x)\ \(count-list z y) ) )", "(equal (equal (append a b)\ \(append a c) )\ \(equal b c) )", "(equal (plus (remainder x y)\ \(times y (quotient x y) ) )\ \(fix x) )", "(equal (power-eval (big-plus1 l i base)\ \base)\ \(plus (power-eval l base)\ \i) )", "(equal (power-eval (big-plus x y i base)\ \base)\ \(plus i (plus (power-eval x base)\ \(power-eval y base) ) ) )", "(equal (remainder y 1)\ \(zero) )", "(equal (lessp (remainder x y)\ \y)\ \(not (zerop y) ) )", "(equal (remainder x x)\ \(zero) )", "(equal (lessp (quotient i j)\ \i)\ \(and (not (zerop i) )\ \(or (zerop j)\ \(not (equal j 1) ) ) ) )", "(equal (lessp (remainder x y)\ \x)\ \(and (not (zerop y) )\ \(not (zerop x) )\ \(not (lessp x y) ) ) )", "(equal (power-eval (power-rep i base)\ \base)\ \(fix i) )", "(equal (power-eval (big-plus (power-rep i base)\ \(power-rep j base)\ \(zero)\ \base)\ \base)\ \(plus i j) )", "(equal (gcd x y)\ \(gcd y x) )", "(equal (nth (append a b)\ \i)\ \(append (nth a i)\ \(nth b (difference i (length a) ) ) ) )", "(equal (difference (plus x y)\ \x)\ \(fix y) )", "(equal (difference (plus y x)\ \x)\ \(fix y) )", "(equal (difference (plus x y)\ \(plus x z) )\ \(difference y z) )", "(equal (times x (difference c w) )\ \(difference (times c x)\ \(times w x) ) )", "(equal (remainder (times x z)\ \z)\ \(zero) )", "(equal (difference (plus b (plus a c) )\ \a)\ \(plus b c) )", "(equal (difference (add1 (plus y z)\ \z)\ \(add1 y) )", "(equal (lessp (plus x y)\ \(plus x z ) )\ \(lessp y z) )", "(equal (lessp (times x z)\ \(times y z) )\ \(and (not (zerop z) )\ \(lessp x y) ) )", "(equal (lessp y (plus x y) )\ \(not (zerop x) ) )", "(equal (gcd (times x z)\ \(times y z) )\ \(times z (gcd x y) ) )", "(equal (value (normalize x)\ \a)\ \(value x a) )", "(equal (equal (flatten x)\ \(cons y (nil) ) )\ \(and (nlistp x)\ \(equal x y) ) )", "(equal (listp (gopher x) )\ \(listp x) )", "(equal (samefringe x y)\ \(equal (flatten x)\ \(flatten y) ) )", "(equal (equal (greatest-factor x y)\ \(zero) )\ \(and (or (zerop y)\ \(equal y 1) )\ \(equal x (zero) ) ) )", "(equal (equal (greatest-factor x y)\ \1)\ \(equal x 1) )", "(equal (numberp (greatest-factor x y) )\ \(not (and (or (zerop y)\ \(equal y 1) )\ \(not (numberp x) ) ) ) )", "(equal (times-list (append x y) )\ \(times (times-list x)\ \(times-list y) ) )", "(equal (prime-list (append x y) )\ \(and (prime-list x)\ \(prime-list y) ) )", "(equal (equal z (times w z) )\ \(and (numberp z)\ \(or (equal z (zero) )\ \(equal w 1) ) ) )", "(equal (greatereqpr x y)\ \(not (lessp x y) ) )", "(equal (equal x (times x y) )\ \(or (equal x (zero) )\ \(and (numberp x)\ \(equal y 1) ) ) )", "(equal (remainder (times y x)\ \y)\ \(zero) )", "(equal (equal (times a b)\ \1)\ \(and (not (equal a (zero) ) )\ \(not (equal b (zero) ) )\ \(numberp a)\ \(numberp b)\ \(equal (1- a)\ \(zero) )\ \(equal (1- b)\ \(zero) ) ) )", "(equal (lessp (length (delete x l) )\ \(length l) )\ \(member x l) )", "(equal (sort2 (delete x l) )\ \(delete x (sort2 l) ) )", "(equal (dsort x)\ \(sort2 x) )", "(equal (length\ \(cons \ \x1\ \(cons \ \x2\ \(cons \ \x3\ \(cons \ \x4\ \(cons \ \x5\ \(cons x6 x7) ) ) ) ) ) )\ \(plus 6 (length x7) ) )", "(equal (difference (add1 (add1 x) )\ \2)\ \(fix x) )", "(equal (quotient (plus x (plus x y) )\ \2)\ \(plus x (quotient y 2) ) )", "(equal (sigma (zero)\ \i)\ \(quotient (times i (add1 i) )\ \2) )", "(equal (plus x (add1 y) )\ \(if (numberp y)\ \(add1 (plus x y) )\ \(add1 x) ) )", "(equal (equal (difference x y)\ \(difference z y) )\ \(if (lessp x y)\ \(not (lessp y z) )\ \(if (lessp z y)\ \(not (lessp y x) )\ \(equal (fix x)\ \(fix z) ) ) ) )", "(equal (meaning (plus-tree (delete x y) )\ \a)\ \(if (member x y)\ \(difference (meaning (plus-tree y)\ \a)\ \(meaning x a) )\ \(meaning (plus-tree y)\ \a) ) )", "(equal (times x (add1 y) )\ \(if (numberp y)\ \(plus x (times x y) )\ \(fix x) ) )", "(equal (nth (nil)\ \i)\ \(if (zerop i)\ \(nil)\ \(zero) ) )", "(equal (last (append a b) )\ \(if (listp b)\ \(last b)\ \(if (listp a)\ \(cons (car (last a) )\ \b)\ \b) ) )", "(equal (equal (lessp x y)\ \z)\ \(if (lessp x y)\ \(equal t z)\ \(equal f z) ) )", "(equal (assignment x (append a b) )\ \(if (assignedp x a)\ \(assignment x a)\ \(assignment x b) ) )", "(equal (car (gopher x) )\ \(if (listp x)\ \(car (flatten x) )\ \(zero) ) )", "(equal (flatten (cdr (gopher x) ) )\ \(if (listp x)\ \(cdr (flatten x) )\ \(cons (zero)\ \(nil) ) ) )", "(equal (quotient (times y x)\ \y)\ \(if (zerop y)\ \(zero)\ \(fix x) ) )", "(equal (get j (set i val mem) )\ \(if (eqp j i)\ \val\ \(get j mem) ) )"]
philderbeast/ghcjs
test/nofib/spectral/boyer2/Rulebasetext.hs
mit
15,416
0
5
8,947
343
229
114
109
1
module A where data A = A other :: Int other = 2 -- | Doc for test2 test2 :: Bool test2 = False -- | Should show up on the page for both modules A and B data X = X -- ^ Doc for consructor -- | Should show up on the page for both modules A and B reExport :: Int reExport = 1
DavidAlphaFox/ghc
utils/haddock/html-test/src/A.hs
bsd-3-clause
279
0
5
72
52
33
19
9
1
module Main where import Control.Concurrent main = do c <- newChan let writer = writeList2Chan c "Hello World\n" forkIO writer let reader = do char <- readChan c if (char == '\n') then return () else do putChar char; reader reader
urbanslug/ghc
testsuite/tests/concurrent/should_run/conc002.hs
bsd-3-clause
262
4
15
72
101
47
54
11
2
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE TupleSections #-} module Stutter.Parser where import Control.Applicative import Control.Monad import Text.Read (readMaybe) import Data.Attoparsec.Text ((<?>)) import qualified Data.Attoparsec.Text as Atto import qualified Data.Text as T import Stutter.Producer hiding (ProducerGroup) type ProducerGroup = ProducerGroup_ () ------------------------------------------------------------------------------- -- Text ------------------------------------------------------------------------------- parseText :: Atto.Parser T.Text parseText = (<?> "text") $ T.pack <$> Atto.many1 parseSimpleChar parseSimpleChar :: Atto.Parser Char parseSimpleChar = (<?> "simple char or escaped char") $ -- A non-special char Atto.satisfy (`notElem` specialChars) <|> -- An escaped special char Atto.char '\\' *> Atto.anyChar specialChars :: [Char] specialChars = [ -- Used for sum '|' -- Used for product , '#' -- Used for zip , '$' -- Used for Kleene plus , '+' -- Used for Kleene start , '*' -- Used for optional , '?' -- Used to delimit ranges , '[', ']' -- Used to scope groups , '(', ')' -- Used to replicate groups , '{', '}' -- Used for escaping , '\\' -- Used for files , '@' ] parseGroup :: Atto.Parser ProducerGroup parseGroup = (<?> "producer group") $ (parseUnit' <**> parseSquasher' <*> parseGroup) <|> (PProduct <$> parseUnit' <*> parseGroup) <|> parseUnit' where parseUnit' = parseReplicatedUnit <|> parseUnit -- Default binary function to product (@#@) parseSquasher' = parseSquasher <|> pure PProduct parseReplicatedUnit :: Atto.Parser ProducerGroup parseReplicatedUnit = (<?> "replicated unary producer") $ -- This the logic for the replication shouldn't be in the parser parseUnit <**> parseReplicator type Squasher = ProducerGroup -> ProducerGroup -> ProducerGroup type Replicator = ProducerGroup -> ProducerGroup parseReplicator :: Atto.Parser Replicator parseReplicator = parseKleenePlus <|> parseKleeneStar <|> parseOptional <|> parseFoldApp parseKleenePlus :: Atto.Parser Replicator parseKleenePlus = Atto.char '+' *> pure (PRepeat) parseKleeneStar :: Atto.Parser Replicator parseKleeneStar = Atto.char '*' *> pure (PSum (PText T.empty) . PRepeat) parseOptional :: Atto.Parser Replicator parseOptional = Atto.char '?' *> pure (PSum (PText T.empty) ) parseFoldApp :: Atto.Parser Replicator parseFoldApp = bracketed '{' '}' ( flip (,) <$> parseSquasher <* Atto.char '|' <*> parseInt <|> (,PSum) <$> parseInt ) <**> (pure (\(n, f) -> foldr1 f . replicate n)) where parseInt :: Atto.Parser Int parseInt = (readMaybe <$> Atto.many1 Atto.digit) >>= \case Nothing -> mzero Just x -> return x parseSquasher :: Atto.Parser Squasher parseSquasher = Atto.anyChar >>= \case '|' -> return PSum '$' -> return PZip '#' -> return PProduct _ -> mzero parseUnit :: Atto.Parser ProducerGroup parseUnit = (<?> "unary producer") $ PRanges <$> parseRanges <|> parseHandle <|> PText <$> parseText <|> bracketed '(' ')' parseGroup bracketed :: Char -> Char -> Atto.Parser a -> Atto.Parser a bracketed cl cr p = Atto.char cl *> p <* Atto.char cr -- | Parse a Handle-like reference, preceded by an @\@@ sign. A single dash -- (@-@) is interpreted as @stdin@, any other string is used as a file path. parseHandle :: Atto.Parser ProducerGroup parseHandle = (<?> "handle reference") $ (flip fmap) parseFile $ \case "-" -> PStdin () fp -> PFile fp ------------------------------------------------------------------------------- -- File ------------------------------------------------------------------------------- parseFile :: Atto.Parser FilePath parseFile = (<?> "file reference") $ T.unpack <$> (Atto.char '@' *> parseText) ------------------------------------------------------------------------------- -- Ranges ------------------------------------------------------------------------------- -- | Parse several ranges -- -- Example: -- @[a-zA-Z0-6]@ parseRanges :: Atto.Parser [Range] parseRanges = (<?> "ranges") $ Atto.char '[' *> Atto.many1 parseRange <* Atto.char ']' -- | Parse a range of the form 'a-z' (int or char) parseRange :: Atto.Parser Range parseRange = (<?> "range") $ parseIntRange <|> parseCharRange -- | Parse a range in the format "<start>-<end>", consuming exactly 3 -- characters parseIntRange :: Atto.Parser Range parseIntRange = (<?> "int range") $ IntRange <$> ((,) <$> parseInt <* Atto.char '-' <*> parseInt) where parseInt :: Atto.Parser Int parseInt = (readMaybe . (:[]) <$> Atto.anyChar) >>= \case Nothing -> mzero Just x -> return x -- | Parse a range in the format "<start>-<end>", consuming exactly 3 -- characters parseCharRange :: Atto.Parser Range parseCharRange = (<?> "char range") $ CharRange <$> ((,) <$> Atto.anyChar <* Atto.char '-' <*> Atto.anyChar)
nmattia/stutter
src/Stutter/Parser.hs
mit
5,112
0
14
1,047
1,176
645
531
113
4
-- This source code is distributed under the terms of a MIT license, -- Copyright (c) 2016-present, SoundCloud Ltd. -- All rights reserved. -- -- This source code is distributed under the terms of a MIT license, -- found in the LICENSE file. {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} module Main where import Kubernetes.Apis import Servant import Servant.Mock import qualified Network.Wai.Handler.Warp as Warp main :: IO () main = Warp.run 8080 $ serve api (mock api)
soundcloud/haskell-kubernetes
server/Main.hs
mit
519
0
8
86
71
45
26
10
1
module Euler008 (euler8) where import Common import Data.Char euler8 :: Int euler8 = maximum [product adjacents | adjacents <- sliding 13 num] num :: [Int] num = map digitToInt "\ \73167176531330624919225119674426574742355349194934\ \96983520312774506326239578318016984801869478851843\ \85861560789112949495459501737958331952853208805511\ \12540698747158523863050715693290963295227443043557\ \66896648950445244523161731856403098711121722383113\ \62229893423380308135336276614282806444486645238749\ \30358907296290491560440772390713810515859307960866\ \70172427121883998797908792274921901699720888093776\ \65727333001053367881220235421809751254540594752243\ \52584907711670556013604839586446706324415722155397\ \53697817977846174064955149290862569321978468622482\ \83972241375657056057490261407972968652414535100474\ \82166370484403199890008895243450658541227588666881\ \16427171479924442928230863465674813919123162824586\ \17866458359124566529476545682848912883142607690042\ \24219022671055626321111109370544217506941658960408\ \07198403850962455444362981230987879927244284909188\ \84580156166097919133875499200524063689912560717606\ \05886116467109405077541002256983155200055935729725\ \71636269561882670428252483600823257530420752963450"
TrustNoOne/Euler
haskell/src/Euler008.hs
mit
1,324
0
9
134
67
37
30
7
1
module Types( Matrix(..), Point(..), Point3d(..), IntPoint, IntPoint3d, GLPoint, GLPoint3d, Line(..), Line3d(..), Viewport(..), Axis, mkViewport, translateMatrix, scaleMatrix, rotationMatrix, translate3d, scale3d, rotate3d ) where import Graphics.Rendering.OpenGL.Raw.Core31 data Matrix a = Matrix{ w :: Int, h :: Int, mdata :: [[a]] } deriving (Show, Eq) type Point a = (a, a) type Point3d a = (a, a, a) type IntPoint = Point Int type GLPoint = Point GLfloat type IntPoint3d = Point3d Int type GLPoint3d = Point3d GLfloat data Line a = Line {p_x :: Point a, p_y :: Point a} deriving (Show, Eq) data Line3d a = Line3d { p :: Point3d a, q :: Point3d a} deriving (Show, Eq) data Viewport = Viewport {minX :: Int, minY :: Int, maxX :: Int, maxY :: Int} deriving (Show, Eq) data Axis = X | Y | Z deriving (Show, Eq) --Safe making viewport mkViewport :: Int -> Int -> Int -> Int -> Maybe Viewport mkViewport minx miny maxx maxy | minx < maxx && miny < maxy = Just (Viewport minx miny maxx maxy) | otherwise = Nothing translateMatrix tx ty = Matrix 3 3 [[1, 0, tx], [0, 1, ty], [0, 0, 1]] scaleMatrix sx sy = Matrix 3 3 [[sx, 0, 0], [0, sy, 0], [0, 0, 1]] rotationMatrix theta = Matrix 3 3 [[cos t, -(sin t), 0], [sin t, cos t, 0], [0, 0, 1]] where t = - (theta * pi / 180) -- to change to clockwise rotation and map to rads translate3d tx ty tz = Matrix 4 4 [[1, 0, 0, tx], [0, 1, 0, ty], [0, 0, 0, tz], [0, 0, 0, 1]] scale3d sx sy sz = Matrix 4 4 [[sx, 0, 0, 0], [0, sy, 0, 0], [0, 0, sz, 0], [0, 0, 0, 1]] rotate3d a theta = let t = - (theta * pi / 180) c = cos t s = sin t in Matrix 4 4 $ case a of X -> [[1, 0, 0, 0], [0, c, s, 0], [0, (-s), c, 0], [0, 0, 0, 1]] Y -> [[c, 0, (-s), 0], [0, 1, 0, 0], [s, 0, c, 0], [0, 0, 0, 1]] Z -> [[c, s, 0, 0], [(-s), c, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5outh/Haskell-Graphics-Projects
Project3/Types.hs
mit
1,881
0
14
467
1,058
637
421
48
3
module Y2017.M07.D04.Exercise where {-- Another Mensa-puzzler from the Genius Mensa Quiz-a-Day Book by Dr. Abbie F. Salny. July 2 problem: Jemima has the same number of brothers as she has sisters, but her brother, Roland, has twice as many sisters as he has brothers. How many boys and girls are there in this family? --} data Name = Jemima | Roland deriving (Eq, Show) data Sex = Male | Female deriving (Eq, Show) data Person = Pers Name Sex deriving (Eq, Show) type Boys = Int type Girls = Int type Multiplier = Int -- to equate girls to boys data Statement = Has Person Multiplier deriving (Eq, Show) jemima, roland :: Statement jemima = Pers Jemima Female `Has` 1 roland = Pers Roland Male `Has` 2 familySize :: [Statement] -> [(Boys, Girls)] familySize statements = undefined
geophf/1HaskellADay
exercises/HAD/Y2017/M07/D04/Exercise.hs
mit
805
0
7
160
182
108
74
17
1
{-# LANGUAGE FlexibleContexts #-} module Metropolis (arb) where import Data.Random arb :: (Distribution Uniform a, Distribution Uniform b, Ord a, Num b, Ord b) => (a->b) -> (a,a) -> b -> RVar a arb f (low, high) top = do site <- uniform low high test <- uniform 0 top if f site > test then return site else arb f (low, high) top
rprospero/NeutronPipe
Metropolis.hs
mit
341
0
9
76
161
84
77
10
2
fromJust (Just v) = v -- data E = Constant Int | Var String | StrictCall String [E] | IfThenElse E E E | FunctionCall String [E] data Fb = [String] := E type F = (String, Fb) -- f_f = ("f", ["x"] := IfThenElse (Var "x") (StrictCall "*" [Var "x", FunctionCall "f" [StrictCall "-" [Var "x", Constant 1]]]) (Constant 1)) {- *Main> interpE [f_f] [] (FunctionCall "f" [Constant 4]) 24 -} g_f = ("g", ["x", "y"] := IfThenElse (Var "x") (Constant 0) (Var "y")) {- *Main> interpE [g_f] [] (FunctionCall "g" [Constant 0, Constant 1]) 1 *Main> interpE [g_f] [] (FunctionCall "g" [Constant 1, Constant 1]) 0 -} -- interpE :: [F] -> [(String,Int)] -> E -> Int interpE fs s (Constant i) = i interpE fs s (Var v) = fromJust (lookup v s) interpE fs s (StrictCall f es) = strictApplyE fs f (map (interpE fs s) es) interpE fs s (IfThenElse b t e) = case interpE fs s b of 0 -> interpE fs s e _ -> interpE fs s t interpE fs s (FunctionCall f es) = applyE fs f (map (interpE fs s) es) strictApplyE fs "*" [x,y] = x*y strictApplyE fs "-" [x,y] = x-y strictApplyE _ f args = error (f ++ " called badly with " ++ show (length args) ++ " args") applyE :: [F] -> String -> [Int] -> Int applyE fs f args = case lookup f fs of Just (vars := body) -> interpE fs (zip vars args) body _ -> error ("No such function: " ++ f)
orchid-hybrid/absint-study
Ch2_Strictness.hs
gpl-2.0
1,371
0
15
339
609
318
291
31
2
module TypedPE where import Data.List (union, intersect, (\\)) import Exp import Type import TypedExp data PrefixSpecies = LambdaPT | FixPT | LetPT deriving (Show, Eq) type TypedPrefix = (PrefixSpecies, Id, Type) type TypedPE = ([TypedPrefix], TypedExp) prefixSpecies :: TypedPrefix -> PrefixSpecies prefixSpecies (p,v,t) = p prefixVar :: TypedPrefix -> Id prefixVar (p,v,t) = v prefixType :: TypedPrefix -> Type prefixType (p,v,t) = t subTypedPEs :: TypedPE -> [TypedPE] subTypedPEs (p,e) = (p,e) : concatMap subTypedPEs (pes' p e) where transitive (p,e) = subTypedPEs (p,e) pes' :: [TypedPrefix] -> TypedExp -> [TypedPE] pes' p e = case e of IdT x t -> [] ApplyT e e' t -> [(p,e), (p,e')] CondT e e' e'' t -> [(p,e), (p,e'), (p,e'')] LambdaT x t' e t -> [(pushLambda x t' p, e)] FixT x t' e t -> [(pushFix x t' p, e)] LetT x t' e e' t -> [(p, e), (pushLet x t' p, e')] genericVars :: [TypedPrefix] -> [Id] genericVars xs = typeVarsIn xs \\ typeVarsIn (filter lambdaBound xs) lambdaBound :: TypedPrefix -> Bool lambdaBound p = prefixSpecies p /= LetPT typeVarsIn :: [TypedPrefix] -> [Id] typeVarsIn = foldl union [] . map (typeVariables . prefixType) pushLambda, pushFix, pushLet :: Id -> Type -> [TypedPrefix] -> [TypedPrefix] pushLambda = pushTP LambdaPT pushFix = pushTP FixPT pushLet = pushTP LetPT pushTP :: PrefixSpecies -> Id -> Type -> [TypedPrefix] -> [TypedPrefix] pushTP s x t p = (s,x,t):p -- TypedPrefix list is backwards compared to the paper, so -- innermost scope is to the left. This is because it's simpler -- to cons a new element onto the left of a list than to concat -- it onto the right. findActive :: Id -> [TypedPrefix] -> Maybe TypedPrefix findActive x [] = Nothing findActive x (p:ps) = if prefixVar p == x then Just p else findActive x ps
pbevin/milner-type-poly
src/TypedPE.hs
gpl-2.0
1,908
0
12
449
746
417
329
42
6
{-| Unittest runner for ganeti-htools -} {- Copyright (C) 2009, 2011 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Main(main) where import Data.IORef import Test.QuickCheck import System.Console.GetOpt import System.IO import System.Exit import System (getArgs) import Text.Printf import Ganeti.HTools.QC import Ganeti.HTools.CLI import Ganeti.HTools.Utils (sepSplit) -- | Options list and functions options :: [OptType] options = [ oReplay , oVerbose , oShowVer , oShowHelp ] fast :: Args fast = stdArgs { maxSuccess = 500 , chatty = False } slow :: Args slow = stdArgs { maxSuccess = 50 , chatty = False } incIORef :: IORef Int -> IO () incIORef ir = atomicModifyIORef ir (\x -> (x + 1, ())) -- | Wrapper over a test runner with error counting wrapTest :: IORef Int -> (Args -> IO Result) -> Args -> IO (Result, Char) wrapTest ir test opts = do r <- test opts c <- case r of Success {} -> return '.' GaveUp {} -> return '?' Failure {} -> incIORef ir >> return '#' NoExpectedFailure {} -> incIORef ir >> return '*' return (r, c) runTests name opts tests max_count = do _ <- printf "%25s : " name hFlush stdout results <- mapM (\t -> do (r, c) <- t opts putChar c hFlush stdout return r ) tests let alldone = sum . map numTests $ results _ <- printf "%*s(%d)\n" (max_count - length tests + 1) " " alldone mapM_ (\(idx, r) -> case r of Failure { output = o, usedSeed = u, usedSize = size } -> printf "Test %d failed (seed was %s, test size %d): %s\n" idx (show u) size o GaveUp { numTests = passed } -> printf "Test %d incomplete: gave up with only %d\ \ passes after discarding %d tests\n" idx passed (maxDiscard opts) _ -> return () ) $ zip ([1..]::[Int]) results return results allTests :: [(String, Args, [Args -> IO Result])] allTests = [ ("Utils", fast, testUtils) , ("PeerMap", fast, testPeerMap) , ("Container", fast, testContainer) , ("Instance", fast, testInstance) , ("Node", fast, testNode) , ("Text", fast, testText) , ("OpCodes", fast, testOpCodes) , ("Jobs", fast, testJobs) , ("Loader", fast, testLoader) , ("Cluster", slow, testCluster) ] transformTestOpts :: Args -> Options -> IO Args transformTestOpts args opts = do r <- case optReplay opts of Nothing -> return Nothing Just str -> do let vs = sepSplit ',' str (case vs of [rng, size] -> return $ Just (read rng, read size) _ -> fail "Invalid state given") return args { chatty = optVerbose opts > 1, replay = r } main :: IO () main = do errs <- newIORef 0 let wrap = map (wrapTest errs) cmd_args <- System.getArgs (opts, args) <- parseOpts cmd_args "test" options let tests = if null args then allTests else filter (\(name, _, _) -> name `elem` args) allTests max_count = maximum $ map (\(_, _, t) -> length t) tests mapM_ (\(name, targs, tl) -> transformTestOpts targs opts >>= \newargs -> runTests name newargs (wrap tl) max_count) tests terr <- readIORef errs (if terr > 0 then do hPutStrLn stderr $ "A total of " ++ show terr ++ " tests failed." exitWith $ ExitFailure 1 else putStrLn "All tests succeeded.")
ekohl/ganeti
htools/test.hs
gpl-2.0
4,312
0
20
1,317
1,191
631
560
103
4
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} module Dolls.Controller where import Control.Lens ((^.)) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE) import Crypto.Hash.MD5 (hashlazy) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Base16 as BS16 import qualified Data.Text as T import Data.Text (Text) import qualified Network.Wreq as Wreq import Network.Wai (Response) import System.FilePath (takeBaseName) import Text.ParserCombinators.Parsec import Web.Fn import Web.Larceny (subs, textFill) import Ctxt import Kiss import Dolls.Model import Dolls.View import Upload import Users.Model import Users.View mkDoll :: String -> Maybe Text -> BS.ByteString -> FilePath -> NewDoll mkDoll name otakuworldUrl hash loc = do NewDoll (T.pack name) otakuworldUrl hash (Just (T.pack loc)) Nothing hashFile :: LBS.ByteString -> BS.ByteString hashFile = BS16.encode . hashlazy fileUploadHandler :: Ctxt -> File -> IO (Maybe Response) fileUploadHandler ctxt (File name _ filePath') = do hash <- hashFile <$> LBS.readFile filePath' output <- runExceptT $ createOrLoadDoll ctxt Nothing (takeBaseName (T.unpack name)) Nothing hash renderKissDoll ctxt output linkUploadHandler :: Ctxt -> Text -> IO (Maybe Response) linkUploadHandler ctxt link = do let mOtakuWorldUrl = otakuWorldUrl link case mOtakuWorldUrl of Right dollname -> do result <- runExceptT $ do mExistingUrlDoll <- liftIO $ getDollByOWUrl ctxt link case mExistingUrlDoll of Nothing -> do resp <- liftIO $ Wreq.get (T.unpack link) let body = resp ^. Wreq.responseBody liftIO $ LBS.writeFile ("static/sets/" ++ dollname ++ ".lzh") body let hash = hashFile body createOrLoadDoll ctxt Nothing dollname (Just link) hash Just doll -> getCels doll renderKissDoll ctxt result Left _ -> renderWith ctxt ["index"] errorSplices where errorSplices = subs [("linkErrors", textFill "Invalid OtakuWorld URL")] <> createUserErrorSplices otakuWorldUrl url = parse parseUrl "" (T.unpack url) parseUrl = do string "http://otakuworld.com/data/kiss/data/" optional $ alphaNum >> char '/' filename <- many (alphaNum <|> oneOf "_-") string ".lzh" return filename -- Looks up the doll by the filehash. If doll with that hash already -- exists, it reads the CNF and returns a directory where the cels -- are stored plus a list of the cels. If no doll with that hash -- already exists, then it creates a new doll and processes it. createOrLoadDoll :: Ctxt -> Maybe Text -> [Char] -> Maybe Text -> BS.ByteString -> ExceptT Text IO (FilePath, [KissCel]) createOrLoadDoll ctxt mUser dollname mLink hash = do mExistingHashDoll <- liftIO $ getDollByHash ctxt hash case mExistingHashDoll of Nothing -> let newDoll = mkDoll dollname mLink hash ("static/sets/" ++ dollname) in processNewDoll ctxt mUser newDoll Just doll -> loadExistingDoll ctxt doll dollname mLink processNewDoll :: Ctxt -> Maybe Text -> NewDoll -> ExceptT Text IO (FilePath, [KissCel]) processNewDoll ctxt mUser newDoll = do let filename = T.unpack (newDollName newDoll <> ".lzh") output <- processDoll mUser (filename, "static/sets/" ++ filename) created <- liftIO $ createDoll ctxt newDoll if created then return output else throwE "Something went wrong" loadExistingDoll :: Ctxt -> Doll -> String -> Maybe Text -> ExceptT Text IO (FilePath, [KissCel]) loadExistingDoll ctxt existingDoll dollname mLink = do mUpdatedDoll <- case mLink of Nothing -> return (Just existingDoll) Just link -> liftIO (updateDollWithUrl ctxt existingDoll dollname link) maybe (getCels existingDoll) getCels mUpdatedDoll userUploadHandler :: User -> Ctxt -> File -> IO (Maybe Response) userUploadHandler user ctxt (File name _ filePath') = do let mUsername = Just (userUsername user) let dollname = takeBaseName (T.unpack name) hash <- hashFile <$> liftIO (LBS.readFile filePath') output <- runExceptT $ createOrLoadDoll ctxt mUsername dollname Nothing hash renderKissDoll ctxt output -- TODO: This should use `getCels` instead of create cels, but -- we can implement that when we add a relation between Users and -- dolls in the database userDollHandler :: User -> Ctxt -> T.Text -> IO (Maybe Response) userDollHandler user ctxt setName = do let userDir = staticUserDir (userUsername user) let staticDir = staticDollDir userDir (T.unpack setName) output <- (fmap . fmap) (staticDir,) (runExceptT $ createCels staticDir) -- The previous line is a bit weird. -- the result of runEitherT is an `IO (Either Text [KissCel])`. -- `renderKissDoll` wants an `Either Text (FilePath, [KissCel])` -- The `(staticDir,)` part uses Tuple Sections to turn the directory and a -- cel into a tuple. -- `(fmap . fmap)` let's us map into two layers of functions -- first the -- IO functor, then then Either functor. This makes the Right side of -- the Either a tuple! Whew. renderKissDoll ctxt output renderKissDoll :: Ctxt -> Either T.Text (FilePath, [KissCel]) -> IO (Maybe Response) renderKissDoll ctxt eOutputError = case eOutputError of Right (staticDir, cels) -> renderWith ctxt ["users", "kiss-set"] $ setSplices staticDir cels Left e -> errText e
emhoracek/smooch
app/src/Dolls/Controller.hs
gpl-3.0
6,052
0
26
1,613
1,499
758
741
120
3
{-# LANGUAGE OverloadedStrings #-} -- | A simple fileserver that uses the @sendfile(2)@ system call: -- -- - receive and parse the incoming request, and -- -- - @sendfile@ the requested file. -- module Main where import Data.ByteString.Char8 () import Network.Socket ( Socket ) import Network.Socket.ByteString ( sendAll ) import Network.Socket.SendFile ( sendFile ) import Utils ( runAcceptLoop, bindPort, readRequestUri ) main :: IO () main = do lsocket <- bindPort 5000 runAcceptLoop lsocket handleRequest handleRequest :: Socket -> IO () handleRequest sock = do uri <- readRequestUri sock sendAll sock "HTTP/1.1 200 OK\r\n\r\n" sendFile sock uri
scvalex/dissemina2
SendFile.hs
gpl-3.0
676
0
8
123
147
81
66
16
1
module System.DevUtils.Parser.KV.ByteString ( defaultKV, runKV, weirdKV ) where -- runKV defaultKV ";a=1\r\nb=2\rc=1\nd=2\r\ne=1\n>f=odkgodkgsdo" -- runKV weirdKV "h>1.g>2{....}p>1" import Text.Parsec import Text.Parsec.ByteString import qualified Data.ByteString.Char8 as B import Data.Maybe type Pair = (B.ByteString, B.ByteString) type St a = GenParser Char KV a data KV = KV { _ident :: St String, _delim :: St String, _eol :: St String, _comment :: St String } defaultKV :: KV defaultKV = KV { _ident = (many1 $ try letter <|> try digit <|> try (oneOf "_-")), _delim = (try (string "=") <|> try (string "->") <|> try (string ":")), _eol = (try (string "\r\n") <|> try (string "\r") <|> try (string "\n")), _comment = (try (string "#") <|> try (string ";")) } weirdKV :: KV weirdKV = KV { _ident = (many1 $ try letter), _delim = (try (string ">")), _eol = (try (string ".")), _comment = do { string "{" ; ; manyTill anyChar (try (string "}")) } } ident :: St String ident = do st <- getState _ident st comment :: St () comment = do st <- getState _comment st _ <- manyTill anyChar $_eol st return () eol :: St () eol = do st <- getState _eol st return () item :: St (B.ByteString, B.ByteString) item = do st <- getState key <- ident skipMany space _delim st skipMany space value <- manyTill anyChar (try eol <|> try comment <|> try eof) return (B.pack key, B.pack value) line :: St (Maybe (B.ByteString, B.ByteString)) line = do do { try $ skipMany space ; try (comment >> return Nothing) <|> try (item >>= return . Just) } parseKV :: St [Pair] parseKV = do kvlines <- many line <?> "line" return $ catMaybes kvlines runKV' :: KV -> St [Pair] -> B.ByteString -> Either String [Pair] runKV' kv p input = do case (runParser p kv "KV" input) of Left err -> Left $ "Parser error: " ++ show err Right val -> Right val runKV :: KV -> B.ByteString -> Either String [Pair] runKV kv input = runKV' kv parseKV input
adarqui/DevUtils-Parser
src/System/DevUtils/Parser/KV/ByteString.hs
gpl-3.0
2,001
1
13
434
867
440
427
68
2
module Teb.Types where type CurrentWorkingDirectory = String type Arguments = [String] type TebManifestFile = String type RemoteLocator = String
ignesco/teb-h
Teb/Types.hs
gpl-3.0
146
0
5
20
33
22
11
5
0
module Murex.Syntax.Abstract where import Import import Data.Sequence ( Seq, (|>), (<|), (><) , ViewL(..), ViewR(..), viewl, viewr) import qualified Data.Sequence as S import Data.Foldable (toList) data AST = Lit Literal | Sequence [AST] | Record (AList Label AST) | Variant Label AST | Var Symbol | Define AST AST | Lambda [Symbol] AST | Apply [AST] | Block [AST] | LetIn AST AST | Builtin Builtin | Project Label | Modify Label AST | Update Label AST data Literal = MurexUnit | MurexBool Bool | MurexNum Rational | MurexInf | MurexNegZ | MurexNegInf | MurexNaN -- | MurexNat Natural --package: natural-numbers -- | MurexInt Integer -- | MurexRat Rational -- | MurexI64 Int64 | MurexI32 Int32 | MurexI16 Int16 | MurexI8 Int8 -- | MurexW64 Word64 | MurexW32 Word32 | MurexW16 Word16 | MurexW8 Word8 -- | MurexF64 Double | Murex32 Float | MurexChar Char | MurexSeq (Seq Literal) | MurexRecord (AList Label Literal) | MurexVariant Label Literal -- | MurexBits TODO -- | MurexRef (MVar Literal) | MurexSharedRef (IORef Literal) -- | MurexArray (IOArray Int Literal) -- | MurexChan Chan -- | MurexHandle Handle -- | MurexHandler TODO deriving (Eq) data Builtin = PutChr | GetChr | PutStr | GetStr --TODO more general IO -- logic | NotBool | EqBool | AndBool | OrBool | XorBool | ElimBool -- arithmentic | NegNum | AddNum | SubNum | MulNum | QuoNum | RemNum | QuoremNum | DivNum | IPowNum | IRootNum -- relationals and predicates | EqNum | NeqNum | LtNum | GtNum | LteNum | GteNum | IsInfNum | IsNanNum | IsZNum | IsPosNum | IsNegNum -- floating point | Exp | Log | Pow | Root | FMA | Sin | Cos | Sincos | Tan | Sinh | Cosh | Sincosh | Tanh | ASin | ACos | ASincos | ATan | ASinh | ACosh | ASincosh | ATanh -- TODO floating point exceptions -- characters | EqChr -- conversions | Numer | Denom | NumChr | ChrNum --TODO more conversions -- sequences | LenSeq | IxSeq | SetSeq | ConsSeq | SnocSeq | CatSeq | HeadSeq | TailSeq | InitSeq | LastSeq deriving (Show, Eq) ------ Murex <-> Haskell ------ instance Show AST where show (Lit x) = show x show (Sequence xs) = "Sequence [" ++ intercalate ", " (show <$> xs) ++ "]" show (Record xs) = "Record [" ++ intercalate ", " (showRecordItem <$> xs) ++ "]" show (Variant l x) = "Variant (" ++ showRecordItem (l, x) ++ ")" show (Var x) = unintern x show (Define x e) = "Define (" ++ show x ++ ") (" ++ show e ++ ")" show (Lambda xs e) = "Lambda [" ++ intercalate ", " (unintern <$> xs) ++ "] (" ++ show e ++ ")" show (Apply es) = "Apply [" ++ intercalate ", " (show <$> es) ++ "]" show (Block es) = "Block [" ++ intercalate ", " (show <$> es) ++ "]" show (LetIn def body) = "Let (" ++ show def ++ ") (" ++ show body ++ ")" show (Project l) = "Project " ++ showLabel l show (Modify l f) = "Modify " ++ showLabel l ++ " (" ++ show f ++ ")" show (Update l f) = "Update " ++ showLabel l ++ " (" ++ show f ++ ")" instance Show Literal where show MurexUnit = "()" show (MurexBool True) = "True" show (MurexBool False) = "False" show (MurexNum x) = if denominator x == 1 then show (numerator x) else show (numerator x) ++ "/" ++ show (denominator x) show (MurexChar c) = show c --TODO show like murex parses show (MurexSeq s) = maybe (show $ toList s) show (fromMurexString s) show (MurexRecord xs) = "{" ++ intercalate ", " (map showRecordItem xs) ++ "}" show (MurexVariant l x) = "{" ++ showRecordItem (l, x) ++ "}" showRecordItem (Left l, x) = "`" ++ show l ++ " " ++ show x showRecordItem (Right l, x) = "`" ++ l ++ " " ++ show x showLabel (Left l) = show l showLabel (Right l) = l fromMurexChar :: Literal -> Char fromMurexChar (MurexChar c) = c toMurexChar :: Char -> Literal toMurexChar c = MurexChar c toMurexString :: String -> Literal toMurexString = MurexSeq . S.fromList . map MurexChar fromMurexString :: Seq Literal -> Maybe String fromMurexString s = let s' = toList s in if all isChar s' then Just (map fromMurexChar s') else Nothing where isChar (MurexChar _) = True isChar _ = False
Zankoku-Okuno/murex
Murex/Syntax/Abstract.hs
gpl-3.0
4,869
0
12
1,696
1,405
769
636
87
3
module Utils ( squear , mag2 , indexToK , indexFromK ) where import Control.Monad (join) import Data.Complex (Complex(..), realPart, conjugate) squear :: Num a => a -> a squear = join (*) mag2 :: RealFloat a => Complex a -> a mag2 x = realPart $ (conjugate x) * x -- functions to convert indexies [0..(n-1)] <--> [-k..k] -- it is needed because of DFT properties indexToK :: Int -> Int -> Int indexToK n i | i <= nk = i | otherwise = i - n where nk = (n - 1) `div` 2 indexFromK :: Int -> Int -> Int indexFromK n k | k >= 0 = k | otherwise = n + k where nk = (n-1) `div` 2
AlexanderKoshkarov/spectralHaskellRepa
src/Utils.hs
gpl-3.0
609
0
9
161
249
135
114
21
1
module Util.Shuffle (shuffle) where import System.Random import Data.Map as M hiding (foldl) fisherYatesStep :: RandomGen g => (Map Int a, g) -> (Int, a) -> (Map Int a, g) fisherYatesStep (m, gen) (i, x) = ((insert j x . insert i (m ! j)) m, gen') where (j, gen') = randomR (0, i) gen fisherYates :: RandomGen g => g -> [a] -> ([a], g) fisherYates gen [] = ([], gen) fisherYates gen l = toElems $ foldl fisherYatesStep (initial (head l) gen) (numerate (tail l)) where toElems (x, y) = (elems x, y) numerate = zip [1..] initial x gen = (singleton 0 x, gen) shuffle :: RandomGen g => g -> [a] -> ([a], g) shuffle = fisherYates
EPashkin/gamenumber-gloss
src/Util/Shuffle.hs
gpl-3.0
653
0
11
148
350
193
157
15
1
-- https://esolangs.org/wiki/Brainfuck -- Build: ghc --make brainfuck -- Usage: brainfuck SRC-FILE import Data.Char(chr,ord) import System.Environment(getArgs) bf :: Integral cell => (String,String) -> [cell] -> [cell] -> Maybe cell -> String -> String bf ([],_) _ _ _ _ = [] bf ('>':prog,rprog) (cell:tape) rtape eof input = bf (prog,'>':rprog) tape (cell:rtape) eof input bf ('<':prog,rprog) tape (cell:rtape) eof input = bf (prog,'<':rprog) (cell:tape) rtape eof input bf ('+':prog,rprog) (cell:tape) rtape eof input = bf (prog,'+':rprog) (succ cell:tape) rtape eof input bf ('-':prog,rprog) (cell:tape) rtape eof input = bf (prog,'-':rprog) (pred cell:tape) rtape eof input bf ('.':prog,rprog) (cell:tape) rtape eof input = chr (fromIntegral cell) : bf (prog,'.':rprog) (cell:tape) rtape eof input bf (',':prog,rprog) (_:tape) rtape eof (ch:input) = bf (prog,',':rprog) (fromIntegral (ord ch):tape) rtape eof input bf (',':prog,rprog) (_:tape) rtape eof@(Just cell) [] = bf (prog,',':rprog) (cell:tape) rtape eof [] bf ('[':prog,rprog) (0:tape) rtape eof input = bf (jump (prog,'[':rprog)) (0:tape) rtape eof input bf (']':prog,rprog) tape rtape eof input = bf (jumpback (']':prog,rprog)) tape rtape eof input bf (insn:prog,rprog) tape rtape eof input = bf (prog,insn:rprog) tape rtape eof input jump :: (String,String) -> (String,String) jump ('[':prog,rprog) = jump (jump (prog,'[':rprog)) jump (']':prog,rprog) = (prog,']':rprog) jump (insn:prog,rprog) = jump (prog,insn:rprog) jump p = p jumpback :: (String,String) -> (String,String) jumpback (prog,'[':rprog) = ('[':prog,rprog) jumpback (prog,']':rprog) = jumpback (jumpback (']':prog,rprog)) jumpback (prog,insn:rprog) = jumpback (insn:prog,rprog) jumpback p = p brainfuck :: String -> IO () brainfuck prog = interact (bf (prog,"") (replicate 30000 0) [] Nothing) main :: IO () main = getArgs >>= readFile . head >>= brainfuck
qpliu/esolang
featured/brainfuck.hs
gpl-3.0
1,931
0
10
302
1,072
580
492
37
1
module Tracker where import BEncode import Torrent.Env import Peer import CompactPeer import HTorrentPrelude import Data.Attoparsec.ByteString import qualified Data.ByteString.Char8 as CBS import Network.HTTP import Network.HTTP.Types.URI import Network.Socket import Network.URI formatRequest :: TorrentInfo -> Request ByteString formatRequest i = mkRequest GET uri where query = renderSimpleQuery True [ ("info_hash", i ^. torrentHash), ("peer_id", i ^. localId), ("port", fromString (show (i ^. portNumber))), ("uploaded", fromString (show (i ^. uploaded))), ("downloaded", fromString (show 0)), ("left", fromString (show (i ^. numPieces * i ^. pieceLength))), ("compact", "1"), ("event", "started") ] uri = (i ^. tracker) {uriQuery = CBS.unpack query} parseResponse :: BEncode -> Maybe (Int, [Peer]) parseResponse b = (,) <$> i <*> ps where i = bLookup "interval" bInt b ps = bLookup "peers" bList b >>= mapM parsePeer compactResponse :: BEncode -> Maybe (Int, [SockAddr]) compactResponse b = (,) <$> i <*> ps where i = bLookup "interval" bInt b ps = bLookup "peers" bString b >>= compactPeers parseCompactResponse :: ByteString -> Maybe (Int, [SockAddr]) parseCompactResponse = (>>= compactResponse) . maybeResult . parse parseBEncode getResponse :: TorrentInfo -> IO ByteString getResponse i = simpleHTTP (formatRequest i) >>= getResponseBody trackerRequest :: TorrentInfo -> IO (Maybe (Int, [SockAddr])) trackerRequest = fmap parseCompactResponse . getResponse
ian-mi/hTorrent
Tracker.hs
gpl-3.0
1,658
0
16
389
521
290
231
38
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE DeriveDataTypeable #-} module Data.Ephys.Spike where import Data.Ephys.Timeseries.Filter import Data.Ord (comparing) import Data.Text hiding (zip, map,foldl1') import Data.Text.Encoding import Data.Time import Control.Monad (liftM) import qualified Data.Serialize as S import qualified Data.Binary as B import Data.Typeable import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import Data.Vector.Cereal import Data.Vector.Binary import Data.Ephys.EphysDefs ------------------------------------------------------------------------------ type Waveform = U.Vector Voltage -- This should be the waveform from Data.Ephys.Waveform probably? ------------------------------------------------------------------------------ -- |Representation of an action potential recorded on a tetrode data TrodeSpike = TrodeSpike { spikeTrodeName :: !Int , spikeTrodeOptsHash :: !Int , spikeTime :: !ExperimentTime , spikeWaveforms :: V.Vector Waveform } deriving (Eq, Show, Typeable) ------------------------------------------------------------------------------ spikePeakIndex :: TrodeSpike -> Int spikePeakIndex s = let chanMaxIs = V.map U.maxIndex (spikeWaveforms s) :: V.Vector Int chanMax = V.map U.maximum (spikeWaveforms s) :: V.Vector Voltage chanWithMax = V.maxIndex chanMax :: Int in chanMaxIs V.! chanWithMax ------------------------------------------------------------------------------ spikeWidth :: TrodeSpike -> Int spikeWidth s = let iChanMax = V.maxIndexBy (comparing U.maximum) (spikeWaveforms s) in chanSpikeWidth $ spikeWaveforms s V.! iChanMax ------------------------------------------------------------------------------ chanSpikeWidth :: U.Vector Voltage -> Int chanSpikeWidth vs = let tailPts = U.drop (U.maxIndex vs + 1) vs iTailMin -- Index of valley after peak | U.null tailPts = 0 | otherwise = 1 + U.minIndex tailPts in iTailMin ------------------------------------------------------------------------------ chanPeakIndexAndV :: U.Vector Voltage -> (Int,Voltage) chanPeakIndexAndV vs = U.foldl1' maxBySnd $ U.zip (U.fromList [0..nSamps]) vs where nSamps = U.length vs ------------------------------------------------------------------------------ maxBySnd :: Ord b => (a,b) -> (a,b) -> (a,b) maxBySnd a@(_,v) b@(_,v') = if v > v' then a else b ------------------------------------------------------------------------------ spikeAmplitudes :: TrodeSpike -> V.Vector Voltage spikeAmplitudes s = V.map (U.! i) (spikeWaveforms s) where i = spikePeakIndex s ------------------------------------------------------------------------------ -- |Representation of tetroe-recorded AP features data SpikeModel = SpikeModel { mSpikeTime :: ExperimentTime , mSpikePeakAmp :: U.Vector Voltage , mSpikepPeakToTroughT :: DiffTime , mSpikepPeakToTroughV :: U.Vector Voltage } deriving (Show) -- TODO: Do I need the rest of the mwl params? maxwd? maxh? -- What about things like 'noise'? Or 'deviation from the cluster'? ------------------------------------------------------------------------------ -- |Polar coordinates representation of tetrode-recorded AP data PolarSpikeModel = PolarSpikeModel { pSpikeTime :: ExperimentTime , pSpikeMagnitute :: Voltage , pSpikeAngles :: U.Vector Double } deriving (Show) ------------------------------------------------------------------------------ -- This should be part of arte, not tetrode-ephys? It's about recording -- But I need it to decode files... data TrodeAcquisitionOpts = TrodeAcquisitionOpts { spikeFilterSpec :: FilterSpec , spikeThresholds :: [Voltage] } deriving (Eq, Show) ------------------------------------------------------------------------------ toRelTime :: TrodeSpike -> Double toRelTime TrodeSpike{..} = spikeTime ------------------------------------------------------------------------------ instance S.Serialize TrodeSpike where put TrodeSpike{..} = do S.put spikeTrodeName S.put spikeTrodeOptsHash S.put spikeTime S.put spikeWaveforms get = do name <- S.get opts <- S.get time <- S.get waveforms <- S.get return $ TrodeSpike name opts time waveforms ------------------------------------------------------------------------------ instance B.Binary TrodeSpike where put TrodeSpike{..} = do B.put spikeTrodeName B.put spikeTrodeOptsHash B.put spikeTime B.put spikeWaveforms get = do name <- B.get opts <- B.get time <- B.get waveforms <- B.get return $ TrodeSpike name opts time waveforms ------------------------------------------------------------------------------ -- TODO: a test spike mySpike :: IO TrodeSpike mySpike = return $ TrodeSpike tName tOpts sTime sWF where tName = 63 tOpts = 1001 sTime = 10.10 sWF = V.replicate 4 $ U.replicate 32 0
imalsogreg/tetrode-ephys
lib/Data/Ephys/Spike.hs
gpl-3.0
5,629
0
13
1,375
1,096
591
505
101
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} module Main where import Control.Applicative import Control.Lens import Control.Monad.IO.Class import Control.Monad.Trans.Either import qualified Data.Attoparsec.ByteString.Char8 as A import qualified Data.ByteString.Char8 as B import qualified Data.Foldable as F import Data.Function (on) import qualified Data.HashMap.Strict as HM import Data.List (sortBy) import Data.Maybe import Data.Monoid import Data.Scientific import Text.Printf data Info = Info { info_hT :: Scientific -- Double , info_pT_j1 :: Scientific -- Double , info_j234 :: Scientific -- Double , info_j56 :: Scientific -- Double , info_full :: Int , info_cut1 :: Int , info_cut2 :: Int , info_cut3 :: Int , info_lepeta :: Int , info_htcut :: Int , info_bj1 :: Int , info_bj2 :: Int , info_bj3 :: Int } deriving (Show,Eq,Ord) normalizedTriple :: Info -> (Double,Double,Double,Int,Int,Int) normalizedTriple Info {..} = (fromIntegral info_bj1 / full, fromIntegral info_bj2 / full, fromIntegral info_bj3/full, info_bj1, info_bj2, info_bj3 ) where full = fromIntegral info_full normalizeInput :: Info -> (Int,Int,Int,Int) normalizeInput Info {..} = if (hT `mod` 5 /= 0 || j1 `mod` 5 /= 0 || j234 `mod` 5 /= 0 || j56 `mod` 5 /= 0) then error "error in normalizeInput" else (hT,j1,j234,j56) where hT = floor info_hT j1 = floor info_pT_j1 j234 = floor info_j234 j56 = floor info_j56 type OneRow = (First Info,First Info,First Info,First Info) data ColumnTag = TTBar | FourTop400 | FourTop750 | FourTop1000 adjustData :: ColumnTag -> ((Int,Int,Int,Int), Info) -> HM.HashMap (Int,Int,Int,Int) OneRow -> HM.HashMap (Int,Int,Int,Int) OneRow adjustData TTBar (k,i) = HM.insertWith mappend k (First (Just i), mempty, mempty, mempty) adjustData FourTop400 (k,i) = HM.insertWith mappend k (mempty, First (Just i), mempty, mempty) adjustData FourTop750 (k,i) = HM.insertWith mappend k (mempty, mempty, First (Just i), mempty) adjustData FourTop1000 (k,i) = HM.insertWith mappend k (mempty, mempty, mempty, First (Just i)) isFilled :: OneRow -> Bool isFilled (First (Just a),First (Just b), First (Just c), First (Just d)) = True isFilled _ = False maybeFilled :: OneRow -> Maybe (Info,Info,Info,Info) maybeFilled (First (Just a),First (Just b), First (Just c), First (Just d)) = Just (a,b,c,d) maybeFilled _ = Nothing removeUnfilled :: HM.HashMap (Int,Int,Int,Int) OneRow -> HM.HashMap (Int,Int,Int,Int) (Info,Info,Info,Info) removeUnfilled = HM.fromList . mapMaybe (\(k,v) -> (k,) <$> maybeFilled v) . HM.toList commentline = do A.char '#' >> A.manyTill A.anyChar A.endOfLine header = (,,) <$> commentline <*> commentline <*> commentline dataline = do A.skipSpace hT <- A.scientific A.skipSpace pT_j1 <- A.scientific A.skipSpace j234 <- A.scientific A.skipSpace j56 <- A.scientific A.skipSpace full <- A.decimal A.skipSpace cut1 <- A.decimal A.skipSpace cut2 <- A.decimal A.skipSpace cut3 <- A.decimal A.skipSpace lepeta <- A.decimal A.skipSpace htcut <- A.decimal A.skipSpace bj1 <- A.decimal A.skipSpace bj2 <- A.decimal A.skipSpace bj3 <- A.decimal A.manyTill A.anyChar A.endOfLine return (Info hT pT_j1 j234 j56 full cut1 cut2 cut3 lepeta htcut bj1 bj2 bj3) -- criterion1 :: (Double,Double,Double) -> (Double,Double,Double) -> Double criterion l1 l2 blst@(bkg1,bkg2,bkg3,_,_,_) slst@(sig1,sig2,sig3,_,_,_) = (s / b, view l2 slst) where bkg = view l1 blst sig = view l1 slst b = if bkg < 1e-6 then 1e-6 else bkg s = sig formatprint :: ((Int,Int,Int,Int),(Double,Int)) -> String formatprint ((ht,j1,j234,j56),(eff,nsig)) = printf "%6d %6d %6d %6d %.1f %4d" ht j1 j234 j56 eff nsig main :: IO () main = do putStrLn "test" bstr_ttbar1 <- B.readFile "result/cutopt20150106_ttbar012.txt" bstr_400 <- B.readFile "result/cutopt20150106_4top400.txt" bstr_750 <- B.readFile "result/cutopt20150106_4top750.txt" bstr_1000 <- B.readFile "result/cutopt20150106_4top1000.txt" r <- runEitherT $ do results_ttbar <- hoistEither $ A.parseOnly (header *> many dataline) bstr_ttbar results_400 <- hoistEither $ A.parseOnly (header *> many dataline) bstr_400 results_750 <- hoistEither $ A.parseOnly (header *> many dataline) bstr_750 results_1000 <- hoistEither $ A.parseOnly (header *> many dataline) bstr_1000 -- liftIO $ (mapM_ print . map normalizedTriple) results_ttbar let [kv_ttbar,kv_400,kv_750,kv_1000] = fmap (map ((,) <$> normalizeInput <*> id)) [results_ttbar,results_400,results_750,results_1000] let m1 = foldr (adjustData TTBar) HM.empty kv_ttbar m2 = foldr (adjustData FourTop400) m1 kv_400 m3 = foldr (adjustData FourTop750) m2 kv_750 m4 = foldr (adjustData FourTop1000) m3 kv_1000 m = removeUnfilled m4 m' = fmap (\(x,y,z,w)->(f x, f y, f z, f w)) m where f = normalizedTriple -- liftIO $ print m -- liftIO $ F.mapM_ (print . isFilled) m -- liftIO . print . HM.size $ m4 m400_1 = fmap (\(x,y,z,w)->criterion _1 _4 x y) m' m750_1 = fmap (\(x,y,z,w)->criterion _1 _4 x z) m' m1000_1 = fmap (\(x,y,z,w)->criterion _1 _4 x w) m' m400_2 = fmap (\(x,y,z,w)->criterion _2 _5 x y) m' m750_2 = fmap (\(x,y,z,w)->criterion _2 _5 x z) m' m1000_2 = fmap (\(x,y,z,w)->criterion _2 _5 x w) m' m400_3 = fmap (\(x,y,z,w)->criterion _3 _6 x y) m' m750_3 = fmap (\(x,y,z,w)->criterion _3 _6 x z) m' m1000_3 = fmap (\(x,y,z,w)->criterion _3 _6 x w) m' liftIO . F.mapM_ (putStrLn . formatprint) . sortBy (flip compare `on` snd) $ HM.toList m400_2 --liftIO $ (mapM_ print . map normalizeInput) results_ttbar --liftIO $ (mapM_ print . map normalizeInput) results_400 --liftIO $ (mapM_ print . map normalizeInput) results_750 --liftIO $ (mapM_ print . map normalizeInput) results_1000 return () print r return ()
wavewave/lhc-analysis-collection
heavyhiggs/optresult.hs
gpl-3.0
6,385
0
20
1,586
2,340
1,274
1,066
129
2
module Engine.Graphics.Render(render) where import Engine.Graphics.Render.Depth import Engine.Graphics.Render.Light import Engine.Graphics.Render.ShadowVolume import qualified Graphics.GLUtil.Camera3D as GLUtilC import Graphics.Rendering.OpenGL import qualified Graphics.UI.GLFW as GLFW import qualified Linear as L import Model.Camera import Model.ClearColor import Model.GameState import Model.Types import Model.World render :: World -> GLFW.Window -> IO () render (gs, _) w = do clearColor $= toGLColor (gsClearColor gs) (width, height) <- GLFW.getFramebufferSize w let cam = gsCamera gs lights = gsLights gs camPos = cPosition cam viewProjMat = mkViewProjMat width height cam ambiance = gsAmbiance gs lightShader = getLightShader gs shadowVolShader = getShadowShader gs depthShader = getDepthShader gs objects = gsObjects gs -- write to depth buffer -- Render ambiance everywhere. Write to depth-buffer. depthMask $= Enabled clear [ColorBuffer, DepthBuffer, StencilBuffer] colorMask $= Color4 Disabled Disabled Disabled Disabled cullFace $= Just Back renderDepth viewProjMat depthShader objects -- foreach light: mapM_ (\l -> do -- Depth fail, mark shadow volumes in the stencil buffer. depthMask $= Disabled clear [StencilBuffer] cullFace $= Nothing colorMask $= Color4 Disabled Disabled Disabled Disabled stencilTest $= Enabled stencilFunc $= (Always, 0, 0xFF) stencilOpSeparate Back $= (OpKeep, OpIncrWrap, OpKeep) stencilOpSeparate Front $= (OpKeep, OpDecrWrap, OpKeep) renderShadowVolumeToStencil viewProjMat l shadowVolShader objects -- using given stencil info. -- Draw the scene with lights. depthMask $= Enabled colorMask $= Color4 Enabled Enabled Enabled Enabled stencilFunc $= (Equal, 0, 0xff) stencilOpSeparate Front $= (OpKeep, OpKeep, OpKeep) cullFace $= Just Back blend $= Enabled -- Max looks good on the 1 test I did, maybe not overall? -- BlendEquation $= FuncAdd blendEquation $= Max blendFunc $= (One, One) renderLightedObjects viewProjMat l camPos lightShader objects blend $= Disabled stencilTest $= Disabled ) lights colorMask $= (Color4 Enabled Enabled Enabled Enabled) cullFace $= Just Back blend $= Enabled blendEquation $= FuncAdd blendFunc $= (One, One) renderAmbientObjects viewProjMat (head lights) camPos lightShader ambiance objects blend $= Disabled mkViewProjMat :: Int -> Int -> Camera -> TransformationMatrix mkViewProjMat width height camera = projMat L.!*! viewMat where viewMat = GLUtilC.camMatrix cam cam = GLUtilC.panRad pan . GLUtilC.tiltRad tilt . GLUtilC.dolly pos $ GLUtilC.fpsCamera tilt = cTilt camera pan = cPan camera pos = cPosition camera projMat = GLUtilC.projectionMatrix fov aspect nearClip farClip aspect = fromIntegral width / fromIntegral height fov = cFov camera nearClip = 0.01 farClip = 100
halvorgb/AO2D
src/Engine/Graphics/Render.hs
gpl-3.0
3,641
0
13
1,254
794
405
389
74
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CloudHSM.DeleteHsm -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Deletes an HSM. Once complete, this operation cannot be undone and your key -- material cannot be recovered. -- -- <http://docs.aws.amazon.com/cloudhsm/latest/dg/API_DeleteHsm.html> module Network.AWS.CloudHSM.DeleteHsm ( -- * Request DeleteHsm -- ** Request constructor , deleteHsm -- ** Request lenses , dhHsmArn -- * Response , DeleteHsmResponse -- ** Response constructor , deleteHsmResponse -- ** Response lenses , dhr1Status ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CloudHSM.Types import qualified GHC.Exts newtype DeleteHsm = DeleteHsm { _dhHsmArn :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'DeleteHsm' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dhHsmArn' @::@ 'Text' -- deleteHsm :: Text -- ^ 'dhHsmArn' -> DeleteHsm deleteHsm p1 = DeleteHsm { _dhHsmArn = p1 } -- | The ARN of the HSM to delete. dhHsmArn :: Lens' DeleteHsm Text dhHsmArn = lens _dhHsmArn (\s a -> s { _dhHsmArn = a }) newtype DeleteHsmResponse = DeleteHsmResponse { _dhr1Status :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'DeleteHsmResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dhr1Status' @::@ 'Text' -- deleteHsmResponse :: Text -- ^ 'dhr1Status' -> DeleteHsmResponse deleteHsmResponse p1 = DeleteHsmResponse { _dhr1Status = p1 } -- | The status of the action. dhr1Status :: Lens' DeleteHsmResponse Text dhr1Status = lens _dhr1Status (\s a -> s { _dhr1Status = a }) instance ToPath DeleteHsm where toPath = const "/" instance ToQuery DeleteHsm where toQuery = const mempty instance ToHeaders DeleteHsm instance ToJSON DeleteHsm where toJSON DeleteHsm{..} = object [ "HsmArn" .= _dhHsmArn ] instance AWSRequest DeleteHsm where type Sv DeleteHsm = CloudHSM type Rs DeleteHsm = DeleteHsmResponse request = post "DeleteHsm" response = jsonResponse instance FromJSON DeleteHsmResponse where parseJSON = withObject "DeleteHsmResponse" $ \o -> DeleteHsmResponse <$> o .: "Status"
dysinger/amazonka
amazonka-cloudhsm/gen/Network/AWS/CloudHSM/DeleteHsm.hs
mpl-2.0
3,252
0
9
774
450
273
177
56
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Logging.BillingAccounts.Locations.Operations.Cancel -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Starts asynchronous cancellation on a long-running operation. The server -- makes a best effort to cancel the operation, but success is not -- guaranteed. If the server doesn\'t support this method, it returns -- google.rpc.Code.UNIMPLEMENTED. Clients can use Operations.GetOperation -- or other methods to check whether the cancellation succeeded or whether -- the operation completed despite cancellation. On successful -- cancellation, the operation is not deleted; instead, it becomes an -- operation with an Operation.error value with a google.rpc.Status.code of -- 1, corresponding to Code.CANCELLED. -- -- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.billingAccounts.locations.operations.cancel@. module Network.Google.Resource.Logging.BillingAccounts.Locations.Operations.Cancel ( -- * REST Resource BillingAccountsLocationsOperationsCancelResource -- * Creating a Request , billingAccountsLocationsOperationsCancel , BillingAccountsLocationsOperationsCancel -- * Request Lenses , balocXgafv , balocUploadProtocol , balocAccessToken , balocUploadType , balocPayload , balocName , balocCallback ) where import Network.Google.Logging.Types import Network.Google.Prelude -- | A resource alias for @logging.billingAccounts.locations.operations.cancel@ method which the -- 'BillingAccountsLocationsOperationsCancel' request conforms to. type BillingAccountsLocationsOperationsCancelResource = "v2" :> CaptureMode "name" "cancel" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] CancelOperationRequest :> Post '[JSON] Empty -- | Starts asynchronous cancellation on a long-running operation. The server -- makes a best effort to cancel the operation, but success is not -- guaranteed. If the server doesn\'t support this method, it returns -- google.rpc.Code.UNIMPLEMENTED. Clients can use Operations.GetOperation -- or other methods to check whether the cancellation succeeded or whether -- the operation completed despite cancellation. On successful -- cancellation, the operation is not deleted; instead, it becomes an -- operation with an Operation.error value with a google.rpc.Status.code of -- 1, corresponding to Code.CANCELLED. -- -- /See:/ 'billingAccountsLocationsOperationsCancel' smart constructor. data BillingAccountsLocationsOperationsCancel = BillingAccountsLocationsOperationsCancel' { _balocXgafv :: !(Maybe Xgafv) , _balocUploadProtocol :: !(Maybe Text) , _balocAccessToken :: !(Maybe Text) , _balocUploadType :: !(Maybe Text) , _balocPayload :: !CancelOperationRequest , _balocName :: !Text , _balocCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BillingAccountsLocationsOperationsCancel' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'balocXgafv' -- -- * 'balocUploadProtocol' -- -- * 'balocAccessToken' -- -- * 'balocUploadType' -- -- * 'balocPayload' -- -- * 'balocName' -- -- * 'balocCallback' billingAccountsLocationsOperationsCancel :: CancelOperationRequest -- ^ 'balocPayload' -> Text -- ^ 'balocName' -> BillingAccountsLocationsOperationsCancel billingAccountsLocationsOperationsCancel pBalocPayload_ pBalocName_ = BillingAccountsLocationsOperationsCancel' { _balocXgafv = Nothing , _balocUploadProtocol = Nothing , _balocAccessToken = Nothing , _balocUploadType = Nothing , _balocPayload = pBalocPayload_ , _balocName = pBalocName_ , _balocCallback = Nothing } -- | V1 error format. balocXgafv :: Lens' BillingAccountsLocationsOperationsCancel (Maybe Xgafv) balocXgafv = lens _balocXgafv (\ s a -> s{_balocXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). balocUploadProtocol :: Lens' BillingAccountsLocationsOperationsCancel (Maybe Text) balocUploadProtocol = lens _balocUploadProtocol (\ s a -> s{_balocUploadProtocol = a}) -- | OAuth access token. balocAccessToken :: Lens' BillingAccountsLocationsOperationsCancel (Maybe Text) balocAccessToken = lens _balocAccessToken (\ s a -> s{_balocAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). balocUploadType :: Lens' BillingAccountsLocationsOperationsCancel (Maybe Text) balocUploadType = lens _balocUploadType (\ s a -> s{_balocUploadType = a}) -- | Multipart request metadata. balocPayload :: Lens' BillingAccountsLocationsOperationsCancel CancelOperationRequest balocPayload = lens _balocPayload (\ s a -> s{_balocPayload = a}) -- | The name of the operation resource to be cancelled. balocName :: Lens' BillingAccountsLocationsOperationsCancel Text balocName = lens _balocName (\ s a -> s{_balocName = a}) -- | JSONP balocCallback :: Lens' BillingAccountsLocationsOperationsCancel (Maybe Text) balocCallback = lens _balocCallback (\ s a -> s{_balocCallback = a}) instance GoogleRequest BillingAccountsLocationsOperationsCancel where type Rs BillingAccountsLocationsOperationsCancel = Empty type Scopes BillingAccountsLocationsOperationsCancel = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/logging.admin"] requestClient BillingAccountsLocationsOperationsCancel'{..} = go _balocName _balocXgafv _balocUploadProtocol _balocAccessToken _balocUploadType _balocCallback (Just AltJSON) _balocPayload loggingService where go = buildClient (Proxy :: Proxy BillingAccountsLocationsOperationsCancelResource) mempty
brendanhay/gogol
gogol-logging/gen/Network/Google/Resource/Logging/BillingAccounts/Locations/Operations/Cancel.hs
mpl-2.0
7,009
0
16
1,448
797
472
325
121
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.BigtableAdmin.Projects.Instances.Tables.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new table in the specified instance. The table can be created -- with a full set of initial column families, specified in the request. -- -- /See:/ <https://cloud.google.com/bigtable/ Cloud Bigtable Admin API Reference> for @bigtableadmin.projects.instances.tables.create@. module Network.Google.Resource.BigtableAdmin.Projects.Instances.Tables.Create ( -- * REST Resource ProjectsInstancesTablesCreateResource -- * Creating a Request , projectsInstancesTablesCreate , ProjectsInstancesTablesCreate -- * Request Lenses , pitcParent , pitcXgafv , pitcUploadProtocol , pitcAccessToken , pitcUploadType , pitcPayload , pitcCallback ) where import Network.Google.BigtableAdmin.Types import Network.Google.Prelude -- | A resource alias for @bigtableadmin.projects.instances.tables.create@ method which the -- 'ProjectsInstancesTablesCreate' request conforms to. type ProjectsInstancesTablesCreateResource = "v2" :> Capture "parent" Text :> "tables" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] CreateTableRequest :> Post '[JSON] Table -- | Creates a new table in the specified instance. The table can be created -- with a full set of initial column families, specified in the request. -- -- /See:/ 'projectsInstancesTablesCreate' smart constructor. data ProjectsInstancesTablesCreate = ProjectsInstancesTablesCreate' { _pitcParent :: !Text , _pitcXgafv :: !(Maybe Xgafv) , _pitcUploadProtocol :: !(Maybe Text) , _pitcAccessToken :: !(Maybe Text) , _pitcUploadType :: !(Maybe Text) , _pitcPayload :: !CreateTableRequest , _pitcCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsInstancesTablesCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pitcParent' -- -- * 'pitcXgafv' -- -- * 'pitcUploadProtocol' -- -- * 'pitcAccessToken' -- -- * 'pitcUploadType' -- -- * 'pitcPayload' -- -- * 'pitcCallback' projectsInstancesTablesCreate :: Text -- ^ 'pitcParent' -> CreateTableRequest -- ^ 'pitcPayload' -> ProjectsInstancesTablesCreate projectsInstancesTablesCreate pPitcParent_ pPitcPayload_ = ProjectsInstancesTablesCreate' { _pitcParent = pPitcParent_ , _pitcXgafv = Nothing , _pitcUploadProtocol = Nothing , _pitcAccessToken = Nothing , _pitcUploadType = Nothing , _pitcPayload = pPitcPayload_ , _pitcCallback = Nothing } -- | Required. The unique name of the instance in which to create the table. -- Values are of the form \`projects\/{project}\/instances\/{instance}\`. pitcParent :: Lens' ProjectsInstancesTablesCreate Text pitcParent = lens _pitcParent (\ s a -> s{_pitcParent = a}) -- | V1 error format. pitcXgafv :: Lens' ProjectsInstancesTablesCreate (Maybe Xgafv) pitcXgafv = lens _pitcXgafv (\ s a -> s{_pitcXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pitcUploadProtocol :: Lens' ProjectsInstancesTablesCreate (Maybe Text) pitcUploadProtocol = lens _pitcUploadProtocol (\ s a -> s{_pitcUploadProtocol = a}) -- | OAuth access token. pitcAccessToken :: Lens' ProjectsInstancesTablesCreate (Maybe Text) pitcAccessToken = lens _pitcAccessToken (\ s a -> s{_pitcAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pitcUploadType :: Lens' ProjectsInstancesTablesCreate (Maybe Text) pitcUploadType = lens _pitcUploadType (\ s a -> s{_pitcUploadType = a}) -- | Multipart request metadata. pitcPayload :: Lens' ProjectsInstancesTablesCreate CreateTableRequest pitcPayload = lens _pitcPayload (\ s a -> s{_pitcPayload = a}) -- | JSONP pitcCallback :: Lens' ProjectsInstancesTablesCreate (Maybe Text) pitcCallback = lens _pitcCallback (\ s a -> s{_pitcCallback = a}) instance GoogleRequest ProjectsInstancesTablesCreate where type Rs ProjectsInstancesTablesCreate = Table type Scopes ProjectsInstancesTablesCreate = '["https://www.googleapis.com/auth/bigtable.admin", "https://www.googleapis.com/auth/bigtable.admin.table", "https://www.googleapis.com/auth/cloud-bigtable.admin", "https://www.googleapis.com/auth/cloud-bigtable.admin.table", "https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsInstancesTablesCreate'{..} = go _pitcParent _pitcXgafv _pitcUploadProtocol _pitcAccessToken _pitcUploadType _pitcCallback (Just AltJSON) _pitcPayload bigtableAdminService where go = buildClient (Proxy :: Proxy ProjectsInstancesTablesCreateResource) mempty
brendanhay/gogol
gogol-bigtableadmin/gen/Network/Google/Resource/BigtableAdmin/Projects/Instances/Tables/Create.hs
mpl-2.0
5,999
0
17
1,331
795
466
329
120
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.AdSenseHost.CustomChannels.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Add a new custom channel to the host AdSense account. -- -- /See:/ <https://developers.google.com/adsense/host/ AdSense Host API Reference> for @adsensehost.customchannels.insert@. module Network.Google.Resource.AdSenseHost.CustomChannels.Insert ( -- * REST Resource CustomChannelsInsertResource -- * Creating a Request , customChannelsInsert , CustomChannelsInsert -- * Request Lenses , cciPayload , cciAdClientId ) where import Network.Google.AdSenseHost.Types import Network.Google.Prelude -- | A resource alias for @adsensehost.customchannels.insert@ method which the -- 'CustomChannelsInsert' request conforms to. type CustomChannelsInsertResource = "adsensehost" :> "v4.1" :> "adclients" :> Capture "adClientId" Text :> "customchannels" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] CustomChannel :> Post '[JSON] CustomChannel -- | Add a new custom channel to the host AdSense account. -- -- /See:/ 'customChannelsInsert' smart constructor. data CustomChannelsInsert = CustomChannelsInsert' { _cciPayload :: !CustomChannel , _cciAdClientId :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CustomChannelsInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cciPayload' -- -- * 'cciAdClientId' customChannelsInsert :: CustomChannel -- ^ 'cciPayload' -> Text -- ^ 'cciAdClientId' -> CustomChannelsInsert customChannelsInsert pCciPayload_ pCciAdClientId_ = CustomChannelsInsert' {_cciPayload = pCciPayload_, _cciAdClientId = pCciAdClientId_} -- | Multipart request metadata. cciPayload :: Lens' CustomChannelsInsert CustomChannel cciPayload = lens _cciPayload (\ s a -> s{_cciPayload = a}) -- | Ad client to which the new custom channel will be added. cciAdClientId :: Lens' CustomChannelsInsert Text cciAdClientId = lens _cciAdClientId (\ s a -> s{_cciAdClientId = a}) instance GoogleRequest CustomChannelsInsert where type Rs CustomChannelsInsert = CustomChannel type Scopes CustomChannelsInsert = '["https://www.googleapis.com/auth/adsensehost"] requestClient CustomChannelsInsert'{..} = go _cciAdClientId (Just AltJSON) _cciPayload adSenseHostService where go = buildClient (Proxy :: Proxy CustomChannelsInsertResource) mempty
brendanhay/gogol
gogol-adsense-host/gen/Network/Google/Resource/AdSenseHost/CustomChannels/Insert.hs
mpl-2.0
3,363
0
14
741
386
232
154
64
1
{-# LANGUAGE NoMonomorphismRestriction #-} -- | -- Module : GameKeeper.Nagios -- Copyright : (c) 2012-2015 Brendan Hay <brendan@soundcloud.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan@soundcloud.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module GameKeeper.Nagios ( -- * Exported Types Health(..) , Message , Status(..) , Plugin(..) , Check(..) -- * Functions , check ) where import Control.Exception import Data.List (nub, intercalate) import qualified Data.ByteString.Char8 as BS import qualified System.Exit as E type Title = BS.ByteString type Service = BS.ByteString type Message = String data Health = Health Double Double deriving (Eq, Show) data Status = OK { title' :: Title , message :: Message } -- ^ The plugin was able to check the service and -- it appeared to be functioning properly | Warning { title' :: Title , message :: Message } -- ^ The plugin was able to check the service, -- but it appeared to be above some "warning" -- threshold or did not appear to be working properly | Critical { title' :: Title , message :: Message } -- ^ The plugin detected that either the service was -- not running or it was above some "critical" threshold | Unknown { title' :: Title , message :: Message } -- ^ Invalid command line arguments were supplied -- to the plugin or low-level failures internal -- to the plugin (such as unable to fork, or open a tcp socket) -- that prevent it from performing the specified operation. -- Higher-level errors (such as name resolution errors, socket timeouts, etc) -- are outside of the control of plugins and should -- generally NOT be reported as UNKNOWN states. deriving (Eq, Show) data Plugin = Plugin Title Service [Check] data Check = Check { title :: Title , value :: Either SomeException Double , health :: Health , ok :: String -> Double -> Message , warning :: String -> Double -> Double -> Message , critical :: String -> Double -> Double -> Message } -- -- API -- check :: Plugin -> IO () check (Plugin title serv checks) = do BS.putStrLn $ format acc mapM_ (BS.putStrLn . format) res E.exitWith $ code acc where res = map (status serv) checks acc = fold title res -- -- Private -- status :: Service -> Check -> Status status _ Check{ title = title, value = Left e } = Unknown title $ show e status serv Check{..} | n >= y = Critical title $ critical serv' n x | n >= x = Warning title $ warning serv' n y | otherwise = OK title $ ok serv' n where (Right n) = value (Health x y) = health serv' = BS.unpack serv fold :: Service -> [Status] -> Status fold serv lst | length ok == length lst = OK serv "All services healthy" | any' crit = Critical serv $ text crit | any' unkn = Unknown serv $ text unkn | any' warn = Warning serv $ text warn | otherwise = Unknown serv $ text unkn where [ok, warn, crit, unkn] = split lst any' = not . null text = intercalate ", " . nub . map message split :: [Status] -> [[Status]] split lst = map f [0..3] where f n = filter ((== n) . enum) lst enum :: Status -> Int enum (OK _ _) = 0 enum (Warning _ _) = 1 enum (Critical _ _) = 2 enum (Unknown _ _) = 3 symbol :: Status -> BS.ByteString symbol s = case enum s of 0 -> "OK" 1 -> "WARNING" 2 -> "CRITICAL" _ -> "UNKNOWN" format :: Status -> BS.ByteString format s = BS.concat [title' s, " ", symbol s, ": ", BS.pack $ message s] code :: Status -> E.ExitCode code (OK _ _) = E.ExitSuccess code s = E.ExitFailure $ enum s
brendanhay/gamekeeper
src/GameKeeper/Nagios.hs
mpl-2.0
4,324
0
11
1,404
1,082
584
498
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {- | Module : $Header$ Description : Entities for tests. Copyright : (c) plaimi 2014-2015 License : AGPL-3 Maintainer : tempuhs@plaimi.net -} module Tempuhs.Spoc.Entity where import Control.Arrow ( (***), ) import Control.Lens ( (.~), (^.), (&), ) import Data.Aeson ( ToJSON, toJSON, ) import Data.Functor ( (<$>), ) import Data.Maybe ( isJust, ) import Data.Stringable ( toText, ) import Data.Time.Clock ( UTCTime, ) import Database.Persist ( Entity (Entity), ) import qualified Data.Set as Z import qualified Data.Text as T import Tempuhs.Chronology import Tempuhs.Server.Database ( mkKey, ) import Tempuhs.Spoc.Default ( attributes, specifieds, ) import Tempuhs.Spoc.Type ( AttributePair, Specified, ) instance HasRubbish a (Maybe UTCTime) => HasRubbish (Entity a) (Maybe UTCTime) where rubbish f (Entity a b) = Entity a <$> rubbish f b (=^=) :: (HasRubbish a (Maybe UTCTime), ToJSON a) => [a] -> [a] -> Bool -- | '(=^=)' takes two lists of GET results, and checks if the results in -- the first list is the same as rubbished versions of the useful results in -- the second result. (a:as) =^= (b:bs) = let rb = b ^. rubbish in isJust rb && toJSON (a & rubbish .~ rb) == toJSON b && as =^= bs [] =^= [] = True _ =^= _ = False (=^^=) :: (HasRubbish a (Maybe UTCTime), HasRubbish b (Maybe UTCTime) ,ToJSON a, ToJSON b) => [(a, [b])] -> [(a, [b])] -> Bool -- | '(=^^=)' is a special version of '(=^=)' for things with attributes. a =^^= b = and $ (fst <$> a) =^= (fst <$> b) : zipWith (=^=) (snd <$> a) (snd <$> b) clockEntity :: Integer -> T.Text -> Entity Clock -- | 'clockEntity' is a convenience function for constructing an 'Entity' -- containing a 'Clock'. clockEntity k = Entity (mkKey k) . flip Clock Nothing roleEntity :: Integer -> T.Text -> Integer -> Entity Role -- | 'roleEntity' is a convenience function for constructing an 'Entity' -- containing a 'Role'. roleEntity k n ns = Entity (mkKey k) $ Role n (mkKey ns) Nothing userEntity :: Integer -> T.Text -> Entity User -- | 'userEntity' is a convenience function for constructing an 'Entity' -- containing a 'User'. userEntity k = Entity (mkKey k) . flip User Nothing attributeEntity :: Integer -> Integer -> T.Text -> T.Text -> Entity TimespanAttribute -- | 'attributeEntity' is a convenience function for constructing -- an 'Entity' containing a 'TimespanAttribute'. attributeEntity i f k v = Entity (mkKey i) $ TimespanAttribute (mkKey f) k v Nothing timespanEntity :: Z.Set Specified -> Entity Timespan -- | 'timespanEntity' is a convenience function for constructing -- an 'Entity' containing a 'Timespan', based on the passed in 'Specified's. timespanEntity ss = Entity (mkKey 1) $ Timespan Nothing (mkKey 1) 10 bMax eMin eMax 1 Nothing where (bMax, eMin, eMax) = case ("beginMax" `Z.member` ss ,"endMin" `Z.member` ss ,"endMax" `Z.member` ss) of (False, False, False) -> (10, 10, 10) (True, False, False) -> (15, 15, 15) (True, True, False) -> (15, 24, 24) (False, True, False) -> (10, 24, 24) (True, False, True) -> (15, 42, 42) (False, True, True) -> (10, 24, 42) (False, False, True) -> (10, 42, 42) (True, True, True) -> (15, 24, 42) timespansSpecsAttrs :: Z.Set Specified -> [AttributePair] -> [(Entity Timespan, [Entity TimespanAttribute])] -- | 'timespansSpecsAttrs' constructs a list of pairs. The first member is an -- 'Entity' with a 'Timespan'. The second is a list of 'Entity's with -- 'TimespanAttribute's. The 'Timespan' respects the passed 'Specified's. The -- 'TimespanAttribute's respects the passed list of 'AttributePair's. timespansSpecsAttrs ss as = [(timespanEntity ss ,mkAttributeEntities as)] timespansSpecs :: Z.Set Specified -> [(Entity Timespan, [Entity TimespanAttribute])] -- | 'timespansSpecs' does 'timespansSpecsAttrs' without 'TimespanAttribute's. timespansSpecs = flip timespansSpecsAttrs [] timespansAttrs :: [AttributePair] -> [(Entity Timespan, [Entity TimespanAttribute])] -- | 'timespansAttrs' does 'timespansSpecsAttrs' without 'Specified's timespansAttrs = timespansSpecsAttrs Z.empty modTimespanEntity :: (Entity Timespan, [Entity TimespanAttribute]) -- | 'modTimespanEntity' is a convenience function for constructing a pair of -- 'Entity's, the first containing a 'Timespan' like the one in -- 'timespanEntity' with a modified beginMin, the second containing the -- default set of 'TimespanAttribute's in 'attributes'. modTimespanEntity = (Entity (mkKey 1) $ Timespan Nothing (mkKey 1) 0 15 24 42 1 Nothing ,mkAttributeEntities attributes) defaultTimespans :: [(Entity Timespan, [Entity TimespanAttribute])] -- | 'defaultTimespans' is a helper value for the often used -- 'Init.initDefaultTimespan'. defaultTimespans = timespansSpecsAttrs specifieds attributes specialTimespan :: Integer -> Maybe Integer -> Entity Timespan -- | 'specialTimespan' is a convenience 'Timespan' that's easy to distinguish -- from 'defaultTimespans'. It takes the Key ID and a 'Maybe' Parent ID. specialTimespan n p = Entity (mkKey n) $ Timespan (mkKey <$> p) (mkKey 1) (-10) (-10) (-10) (-10) 1 Nothing mkAttributeEntities :: [AttributePair] -> [Entity TimespanAttribute] -- | 'mkAttributeEntities' takes a list of key-value pairs and makes -- a '[Entity TimespanAttribute]'. mkAttributeEntities as = [ attributeEntity i 1 k v | (i, (k, v)) <- [1 .. ] `zip` map (toText *** toText) as ] defaultClock :: Entity Clock -- | 'defaultClock' is a helper value for the often used 'Init.initClock'. defaultClock = Entity (mkKey 1) $ Clock "TT" Nothing defaultUser :: Entity User -- | 'defaultUser' is a helper value for the often used -- 'Init.initUser'. defaultUser = Entity (mkKey 1) $ User "Luser" Nothing defaultUserWithAttrs :: (Entity User, [Entity UserAttribute]) -- | 'defaultUserWithAttrs' is a helper value for the often used -- 'Init.initUserAttribute'. defaultUserWithAttrs = (defaultUser ,[Entity (mkKey 1) $ UserAttribute (mkKey 1) "name" "test" Nothing]) defaultRole :: Entity Role -- | 'defaultRole' is a helper value for the often used -- 'Init.initRole'. defaultRole = Entity (mkKey 1) $ Role "Rulle" (mkKey 1) Nothing defaultPermissionset :: Entity Permissionset -- | 'defaultPermissionset' is a helper value for the often used -- 'Init.initPermissionset'. defaultPermissionset = Entity (mkKey 1) $ Permissionset (mkKey 1) (mkKey 1) True True True Nothing
plaimi/tempuhs-server
test/Tempuhs/Spoc/Entity.hs
agpl-3.0
6,897
0
14
1,434
1,744
973
771
126
8
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ScopedTypeVariables #-} module Language.Haskell.Brittany.Internal ( parsePrintModule , parsePrintModuleTests , pPrintModule , pPrintModuleAndCheck -- re-export from utils: , parseModule , parseModuleFromString , extractCommentConfigs , getTopLevelDeclNameMap ) where import Control.Monad.Trans.Except import qualified Control.Monad.Trans.MultiRWS.Strict as MultiRWSS import qualified Data.ByteString.Char8 import Data.CZipWith import Data.Char (isSpace) import Data.HList.HList import qualified Data.Map as Map import qualified Data.Maybe import qualified Data.Semigroup as Semigroup import qualified Data.Sequence as Seq import qualified Data.Text as Text import qualified Data.Text.Lazy as TextL import qualified Data.Text.Lazy.Builder as Text.Builder import qualified Data.Yaml import qualified GHC hiding (parseModule) import GHC (GenLocated(L)) import qualified GHC.Driver.Session as GHC import GHC.Hs import qualified GHC.LanguageExtensions.Type as GHC import qualified GHC.OldList as List import GHC.Parser.Annotation (AnnKeywordId(..)) import GHC.Types.SrcLoc (SrcSpan) import Language.Haskell.Brittany.Internal.Backend import Language.Haskell.Brittany.Internal.BackendUtils import Language.Haskell.Brittany.Internal.Config import Language.Haskell.Brittany.Internal.Config.Types import Language.Haskell.Brittany.Internal.ExactPrintUtils import Language.Haskell.Brittany.Internal.LayouterBasics import Language.Haskell.Brittany.Internal.Layouters.Decl import Language.Haskell.Brittany.Internal.Layouters.Module import Language.Haskell.Brittany.Internal.Prelude import Language.Haskell.Brittany.Internal.PreludeUtils import Language.Haskell.Brittany.Internal.Transformations.Alt import Language.Haskell.Brittany.Internal.Transformations.Columns import Language.Haskell.Brittany.Internal.Transformations.Floating import Language.Haskell.Brittany.Internal.Transformations.Indent import Language.Haskell.Brittany.Internal.Transformations.Par import Language.Haskell.Brittany.Internal.Types import Language.Haskell.Brittany.Internal.Utils import qualified Language.Haskell.GHC.ExactPrint as ExactPrint import qualified Language.Haskell.GHC.ExactPrint.Types as ExactPrint import qualified UI.Butcher.Monadic as Butcher data InlineConfigTarget = InlineConfigTargetModule | InlineConfigTargetNextDecl -- really only next in module | InlineConfigTargetNextBinding -- by name | InlineConfigTargetBinding String extractCommentConfigs :: ExactPrint.Anns -> TopLevelDeclNameMap -> Either (String, String) (CConfig Maybe, PerItemConfig) extractCommentConfigs anns (TopLevelDeclNameMap declNameMap) = do let commentLiness = [ ( k , [ x | (ExactPrint.Comment x _ _, _) <- (ExactPrint.annPriorComments ann ++ ExactPrint.annFollowingComments ann ) ] ++ [ x | (ExactPrint.AnnComment (ExactPrint.Comment x _ _), _) <- ExactPrint.annsDP ann ] ) | (k, ann) <- Map.toList anns ] let configLiness = commentLiness <&> second (Data.Maybe.mapMaybe $ \line -> do l1 <- List.stripPrefix "-- BRITTANY" line <|> List.stripPrefix "--BRITTANY" line <|> List.stripPrefix "-- brittany" line <|> List.stripPrefix "--brittany" line <|> (List.stripPrefix "{- BRITTANY" line >>= stripSuffix "-}") let l2 = dropWhile isSpace l1 guard (("@" `isPrefixOf` l2) || ("-disable" `isPrefixOf` l2) || ("-next" `isPrefixOf` l2) || ("{" `isPrefixOf` l2) || ("--" `isPrefixOf` l2) ) pure l2 ) let configParser = Butcher.addAlternatives [ ( "commandline-config" , \s -> "-" `isPrefixOf` dropWhile (== ' ') s , cmdlineConfigParser ) , ( "yaml-config-document" , \s -> "{" `isPrefixOf` dropWhile (== ' ') s , Butcher.addCmdPart (Butcher.varPartDesc "yaml-config-document") $ fmap (\lconf -> (mempty { _conf_layout = lconf }, "")) . either (const Nothing) Just . Data.Yaml.decodeEither' . Data.ByteString.Char8.pack -- TODO: use some proper utf8 encoder instead? ) ] parser = do -- we will (mis?)use butcher here to parse the inline config -- line. let nextDecl = do conf <- configParser Butcher.addCmdImpl (InlineConfigTargetNextDecl, conf) Butcher.addCmd "-next-declaration" nextDecl Butcher.addCmd "-Next-Declaration" nextDecl Butcher.addCmd "-NEXT-DECLARATION" nextDecl let nextBinding = do conf <- configParser Butcher.addCmdImpl (InlineConfigTargetNextBinding, conf) Butcher.addCmd "-next-binding" nextBinding Butcher.addCmd "-Next-Binding" nextBinding Butcher.addCmd "-NEXT-BINDING" nextBinding let disableNextBinding = do Butcher.addCmdImpl ( InlineConfigTargetNextBinding , mempty { _conf_roundtrip_exactprint_only = pure $ pure True } ) Butcher.addCmd "-disable-next-binding" disableNextBinding Butcher.addCmd "-Disable-Next-Binding" disableNextBinding Butcher.addCmd "-DISABLE-NEXT-BINDING" disableNextBinding let disableNextDecl = do Butcher.addCmdImpl ( InlineConfigTargetNextDecl , mempty { _conf_roundtrip_exactprint_only = pure $ pure True } ) Butcher.addCmd "-disable-next-declaration" disableNextDecl Butcher.addCmd "-Disable-Next-Declaration" disableNextDecl Butcher.addCmd "-DISABLE-NEXT-DECLARATION" disableNextDecl let disableFormatting = do Butcher.addCmdImpl ( InlineConfigTargetModule , mempty { _conf_disable_formatting = pure $ pure True } ) Butcher.addCmd "-disable" disableFormatting Butcher.addCmd "@" $ do -- Butcher.addCmd "module" $ do -- conf <- configParser -- Butcher.addCmdImpl (InlineConfigTargetModule, conf) Butcher.addNullCmd $ do bindingName <- Butcher.addParamString "BINDING" mempty conf <- configParser Butcher.addCmdImpl (InlineConfigTargetBinding bindingName, conf) conf <- configParser Butcher.addCmdImpl (InlineConfigTargetModule, conf) lineConfigss <- configLiness `forM` \(k, ss) -> do r <- ss `forM` \s -> case Butcher.runCmdParserSimple s parser of Left err -> Left $ (err, s) Right c -> Right $ c pure (k, r) let perModule = foldl' (<>) mempty [ conf | (_, lineConfigs) <- lineConfigss , (InlineConfigTargetModule, conf) <- lineConfigs ] let perBinding = Map.fromListWith (<>) [ (n, conf) | (k, lineConfigs) <- lineConfigss , (target, conf) <- lineConfigs , n <- case target of InlineConfigTargetBinding s -> [s] InlineConfigTargetNextBinding | Just name <- Map.lookup k declNameMap -> [name] _ -> [] ] let perKey = Map.fromListWith (<>) [ (k, conf) | (k, lineConfigs) <- lineConfigss , (target, conf) <- lineConfigs , case target of InlineConfigTargetNextDecl -> True InlineConfigTargetNextBinding | Nothing <- Map.lookup k declNameMap -> True _ -> False ] pure $ ( perModule , PerItemConfig { _icd_perBinding = perBinding, _icd_perKey = perKey } ) getTopLevelDeclNameMap :: GHC.ParsedSource -> TopLevelDeclNameMap getTopLevelDeclNameMap (L _ (HsModule _ _name _exports _ decls _ _)) = TopLevelDeclNameMap $ Map.fromList [ (ExactPrint.mkAnnKey decl, name) | decl <- decls , (name : _) <- [getDeclBindingNames decl] ] -- | Exposes the transformation in an pseudo-pure fashion. The signature -- contains `IO` due to the GHC API not exposing a pure parsing function, but -- there should be no observable effects. -- -- Note that this function ignores/resets all config values regarding -- debugging, i.e. it will never use `trace`/write to stderr. -- -- Note that the ghc parsing function used internally currently is wrapped in -- `mask_`, so cannot be killed easily. If you don't control the input, you -- may wish to put some proper upper bound on the input's size as a timeout -- won't do. parsePrintModule :: Config -> Text -> IO (Either [BrittanyError] Text) parsePrintModule configWithDebugs inputText = runExceptT $ do let config = configWithDebugs { _conf_debug = _conf_debug staticDefaultConfig } let ghcOptions = config & _conf_forward & _options_ghc & runIdentity let config_pp = config & _conf_preprocessor let cppMode = config_pp & _ppconf_CPPMode & confUnpack let hackAroundIncludes = config_pp & _ppconf_hackAroundIncludes & confUnpack (anns, parsedSource, hasCPP) <- do let hackF s = if "#include" `isPrefixOf` s then "-- BRITANY_INCLUDE_HACK " ++ s else s let hackTransform = if hackAroundIncludes then List.intercalate "\n" . fmap hackF . lines' else id let cppCheckFunc dynFlags = if GHC.xopt GHC.Cpp dynFlags then case cppMode of CPPModeAbort -> return $ Left "Encountered -XCPP. Aborting." CPPModeWarn -> return $ Right True CPPModeNowarn -> return $ Right True else return $ Right False parseResult <- lift $ parseModuleFromString ghcOptions "stdin" cppCheckFunc (hackTransform $ Text.unpack inputText) case parseResult of Left err -> throwE [ErrorInput err] Right x -> pure x (inlineConf, perItemConf) <- either (throwE . (: []) . uncurry ErrorMacroConfig) pure $ extractCommentConfigs anns (getTopLevelDeclNameMap parsedSource) let moduleConfig = cZipWith fromOptionIdentity config inlineConf let disableFormatting = moduleConfig & _conf_disable_formatting & confUnpack if disableFormatting then do return inputText else do (errsWarns, outputTextL) <- do let omitCheck = moduleConfig & _conf_errorHandling & _econf_omit_output_valid_check & confUnpack (ews, outRaw) <- if hasCPP || omitCheck then return $ pPrintModule moduleConfig perItemConf anns parsedSource else lift $ pPrintModuleAndCheck moduleConfig perItemConf anns parsedSource let hackF s = fromMaybe s $ TextL.stripPrefix (TextL.pack "-- BRITANY_INCLUDE_HACK ") s pure $ if hackAroundIncludes then ( ews , TextL.intercalate (TextL.pack "\n") $ hackF <$> TextL.splitOn (TextL.pack "\n") outRaw ) else (ews, outRaw) let customErrOrder ErrorInput{} = 4 customErrOrder LayoutWarning{} = 0 :: Int customErrOrder ErrorOutputCheck{} = 1 customErrOrder ErrorUnusedComment{} = 2 customErrOrder ErrorUnknownNode{} = 3 customErrOrder ErrorMacroConfig{} = 5 let hasErrors = if moduleConfig & _conf_errorHandling & _econf_Werror & confUnpack then not $ null errsWarns else 0 < maximum (-1 : fmap customErrOrder errsWarns) if hasErrors then throwE $ errsWarns else pure $ TextL.toStrict outputTextL -- BrittanyErrors can be non-fatal warnings, thus both are returned instead -- of an Either. -- This should be cleaned up once it is clear what kinds of errors really -- can occur. pPrintModule :: Config -> PerItemConfig -> ExactPrint.Anns -> GHC.ParsedSource -> ([BrittanyError], TextL.Text) pPrintModule conf inlineConf anns parsedModule = let ((out, errs), debugStrings) = runIdentity $ MultiRWSS.runMultiRWSTNil $ MultiRWSS.withMultiWriterAW $ MultiRWSS.withMultiWriterAW $ MultiRWSS.withMultiWriterW $ MultiRWSS.withMultiReader anns $ MultiRWSS.withMultiReader conf $ MultiRWSS.withMultiReader inlineConf $ MultiRWSS.withMultiReader (extractToplevelAnns parsedModule anns) $ do traceIfDumpConf "bridoc annotations raw" _dconf_dump_annotations $ annsDoc anns ppModule parsedModule tracer = if Seq.null debugStrings then id else trace ("---- DEBUGMESSAGES ---- ") . foldr (seq . join trace) id debugStrings in tracer $ (errs, Text.Builder.toLazyText out) -- unless () $ do -- -- debugStrings `forM_` \s -> -- trace s $ return () -- | Additionally checks that the output compiles again, appending an error -- if it does not. pPrintModuleAndCheck :: Config -> PerItemConfig -> ExactPrint.Anns -> GHC.ParsedSource -> IO ([BrittanyError], TextL.Text) pPrintModuleAndCheck conf inlineConf anns parsedModule = do let ghcOptions = conf & _conf_forward & _options_ghc & runIdentity let (errs, output) = pPrintModule conf inlineConf anns parsedModule parseResult <- parseModuleFromString ghcOptions "output" (\_ -> return $ Right ()) (TextL.unpack output) let errs' = errs ++ case parseResult of Left{} -> [ErrorOutputCheck] Right{} -> [] return (errs', output) -- used for testing mostly, currently. -- TODO: use parsePrintModule instead and remove this function. parsePrintModuleTests :: Config -> String -> Text -> IO (Either String Text) parsePrintModuleTests conf filename input = do let inputStr = Text.unpack input parseResult <- parseModuleFromString (conf & _conf_forward & _options_ghc & runIdentity) filename (const . pure $ Right ()) inputStr case parseResult of Left err -> return $ Left err Right (anns, parsedModule, _) -> runExceptT $ do (inlineConf, perItemConf) <- case extractCommentConfigs anns (getTopLevelDeclNameMap parsedModule) of Left err -> throwE $ "error in inline config: " ++ show err Right x -> pure x let moduleConf = cZipWith fromOptionIdentity conf inlineConf let omitCheck = conf & _conf_errorHandling .> _econf_omit_output_valid_check .> confUnpack (errs, ltext) <- if omitCheck then return $ pPrintModule moduleConf perItemConf anns parsedModule else lift $ pPrintModuleAndCheck moduleConf perItemConf anns parsedModule if null errs then pure $ TextL.toStrict $ ltext else let errStrs = errs <&> \case ErrorInput str -> str ErrorUnusedComment str -> str LayoutWarning str -> str ErrorUnknownNode str _ -> str ErrorMacroConfig str _ -> "when parsing inline config: " ++ str ErrorOutputCheck -> "Output is not syntactically valid." in throwE $ "pretty printing error(s):\n" ++ List.unlines errStrs -- this approach would for if there was a pure GHC.parseDynamicFilePragma. -- Unfortunately that does not exist yet, so we cannot provide a nominally -- pure interface. -- parsePrintModuleTests :: Text -> Either String Text -- parsePrintModuleTests input = do -- let dflags = GHC.unsafeGlobalDynFlags -- let fakeFileName = "SomeTestFakeFileName.hs" -- let pragmaInfo = GHC.getOptions -- dflags -- (GHC.stringToStringBuffer $ Text.unpack input) -- fakeFileName -- (dflags1, _, _) <- GHC.parseDynamicFilePragma dflags pragmaInfo -- let parseResult = ExactPrint.Parsers.parseWith -- dflags1 -- fakeFileName -- GHC.parseModule -- inputStr -- case parseResult of -- Left (_, s) -> Left $ "parsing error: " ++ s -- Right (anns, parsedModule) -> do -- let (out, errs) = runIdentity -- $ runMultiRWSTNil -- $ Control.Monad.Trans.MultiRWS.Lazy.withMultiWriterAW -- $ Control.Monad.Trans.MultiRWS.Lazy.withMultiWriterW -- $ Control.Monad.Trans.MultiRWS.Lazy.withMultiReader anns -- $ ppModule parsedModule -- if (not $ null errs) -- then do -- let errStrs = errs <&> \case -- ErrorUnusedComment str -> str -- Left $ "pretty printing error(s):\n" ++ List.unlines errStrs -- else return $ TextL.toStrict $ Text.Builder.toLazyText out toLocal :: Config -> ExactPrint.Anns -> PPMLocal a -> PPM a toLocal conf anns m = do (x, write) <- lift $ MultiRWSS.runMultiRWSTAW (conf :+: anns :+: HNil) HNil $ m MultiRWSS.mGetRawW >>= \w -> MultiRWSS.mPutRawW (w `mappend` write) pure x ppModule :: GenLocated SrcSpan HsModule -> PPM () ppModule lmod@(L _loc _m@(HsModule _ _name _exports _ decls _ _)) = do defaultAnns <- do anns <- mAsk let annKey = ExactPrint.mkAnnKey lmod let annMap = Map.findWithDefault Map.empty annKey anns let isEof = (== ExactPrint.AnnEofPos) let overAnnsDP f a = a { ExactPrint.annsDP = f $ ExactPrint.annsDP a } pure $ fmap (overAnnsDP . filter $ isEof . fst) annMap post <- ppPreamble lmod decls `forM_` \decl -> do let declAnnKey = ExactPrint.mkAnnKey decl let declBindingNames = getDeclBindingNames decl inlineConf <- mAsk let mDeclConf = Map.lookup declAnnKey $ _icd_perKey inlineConf let mBindingConfs = declBindingNames <&> \n -> Map.lookup n $ _icd_perBinding inlineConf filteredAnns <- mAsk <&> \annMap -> Map.union defaultAnns $ Map.findWithDefault Map.empty declAnnKey annMap traceIfDumpConf "bridoc annotations filtered/transformed" _dconf_dump_annotations $ annsDoc filteredAnns config <- mAsk let config' = cZipWith fromOptionIdentity config $ mconcat (catMaybes (mBindingConfs ++ [mDeclConf])) let exactprintOnly = config' & _conf_roundtrip_exactprint_only & confUnpack toLocal config' filteredAnns $ do bd <- if exactprintOnly then briDocMToPPM $ briDocByExactNoComment decl else do (r, errs, debugs) <- briDocMToPPMInner $ layoutDecl decl mTell debugs mTell errs if null errs then pure r else briDocMToPPM $ briDocByExactNoComment decl layoutBriDoc bd let finalComments = filter (fst .> \case ExactPrint.AnnComment{} -> True _ -> False ) post post `forM_` \case (ExactPrint.AnnComment (ExactPrint.Comment cmStr _ _), l) -> do ppmMoveToExactLoc l mTell $ Text.Builder.fromString cmStr (ExactPrint.AnnEofPos, (ExactPrint.DP (eofZ, eofX))) -> let folder (acc, _) (kw, ExactPrint.DP (y, x)) = case kw of ExactPrint.AnnComment cm | span <- ExactPrint.commentIdentifier cm -> ( acc + y + GHC.srcSpanEndLine span - GHC.srcSpanStartLine span , x + GHC.srcSpanEndCol span - GHC.srcSpanStartCol span ) _ -> (acc + y, x) (cmY, cmX) = foldl' folder (0, 0) finalComments in ppmMoveToExactLoc $ ExactPrint.DP (eofZ - cmY, eofX - cmX) _ -> return () getDeclBindingNames :: LHsDecl GhcPs -> [String] getDeclBindingNames (L _ decl) = case decl of SigD _ (TypeSig _ ns _) -> ns <&> \(L _ n) -> Text.unpack (rdrNameToText n) ValD _ (FunBind _ (L _ n) _ _) -> [Text.unpack $ rdrNameToText n] _ -> [] -- Prints the information associated with the module annotation -- This includes the imports ppPreamble :: GenLocated SrcSpan HsModule -> PPM [(ExactPrint.KeywordId, ExactPrint.DeltaPos)] ppPreamble lmod@(L loc m@HsModule{}) = do filteredAnns <- mAsk <&> \annMap -> Map.findWithDefault Map.empty (ExactPrint.mkAnnKey lmod) annMap -- Since ghc-exactprint adds annotations following (implicit) -- modules to both HsModule and the elements in the module -- this can cause duplication of comments. So strip -- attached annotations that come after the module's where -- from the module node config <- mAsk let shouldReformatPreamble = config & _conf_layout & _lconfig_reformatModulePreamble & confUnpack let (filteredAnns', post) = case Map.lookup (ExactPrint.mkAnnKey lmod) filteredAnns of Nothing -> (filteredAnns, []) Just mAnn -> let modAnnsDp = ExactPrint.annsDP mAnn isWhere (ExactPrint.G AnnWhere) = True isWhere _ = False isEof (ExactPrint.AnnEofPos) = True isEof _ = False whereInd = List.findIndex (isWhere . fst) modAnnsDp eofInd = List.findIndex (isEof . fst) modAnnsDp (pre, post') = case (whereInd, eofInd) of (Nothing, Nothing) -> ([], modAnnsDp) (Just i, Nothing) -> List.splitAt (i + 1) modAnnsDp (Nothing, Just _i) -> ([], modAnnsDp) (Just i, Just j) -> List.splitAt (min (i + 1) j) modAnnsDp mAnn' = mAnn { ExactPrint.annsDP = pre } filteredAnns'' = Map.insert (ExactPrint.mkAnnKey lmod) mAnn' filteredAnns in (filteredAnns'', post') traceIfDumpConf "bridoc annotations filtered/transformed" _dconf_dump_annotations $ annsDoc filteredAnns' if shouldReformatPreamble then toLocal config filteredAnns' $ withTransformedAnns lmod $ do briDoc <- briDocMToPPM $ layoutModule lmod layoutBriDoc briDoc else let emptyModule = L loc m { hsmodDecls = [] } in MultiRWSS.withMultiReader filteredAnns' $ processDefault emptyModule return post _sigHead :: Sig GhcPs -> String _sigHead = \case TypeSig _ names _ -> "TypeSig " ++ intercalate "," (Text.unpack . lrdrNameToText <$> names) _ -> "unknown sig" _bindHead :: HsBind GhcPs -> String _bindHead = \case FunBind _ fId _ [] -> "FunBind " ++ (Text.unpack $ lrdrNameToText $ fId) PatBind _ _pat _ ([], []) -> "PatBind smth" _ -> "unknown bind" layoutBriDoc :: BriDocNumbered -> PPMLocal () layoutBriDoc briDoc = do -- first step: transform the briDoc. briDoc' <- MultiRWSS.withMultiStateS BDEmpty $ do -- Note that briDoc is BriDocNumbered, but state type is BriDoc. -- That's why the alt-transform looks a bit special here. traceIfDumpConf "bridoc raw" _dconf_dump_bridoc_raw $ briDocToDoc $ unwrapBriDocNumbered $ briDoc -- bridoc transformation: remove alts transformAlts briDoc >>= mSet mGet >>= briDocToDoc .> traceIfDumpConf "bridoc post-alt" _dconf_dump_bridoc_simpl_alt -- bridoc transformation: float stuff in mGet >>= transformSimplifyFloating .> mSet mGet >>= briDocToDoc .> traceIfDumpConf "bridoc post-floating" _dconf_dump_bridoc_simpl_floating -- bridoc transformation: par removal mGet >>= transformSimplifyPar .> mSet mGet >>= briDocToDoc .> traceIfDumpConf "bridoc post-par" _dconf_dump_bridoc_simpl_par -- bridoc transformation: float stuff in mGet >>= transformSimplifyColumns .> mSet mGet >>= briDocToDoc .> traceIfDumpConf "bridoc post-columns" _dconf_dump_bridoc_simpl_columns -- bridoc transformation: indent mGet >>= transformSimplifyIndent .> mSet mGet >>= briDocToDoc .> traceIfDumpConf "bridoc post-indent" _dconf_dump_bridoc_simpl_indent mGet >>= briDocToDoc .> traceIfDumpConf "bridoc final" _dconf_dump_bridoc_final -- -- convert to Simple type -- simpl <- mGet <&> transformToSimple -- return simpl anns :: ExactPrint.Anns <- mAsk let state = LayoutState { _lstate_baseYs = [0] , _lstate_curYOrAddNewline = Right 0 -- important that we dont use left -- here because moveToAnn stuff -- of the first node needs to do -- its thing properly. , _lstate_indLevels = [0] , _lstate_indLevelLinger = 0 , _lstate_comments = anns , _lstate_commentCol = Nothing , _lstate_addSepSpace = Nothing , _lstate_commentNewlines = 0 } state' <- MultiRWSS.withMultiStateS state $ layoutBriDocM briDoc' let remainingComments = [ c | (ExactPrint.AnnKey _ con, elemAnns) <- Map.toList (_lstate_comments state') -- With the new import layouter, we manually process comments -- without relying on the backend to consume the comments out of -- the state/map. So they will end up here, and we need to ignore -- them. , ExactPrint.unConName con /= "ImportDecl" , c <- extractAllComments elemAnns ] remainingComments `forM_` (fst .> show .> ErrorUnusedComment .> (: []) .> mTell) return $ ()
lspitzner/brittany
source/library/Language/Haskell/Brittany/Internal.hs
agpl-3.0
24,946
0
24
6,505
5,707
2,974
2,733
527
17
module PhhhbbtttEither where import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes data PhhhbbtttEither b a = Left a | Right b deriving (Eq, Show) -- Required for checkers instance (Eq a, Eq b) => EqProp (PhhhbbtttEither b a) where (=-=) = eq -- QuickCheck arbitrary instance (Arbitrary a, Arbitrary b) => Arbitrary (PhhhbbtttEither b a) where arbitrary = do x <- arbitrary y <- arbitrary aPhhhbbtttEither <- elements [PhhhbbtttEither.Left x, PhhhbbtttEither.Right y] return $ aPhhhbbtttEither instance Functor (PhhhbbtttEither b) where fmap _ (PhhhbbtttEither.Right b) = (PhhhbbtttEither.Right b) fmap f (PhhhbbtttEither.Left b) = (PhhhbbtttEither.Left (f b)) instance Applicative (PhhhbbtttEither b) where pure = PhhhbbtttEither.Left (<*>) (PhhhbbtttEither.Left x) (PhhhbbtttEither.Left y) = PhhhbbtttEither.Left (x y) (<*>) (PhhhbbtttEither.Right x) _ = PhhhbbtttEither.Right x (<*>) _ (PhhhbbtttEither.Right x) = PhhhbbtttEither.Right x instance Monad (PhhhbbtttEither b) where return = pure (>>=) (PhhhbbtttEither.Left x) ma = ma x (>>=) (PhhhbbtttEither.Right x) _ = PhhhbbtttEither.Right x checkPhhhbbtttEither :: IO () checkPhhhbbtttEither = do putStrLn "== Checking PhhhbbtttEither Monad ==" let a = (undefined :: PhhhbbtttEither (Int, String, Int) (String,Int,Int)) quickBatch $ functor a quickBatch $ applicative a quickBatch $ monad a
dmp1ce/Haskell-Programming-Exercises
Chapter 18/MonadInstances/src/PhhhbbtttEither.hs
unlicense
1,479
0
12
281
509
265
244
32
1
ans s [] = if s == 0 then "YES" else "NO" ans s (l:ls) = case l of "A" -> ans (s+1) ls "Un" -> if s == 0 then "NO" else ans (s-1) ls main = do _ <- getLine c <- getContents let i = lines c o = ans 0 i putStrLn o
a143753/AOJ
2738.hs
apache-2.0
241
0
11
86
141
70
71
11
4
{-# LANGUAGE ForeignFunctionInterface #-} {-# OPTIONS_GHC -O2 #-} -- | * Author: Jefferson Heard (jefferson.r.heard at gmail.com) -- -- * Copyright 2008 Renaissance Computing Institute < http://www.renci.org > -- -- * License: GNU LGPL -- -- * Compatibility GHC (I could change the data declarations to not be empty and that would make it more generally compatible, I believe) -- -- * Description: -- -- Use FreeType 2 Fonts in OpenGL. Requires the FTGL library and FreeType libraries. -- available at < http://ftgl.wiki.sourceforge.net/ > . The most important functions for -- everyday use are renderFont and the create*Font family of functions. To render a -- simple string inside OpenGL, assuming you have OpenGL initialized and a current -- pen color, all you need is: -- -- > do font <- createTextureFont "Font.ttf" -- > setFontFaceSize font 24 72 -- > renderFont font "Hello world!" -- -- Fonts are rendered so that a single point is an OpenGL unit, and a point is 1:72 of -- an inch. module Graphics.Rendering.FTGL where import System.IO.Unsafe (unsafePerformIO) import Foreign.C import Foreign.Ptr import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Data.Bits import Data.Char (ord) import Data.Word import qualified Graphics.Rendering.OpenGL.GL as GL import Control.Applicative ((<$>)) foreign import ccall unsafe "ftglCreateBitmapFont" fcreateBitmapFont :: CString -> IO Font -- | Create a bitmapped version of a TrueType font. Bitmapped versions will not -- | respond to matrix transformations, but rather must be transformed using the -- | raster positioning functions in OpenGL createBitmapFont :: String -> IO Font createBitmapFont file = withCString file $ \p -> fcreateBitmapFont p foreign import ccall unsafe "ftglCreateBufferFont" fcreateBufferFont :: CString -> IO Font -- | Create a buffered version of a TrueType font. This stores the entirety of -- | a string in a texture, "buffering" it before rendering. Very fast if you -- | will be repeatedly rendering the same strings over and over. createBufferFont :: String -> IO Font createBufferFont file = withCString file $ \p -> fcreateBufferFont p {- foreign import ccall unsafe "ftglCreateOutlineFont" fcreateOutlineFont :: CString -> IO Font -- | Create an outline version of a TrueType font. This uses actual geometry -- | and will scale independently without loss of quality. Faster than polygons -- | but slower than texture or buffer fonts. createOutlineFont :: String -> IO Font createOutlineFont file = withCString file $ \p -> fcreateOutlineFont p -} foreign import ccall unsafe "ftglCreatePixmapFont" fcreatePixmapFont :: CString -> IO Font -- | Create a pixmap version of a TrueType font. Higher quality than the bitmap -- | font without losing any performance. Use this if you don't mind using -- | set and get RasterPosition. createPixmapFont :: String -> IO Font createPixmapFont file = withCString file $ \p -> fcreatePixmapFont p foreign import ccall unsafe "ftglCreatePolygonFont" fcreatePolygonFont :: CString -> IO Font -- | Create polygonal display list fonts. These scale independently without -- | losing quality, unlike texture or buffer fonts, but can be impractical -- | for large amounts of text because of the high number of polygons needed. -- | Additionally, they do not, unlike the textured fonts, create artifacts -- | within the square formed at the edge of each character. createPolygonFont :: String -> IO Font createPolygonFont file = withCString file $ \p -> fcreatePolygonFont p foreign import ccall unsafe "ftglCreateTextureFont" fcreateTextureFont :: CString -> IO Font -- | Create textured display list fonts. These can scale somewhat well, -- | but lose quality quickly. They are much faster than polygonal fonts, -- | though, so are suitable for large quantities of text. Especially suited -- | well to text that changes with most frames, because it doesn't incur the -- | (normally helpful) overhead of buffering. createTextureFont :: String -> IO Font createTextureFont file = withCString file $ \p -> fcreateTextureFont p {- foreign import ccall unsafe "ftglCreateExtrudeFont" fcreateExtrudeFont :: CString -> IO Font -- | Create a 3D extruded font. This is the only way of creating 3D fonts -- | within FTGL. Could be fun to use a geometry shader to get different -- | effects by warping the otherwise square nature of the font. Polygonal. -- | Scales without losing quality. Slower than all other fonts. createExtrudeFont :: String -> IO Font createExtrudeFont file = withCString file $ \p -> fcreateExtrudeFont p -} -- | Create a simple layout foreign import ccall unsafe "ftglCreateSimpleLayout" createSimpleLayout :: IO Layout -- | Set the layout's font. foreign import ccall unsafe "ftglSetLayoutFont" setLayoutFont :: Layout -> Font -> IO () foreign import ccall unsafe "ftglGetLayoutFont" fgetLayoutFont :: Layout -> IO Font -- | Get the embedded font from the Layout getLayoutFont f = fgetLayoutFont f -- | Set the line length, I believe in OpenGL units, although I'm not sure. foreign import ccall unsafe "ftglSetLayoutLineLength" setLayoutLineLength :: Layout -> CFloat -> IO () foreign import ccall unsafe "ftglGetLayoutLineLength" fgetLayoutLineLength :: Layout -> IO CFloat -- | Get the line length in points (1:72in) of lines in the layout getLayoutLineLength :: Layout -> IO Float getLayoutLineLength f = realToFrac <$> fgetLayoutLineLength f foreign import ccall unsafe "ftglSetLayoutAlignment" fsetLayoutAlignment :: Layout -> CInt -> IO () -- | Set the layout alignment setLayoutAlignment layout alignment = fsetLayoutAlignment layout (marshalTextAlignment alignment) foreign import ccall unsafe "ftglGetLayoutAlignement" fgetLayoutAlignment :: Layout -> IO CInt -- | Get the alignment of text in this layout. getLayoutAlignment f = readTextAlignment <$> fgetLayoutAlignment f foreign import ccall unsafe "ftglSetLayoutLineSpacing" fsetLayoutLineSpacing :: Layout -> CFloat -> IO () -- | Set layout line spacing in OpenGL units. setLayoutLineSpacing :: Layout -> Float -> IO () setLayoutLineSpacing layout spacing = setLayoutLineSpacing layout (realToFrac spacing) -- | Destroy a font foreign import ccall unsafe "ftglDestroyFont" destroyFont :: Font -> IO () foreign import ccall unsafe "ftglAttachFile" fattachFile :: Font -> CString -> IO () -- | Attach a metadata file to a font. attachFile :: Font -> String -> IO () attachFile font str = withCString str $ \p -> fattachFile font p -- | Attach some external data (often kerning) to the font foreign import ccall unsafe "ftglAttachData" attachData :: Font -> Ptr () -> IO () -- | Set the font's character map foreign import ccall unsafe "ftglSetFontCharMap" fsetFontCharMap :: Font -> CInt -> IO () setCharMap :: Font -> CharMap -> IO () setCharMap font charmap = fsetFontCharMap font (marshalCharMap charmap) foreign import ccall unsafe "ftglGetFontCharMapCount" fgetFontCharMapCount :: Font -> IO CInt -- | Get the number of characters loaded into the current charmap for the font. getFontCharMapCount :: Font -> Int getFontCharMapCount f = fromIntegral . unsafePerformIO $ fgetFontCharMapCount f foreign import ccall unsafe "ftglGetFontCharMapList" fgetFontCharMapList :: Font -> IO (Ptr CInt) -- | Get the different character mappings available in this font. getFontCharMapList f = unsafePerformIO $ fgetFontCharMapList f foreign import ccall unsafe "ftglSetFontFaceSize" fsetFontFaceSize :: Font -> CInt -> CInt -> IO CInt setFontFaceSize :: Font -> Int -> Int -> IO CInt setFontFaceSize f s x = fsetFontFaceSize f (fromIntegral s) (fromIntegral x) foreign import ccall unsafe "ftglGetFontFaceSize" fgetFontFaceSize :: Font -> IO CInt -- | Get the current font face size in points. getFontFaceSize :: Font -> IO Int getFontFaceSize f = fromIntegral <$> fgetFontFaceSize f foreign import ccall unsafe "ftglSetFontDepth" fsetFontDepth :: Font -> CFloat -> IO () setFontDepth :: Font -> Float -> IO () setFontDepth font depth = fsetFontDepth font (realToFrac depth) foreign import ccall unsafe "ftglSetFontOutset" fsetFontOutset :: Font -> CFloat -> CFloat -> IO () setFontOutset :: Font -> Float -> Float -> IO () setFontOutset font d o = fsetFontOutset font (realToFrac d) (realToFrac o) foreign import ccall unsafe "ftglGetFontBBoxW" fgetFontBBoxW :: Font -> Ptr Word32 -> Int -> Ptr CFloat -> IO () -- | Get the text extents of a string as a list of (llx,lly,lly,urx,ury,urz) getFontBBox :: Font -> String -> IO [Float] getFontBBox f str = allocaBytes 24 $ \pf -> allocaArray (length str + 1) $ \ps -> do pokeArray0 0 ps (map (fromIntegral . ord) str) fgetFontBBoxW f ps (-1) pf map realToFrac <$> peekArray 6 pf foreign import ccall unsafe "ftglGetFontAscender" fgetFontAscender :: Font -> CFloat -- | Get the global ascender height for the face. getFontAscender :: Font -> Float getFontAscender = realToFrac . fgetFontAscender foreign import ccall unsafe "ftglGetFontDescender" fgetFontDescender :: Font -> CFloat -- | Gets the global descender height for the face. getFontDescender :: Font -> Float getFontDescender = realToFrac . fgetFontDescender foreign import ccall unsafe "ftglGetFontLineHeight" fgetFontLineHeight :: Font -> CFloat -- | Gets the global line spacing for the face. getFontLineHeight :: Font -> Float getFontLineHeight = realToFrac . fgetFontLineHeight foreign import ccall unsafe "ftglGetFontAdvanceW" fgetFontAdvanceW :: Font -> Ptr Word32 -> IO CFloat -- | Get the horizontal span of a string of text using the current font. Input as the xcoord -- | in any translate operation getFontAdvance :: Font -> String -> IO Float getFontAdvance font str = allocaArray (length str + 1) $ \p -> do pokeArray0 0 p (map (fromIntegral . ord) str) realToFrac <$> fgetFontAdvanceW font p foreign import ccall unsafe "ftglRenderFontW" frenderFontW :: Font -> Ptr Word32 -> CInt -> IO () -- | Render a string of text in the current font. renderFont :: Font -> String -> RenderMode -> IO () renderFont font str mode = allocaArray (length str + 1) $ \p -> do pokeArray0 0 p (map (fromIntegral . ord) str) frenderFontW font p (marshalRenderMode mode) foreign import ccall unsafe "ftglGetFontError" fgetFontError :: Font -> IO CInt -- | Get any errors associated with loading a font. FIXME return should be a type, not an Int. getFontError :: Font -> IO Int getFontError f = fromIntegral <$> fgetFontError f foreign import ccall unsafe "ftglDestroyLayout" destroyLayout :: Layout -> IO () foreign import ccall unsafe "ftglRenderLayout" frenderLayout :: Layout -> CString -> IO () -- | Render a string of text within a layout. renderLayout layout str = withCString str $ \strPtr -> do frenderLayout layout strPtr foreign import ccall unsafe "ftglGetLayoutError" fgetLayoutError :: Layout -> IO CInt -- | Get any errors associated with a layout. getLayoutError f = fgetLayoutError f -- | Whether or not in polygonal or extrusion mode, the font will render equally front and back data RenderMode = Front | Back | Side | All -- | In a Layout directed render, the layout mode of the text data TextAlignment = AlignLeft | AlignCenter | AlignRight | Justify marshalRenderMode :: RenderMode -> CInt marshalRenderMode Front = 0x0001 marshalRenderMode Back = 0x0002 marshalRenderMode Side = 0x004 marshalRenderMode All = 0xffff marshalTextAlignment :: TextAlignment -> CInt marshalTextAlignment AlignLeft = 0 marshalTextAlignment AlignCenter = 1 marshalTextAlignment AlignRight = 2 marshalTextAlignment Justify = 3 readTextAlignment :: CInt -> TextAlignment readTextAlignment 0 = AlignLeft readTextAlignment 1 = AlignCenter readTextAlignment 2 = AlignRight readTextAlignment 3 = Justify -- | An opaque type encapsulating a glyph in C. Currently the glyph functions are unimplemented in Haskell. data Glyph_Opaque -- | An opaque type encapsulating a font in C. data Font_Opaque -- | An opaque type encapsulating a layout in C data Layout_Opaque type Glyph = Ptr Glyph_Opaque type Font = Ptr Font_Opaque type Layout = Ptr Layout_Opaque data CharMap = EncodingNone | EncodingMSSymbol | EncodingUnicode | EncodingSJIS | EncodingGB2312 | EncodingBig5 | EncodingWanSung | EncodingJohab | EncodingAdobeStandard | EncodingAdobeExpert | EncodingAdobeCustom | EncodingAdobeLatin1 | EncodingOldLatin2 | EncodingAppleRoman encodeTag :: Char -> Char -> Char -> Char -> CInt encodeTag a b c d = (fromIntegral (ord a) `shift` 24) .|. (fromIntegral (ord b) `shift` 16) .|. (fromIntegral (ord c) `shift` 8) .|. (fromIntegral (ord d)) marshalCharMap EncodingNone = 0 marshalCharMap EncodingMSSymbol = encodeTag 's' 'y' 'm' 'b' marshalCharMap EncodingUnicode =encodeTag 'u' 'n' 'i' 'c' marshalCharMap EncodingSJIS = encodeTag 's' 'j' 'i' 's' marshalCharMap EncodingGB2312 = encodeTag 'g' 'b' ' ' ' ' marshalCharMap EncodingBig5= encodeTag 'b' 'i' 'g' '5' marshalCharMap EncodingWanSung= encodeTag 'w' 'a' 'n' 's' marshalCharMap EncodingJohab= encodeTag 'j' 'o' 'h' 'a' marshalCharMap EncodingAdobeStandard= encodeTag 'A' 'D' 'O' 'B' marshalCharMap EncodingAdobeExpert= encodeTag 'A' 'D' 'B' 'E' marshalCharMap EncodingAdobeCustom= encodeTag 'A' 'D' 'B' 'C' marshalCharMap EncodingAdobeLatin1= encodeTag 'l' 'a' 't' '1' marshalCharMap EncodingOldLatin2= encodeTag 'l' 'a' 't' '2' marshalCharMap EncodingAppleRoman= encodeTag 'a' 'r' 'm' 'n'
ghc-ios/FTGLES
Graphics/Rendering/FTGL.hs
bsd-2-clause
13,564
0
15
2,357
2,551
1,342
1,209
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Scoutess.Service.Source.Dir (fetchDir, fetchVersionsDir) where import Control.Monad.Trans (MonadIO, liftIO) import Data.Monoid ((<>)) import Data.Set (singleton) import Data.Text (pack) import Data.Version (showVersion) import Distribution.PackageDescription.Parse (readPackageDescription) import Distribution.Simple.Utils (installDirectoryContents) import Distribution.Verbosity (silent) import System.FilePath ((</>)) import Scoutess.Core import Scoutess.Types fetchDir :: MonadIO m => SourceConfig -> VersionInfo -> m (Either SourceException SourceInfo) fetchDir sourceConfig versionInfo = do let Dir oldPath = viSourceLocation versionInfo nameVersion = viName versionInfo <> "-" <> showVersion (viVersion versionInfo) newPath = srcCacheDir sourceConfig </> nameVersion liftIO $ installDirectoryContents silent oldPath newPath return . Right $ SourceInfo newPath versionInfo fetchVersionsDir :: MonadIO m => SourceLocation -> m (Either SourceException VersionSpec) fetchVersionsDir sourceLocation = do let Dir filePath = sourceLocation mCabalFile <- liftIO $ findCabalFile filePath case mCabalFile of Nothing -> do return . Left . SourceErrorOther $ "Could not find .cabal file in " <> pack filePath Just cabalFile -> do gpd <- liftIO $ readPackageDescription silent cabalFile let versionInfo = createVersionInfo sourceLocation cabalFile gpd return . Right $ VersionSpec (singleton versionInfo) Nothing
cartazio/scoutess
Scoutess/Service/Source/Dir.hs
bsd-3-clause
1,631
0
15
351
411
210
201
36
2
{-#LANGUAGE ScopedTypeVariables, QuasiQuotes, OverloadedStrings #-} module Web.Horse.Forms.Basic where import Control.Arrow import Data.Monoid textField :: String -> Maybe String -> String -> String -> String textField label err val name = mconcat $ [ maybe "" (\x -> mconcat ["<span class=\"error\">", x, "</span><br/>"]) err, "<label>", label, "<br/><input type=\"text\" value=\"", val, "\" name=\"", name, "\"><br/></label>" ] link :: String -> String -> String link linkName name = mconcat ["<a href=\"?", name, "=1\">", linkName, "</a><br/>"] select :: String -> [String] -> Int -> String -> String select label options val name = mconcat [ "<label>", label, "<br/>", "<select name=\"", name, "\">", opts, "</select>", "<br/>", "</label>" ] where opts = mconcat $ map renderOpt (zip [0..] options) renderOpt (n, opt) = mconcat $ [ "<option ", if n == val then "selected=\"selected\"" else "", " value=\"", show n, "\">", opt, "</option>" ] wrapForm :: String -> String wrapForm f = mconcat ["<form method='POST' action=''>", f, "<input type='submit'></input></form>"]
jhp/on-a-horse
Web/Horse/Forms/Basic.hs
bsd-3-clause
1,334
0
11
414
334
191
143
28
2
import Control.Concurrent import Control.Concurrent.STM.TChan import Control.Monad import Control.Monad.STM import Quant.MatchingEngine.BasicTypes import Quant.MatchingEngine.Book import Quant.MatchingEngine.Feed import Quant.MatchingEngine.Protocol import System.Directory import System.Environment import System.Exit import System.FilePath import System.IO import Quant.MatchingEngine.Tests main :: IO () main = getArgs >>= parseArgs where parseArgs :: [String] -> IO () parseArgs [rootdir, port] = mif (doesDirectoryExist rootdir) (startServer rootdir port) (putStrLn ("Directory "++ rootdir ++ " not found")) parseArgs [arg] | arg == "test" = runTests parseArgs _ = usage >> exitWith (ExitFailure 2) mif :: Monad m => m Bool -> m () -> m () -> m () mif test actionTrue actionFalse = test >>= \t -> if t then actionTrue else actionFalse usage :: IO () usage = putStrLn "exec <root directory> <port>" type FeedChannel = TChan FeedMessage type TradeChannel = TChan TradeMessage type TradeResponseChannel = TChan TradeResponseMessage startServer :: FilePath -> String -> IO () startServer rootDir port = do marketFeed <- newTChanIO tradingInterface <- newTChanIO tradingResponses <- newTChanIO _ <- forkIO $ algo (ClientID 1) marketFeed tradingInterface tradingResponses exchange emptyBook marketFeed tradingInterface tradingResponses print "yada" -- read config file to get list of securities to create books for -- configuration also specifices number and type of algos to create -- and has algo-specific config (root directory for each algo instance) -- create control channel and control module (sends market open, auction, close, timer events) -- create books -- create client trade interface channels -- create client feed interface channels -- create clients and connect channels -- algo :: ClientID -> FeedChannel -> TradeChannel -> TradeResponseChannel -> IO () algo clientID feed tradeChannel tradeResponses = do atomically $ writeTChan tradeChannel (NewOrder clientID Buy (Price 100) (ShareCount 50) (ClientOrderID 1)) tradeResponseMessage <- atomically $ readTChan tradeResponses print ("received trade response " ++ show tradeResponseMessage) algo clientID feed tradeChannel tradeResponses exchange :: Book -> FeedChannel -> TradeChannel -> TradeResponseChannel -> IO () exchange book feedChannel tradeChannel tradeResponseChannel = do tradeMessage <- atomically $ readTChan tradeChannel let tradeResponseMessage = validateAndAckTradeMessage book tradeMessage atomically $ writeTChan tradeResponseChannel tradeResponseMessage let (newBook, feedMessages, tradeResponseMessages) = processTradeMessage book tradeMessage print ("new book:" ++ show newBook) let r1 = map (writeTChan feedChannel) feedMessages let r2 = map (writeTChan tradeResponseChannel) tradeResponseMessages exchange newBook feedChannel tradeChannel tradeResponseChannel validateAndAckTradeMessage :: Book -> TradeMessage -> TradeResponseMessage validateAndAckTradeMessage book (NewOrder clientID _ _ _ clientOrderID) = NewOrderAck clientID clientOrderID orderID where orderID = OrderID 1101 validateAndAckTradeMessage book (CancelOrder clientID orderID) = if okToCancel then CancelOrderAck clientID orderID else CancelOrderNack clientID orderID where okToCancel = orderExists book clientID orderID processTradeMessage :: Book -> TradeMessage -> (Book, [FeedMessage], [TradeResponseMessage]) processTradeMessage book (NewOrder clientID Buy price shareCount clientOrderID) = (newBook, feedMessages, tradeResponseMessages) where (newBook, trades) = processBuy book (OrderBuy price time shareCount clientID orderID) feedMessages = map (\(Trade tprice tshareCount _ _ _ _) -> FeedMessageTrade tshareCount tprice) trades tradeResponseMessages = map genFill1 trades ++ map genFill2 trades time = Time 0 orderID = OrderID 400 genFill1 :: Trade -> TradeResponseMessage genFill1 (Trade price shareCount orderID clientID _ _) = OrderFill clientID orderID price shareCount genFill2 :: Trade -> TradeResponseMessage genFill2 (Trade price shareCount _ _ orderID clientID) = OrderFill clientID orderID price shareCount
tdoris/StockExchange
Main.hs
bsd-3-clause
4,420
0
12
853
1,122
556
566
72
3
----------------------------------------------------------------------------- -- -- Module : Language.Haskell.Parser.ParsePostProcess -- Copyright : -- License : AllRightsReserved -- -- Maintainer : -- Stability : -- Portability : -- -- Description: Post processing for the Haskell Parser suite. -- -- The HsParser places each HsMatch equation in -- a seperate HsFunbind, even when multiple -- HsMatchs should appear in the same HsFunbind. -- -- This code is intended as a post-processor of the -- output from the parser, that re-groups -- associated HsMatch equations into the same -- HsFunBind. It has no semantic effect on the code. -- -- It requires a single pass over the entire parse -- tree, some applications might find this expensive. -- -- Associated matches are determined by the string -- name of the variable that is being bound, in -- _unqualified_ form. This means that: -- -- Foo.f w x = ... -- f y z = ... -- -- are treated as matches for the same variable, -- even though I don't think this is possible in -- Haskell 98, the parser does allow it, and thus so -- does this code. -- -- There is plenty of room for static analysis of the -- parsed code, but that is not the intention of this -- module. -- -- In time, other post-processing tasks may be -- placed in this module. -- ----------------------------------------------------------------------------- module Haskell.Parser.ParsePostProcess (fixFunBindsInModule, fixFunBinds) where import Haskell.Syntax.Syntax -- applies fixFunBinds to all decls in a Module fixFunBindsInModule :: HsModule -> HsModule fixFunBindsInModule (HsModule loc modName exports imports decls) = HsModule loc modName exports imports $ fixFunBinds decls -- collect associated funbind equations (matches) into a single funbind -- intended as a post-processer for the parser output fixFunBinds :: [HsDecl] -> [HsDecl] fixFunBinds [] = [] fixFunBinds (d:ds) = case d of HsClassDecl sloc ctx n tvs decls -> HsClassDecl sloc ctx n tvs (fixFunBinds decls) : fixFunBinds ds HsInstDecl sloc ctx qn tys decls -> HsInstDecl sloc ctx qn tys (fixFunBinds decls) : fixFunBinds ds HsFunBind matches@(_:_) -> let funName = matchName $ head matches (same, different) = span (sameFun funName) (d:ds) newMatches = map fixFunBindsInMatch $ collectMatches same in (HsFunBind newMatches) : fixFunBinds different HsPatBind sloc pat rhs decls -> HsPatBind sloc pat (fixFunBindsInRhs rhs) (fixFunBinds decls) : fixFunBinds ds _anythingElse -> d : fixFunBinds ds -- get the variable name bound by a match matchName :: HsMatch -> String matchName (HsMatch _sloc name _pats _rhs _whereDecls) = unHsName name -- selects the string identifier from a (possibly) -- qualified name (ie drops the module name when possible) unQualName :: HsQName -> String unQualName name = case name of (Qual _mod ident) -> unHsName ident (UnQual ident) -> unHsName ident (Special s) -> specialName s unHsName (HsIdent s) = s unHsName (HsSymbol s) = s specialName HsUnitCon = "()" specialName HsListCon = "[]" specialName HsFunCon = "->" specialName (HsTupleCon n) = "(" ++ (replicate (n - 1) ',') ++ ")" specialName HsCons = ":" -- True if the decl is a HsFunBind and binds the same name as the -- first argument, False otherwise sameFun :: String -> HsDecl -> Bool sameFun name (HsFunBind matches@(_:_)) | name == (matchName $ head matches) = True | otherwise = False sameFun _name _decl = False -- collects all the HsMatch equations from any FunBinds -- from a list of HsDecls collectMatches :: [HsDecl] -> [HsMatch] collectMatches [] = [] collectMatches (d:ds) = case d of (HsFunBind matches) -> matches ++ collectMatches ds _anythingElse -> collectMatches ds -- the rest of the code just crawls tediously over the syntax tree -- recursively fixing up any decls where they occur fixFunBindsInMatch :: HsMatch -> HsMatch fixFunBindsInMatch (HsMatch sloc name pats rhs wheres) = HsMatch sloc name pats (fixFunBindsInRhs rhs) $ fixFunBinds wheres fixFunBindsInRhs :: HsRhs -> HsRhs fixFunBindsInRhs (HsUnGuardedRhs e) = HsUnGuardedRhs $ fixFunBindsInExp e fixFunBindsInRhs (HsGuardedRhss rhss) = HsGuardedRhss $ map fixFunBindsInGuardedRhs rhss fixFunBindsInGuardedRhs :: HsGuardedRhs -> HsGuardedRhs fixFunBindsInGuardedRhs (HsGuardedRhs sloc e1 e2) = HsGuardedRhs sloc (fixFunBindsInExp e1) (fixFunBindsInExp e2) fixFunBindsInExp :: HsExp -> HsExp fixFunBindsInExp e@(HsVar _) = e fixFunBindsInExp e@(HsCon _) = e fixFunBindsInExp e@(HsLit _) = e fixFunBindsInExp (HsInfixApp e1 e2 e3) = HsInfixApp (fixFunBindsInExp e1) e2 (fixFunBindsInExp e3) fixFunBindsInExp (HsApp e1 e2) = HsApp (fixFunBindsInExp e1) (fixFunBindsInExp e2) fixFunBindsInExp (HsNegApp e) = HsNegApp $ fixFunBindsInExp e fixFunBindsInExp (HsLambda sloc pats e) = HsLambda sloc pats $ fixFunBindsInExp e fixFunBindsInExp (HsLet decls e) = HsLet (fixFunBinds decls) $ fixFunBindsInExp e fixFunBindsInExp (HsIf e1 e2 e3) = HsIf (fixFunBindsInExp e1) (fixFunBindsInExp e2) (fixFunBindsInExp e3) fixFunBindsInExp (HsCase e alts) = HsCase (fixFunBindsInExp e) $ map fixFunBindsInAlt alts fixFunBindsInExp (HsDo stmts) = HsDo $ map fixFunBindsInStmt stmts fixFunBindsInExp (HsTuple exps) = HsTuple $ map fixFunBindsInExp exps fixFunBindsInExp (HsList exps) = HsList $ map fixFunBindsInExp exps fixFunBindsInExp (HsParen e) = HsParen $ fixFunBindsInExp e fixFunBindsInExp (HsLeftSection e1 e2) = HsLeftSection (fixFunBindsInExp e1) e2 fixFunBindsInExp (HsRightSection e1 e2) = HsRightSection e1 (fixFunBindsInExp e2) fixFunBindsInExp e@(HsRecConstr qname fieldUpdates) = e fixFunBindsInExp (HsRecUpdate e fieldUpdates) = HsRecUpdate (fixFunBindsInExp e) fieldUpdates fixFunBindsInExp (HsEnumFrom e) = HsEnumFrom $ fixFunBindsInExp e fixFunBindsInExp (HsEnumFromTo e1 e2) = HsEnumFromTo (fixFunBindsInExp e1) (fixFunBindsInExp e2) fixFunBindsInExp (HsEnumFromThen e1 e2) = HsEnumFromThen (fixFunBindsInExp e1) (fixFunBindsInExp e2) fixFunBindsInExp (HsEnumFromThenTo e1 e2 e3) = HsEnumFromThenTo (fixFunBindsInExp e1) (fixFunBindsInExp e2) (fixFunBindsInExp e3) fixFunBindsInExp (HsListComp e stmts) = HsListComp (fixFunBindsInExp e) $ map fixFunBindsInStmt stmts fixFunBindsInExp (HsExpTypeSig sloc e qtype) = HsExpTypeSig sloc (fixFunBindsInExp e) qtype fixFunBindsInExp (HsAsPat name e) = HsAsPat name $ fixFunBindsInExp e fixFunBindsInExp e@HsWildCard = e fixFunBindsInExp (HsIrrPat e) = HsIrrPat $ fixFunBindsInExp e fixFunBindsInAlt :: HsAlt -> HsAlt fixFunBindsInAlt (HsAlt sloc pat (HsUnGuardedAlt e) decls) = HsAlt sloc pat (HsUnGuardedAlt (fixFunBindsInExp e)) $ fixFunBinds decls fixFunBindsInAlt (HsAlt sloc pat (HsGuardedAlts alts) decls) = HsAlt sloc pat (HsGuardedAlts $ map fixFunBindsInGuardedAlt alts) $ fixFunBinds decls fixFunBindsInGuardedAlt :: HsGuardedAlt -> HsGuardedAlt fixFunBindsInGuardedAlt (HsGuardedAlt sloc e1 e2) = HsGuardedAlt sloc (fixFunBindsInExp e1) (fixFunBindsInExp e2) fixFunBindsInStmt :: HsStmt -> HsStmt fixFunBindsInStmt (HsGenerator sloc pat e) = HsGenerator sloc pat $ fixFunBindsInExp e fixFunBindsInStmt (HsQualifier e) = HsQualifier $ fixFunBindsInExp e fixFunBindsInStmt (HsLetStmt decls) = HsLetStmt $ fixFunBinds decls --------------------------------------------------------------------------------
emcardoso/CTi
src/Haskell/Parser/ParsePostProcess.hs
bsd-3-clause
8,149
0
14
1,942
1,880
954
926
136
5
{-# LANGUAGE BangPatterns, CPP, OverloadedStrings #-} -- | -- Module: Data.Aeson.Parser.Internal -- Copyright: (c) 2011, 2012 Bryan O'Sullivan -- (c) 2011 MailRank, Inc. -- License: Apache -- Maintainer: Bryan O'Sullivan <bos@serpentine.com> -- Stability: experimental -- Portability: portable -- -- Efficiently and correctly parse a JSON string. The string must be -- encoded as UTF-8. module Data.Aeson.Parser.Internal ( -- * Lazy parsers json, jsonEOF , value , jstring -- * Strict parsers , json', jsonEOF' , value' -- * Helpers , decodeWith , decodeStrictWith , eitherDecodeWith , eitherDecodeStrictWith ) where import Control.Applicative ((*>), (<$>), (<*), liftA2, pure) import Control.Monad.IO.Class (liftIO) import Data.Aeson.Types (Result(..), Value(..)) import Data.Attoparsec.ByteString.Char8 (Parser, char, endOfInput, scientific, skipSpace, string) import Data.Bits ((.|.), shiftL) import Data.ByteString.Internal (ByteString(..)) import Data.Char (chr) import Data.Text (Text) import Data.Text.Encoding (decodeUtf8') import Data.Text.Internal.Encoding.Utf8 (ord2, ord3, ord4) import Data.Text.Internal.Unsafe.Char (ord) import Data.Vector as Vector (Vector, fromList) import Data.Word (Word8) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Ptr (minusPtr) import Foreign.Ptr (Ptr, plusPtr) import Foreign.Storable (poke) import System.IO.Unsafe (unsafePerformIO) import qualified Data.Attoparsec.ByteString as A import qualified Data.Attoparsec.Lazy as L import qualified Data.Attoparsec.Zepto as Z import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Internal as B import qualified Data.ByteString.Unsafe as B import qualified Data.HashMap.Strict as H #define BACKSLASH 92 #define CLOSE_CURLY 125 #define CLOSE_SQUARE 93 #define COMMA 44 #define DOUBLE_QUOTE 34 #define OPEN_CURLY 123 #define OPEN_SQUARE 91 #define C_0 48 #define C_9 57 #define C_A 65 #define C_F 70 #define C_a 97 #define C_f 102 #define C_n 110 #define C_t 116 -- | Parse a top-level JSON value. -- -- The conversion of a parsed value to a Haskell value is deferred -- until the Haskell value is needed. This may improve performance if -- only a subset of the results of conversions are needed, but at a -- cost in thunk allocation. -- -- This function is an alias for 'value'. In aeson 0.8 and earlier, it -- parsed only object or array types, in conformance with the -- now-obsolete RFC 4627. json :: Parser Value json = value -- | Parse a top-level JSON value. -- -- This is a strict version of 'json' which avoids building up thunks -- during parsing; it performs all conversions immediately. Prefer -- this version if most of the JSON data needs to be accessed. -- -- This function is an alias for 'value''. In aeson 0.8 and earlier, it -- parsed only object or array types, in conformance with the -- now-obsolete RFC 4627. json' :: Parser Value json' = value' object_ :: Parser Value object_ = {-# SCC "object_" #-} Object <$> objectValues jstring value object_' :: Parser Value object_' = {-# SCC "object_'" #-} do !vals <- objectValues jstring' value' return (Object vals) where jstring' = do !s <- jstring return s objectValues :: Parser Text -> Parser Value -> Parser (H.HashMap Text Value) objectValues str val = do skipSpace let pair = liftA2 (,) (str <* skipSpace) (char ':' *> val) H.fromList <$> commaSeparated pair CLOSE_CURLY {-# INLINE objectValues #-} array_ :: Parser Value array_ = {-# SCC "array_" #-} Array <$> arrayValues value array_' :: Parser Value array_' = {-# SCC "array_'" #-} do !vals <- arrayValues value' return (Array vals) commaSeparated :: Parser a -> Word8 -> Parser [a] commaSeparated item endByte = do w <- A.peekWord8' if w == endByte then A.anyWord8 >> return [] else loop where loop = do v <- item <* skipSpace ch <- A.satisfy $ \w -> w == COMMA || w == endByte if ch == COMMA then skipSpace >> (v:) <$> loop else return [v] {-# INLINE commaSeparated #-} arrayValues :: Parser Value -> Parser (Vector Value) arrayValues val = do skipSpace Vector.fromList <$> commaSeparated val CLOSE_SQUARE {-# INLINE arrayValues #-} -- | Parse any JSON value. You should usually 'json' in preference to -- this function, as this function relaxes the object-or-array -- requirement of RFC 4627. -- -- In particular, be careful in using this function if you think your -- code might interoperate with Javascript. A na&#xef;ve Javascript -- library that parses JSON data using @eval@ is vulnerable to attack -- unless the encoded data represents an object or an array. JSON -- implementations in other languages conform to that same restriction -- to preserve interoperability and security. value :: Parser Value value = do skipSpace w <- A.peekWord8' case w of DOUBLE_QUOTE -> A.anyWord8 *> (String <$> jstring_) OPEN_CURLY -> A.anyWord8 *> object_ OPEN_SQUARE -> A.anyWord8 *> array_ C_f -> string "false" *> pure (Bool False) C_t -> string "true" *> pure (Bool True) C_n -> string "null" *> pure Null _ | w >= 48 && w <= 57 || w == 45 -> Number <$> scientific | otherwise -> fail "not a valid json value" -- | Strict version of 'value'. See also 'json''. value' :: Parser Value value' = do skipSpace w <- A.peekWord8' case w of DOUBLE_QUOTE -> do !s <- A.anyWord8 *> jstring_ return (String s) OPEN_CURLY -> A.anyWord8 *> object_' OPEN_SQUARE -> A.anyWord8 *> array_' C_f -> string "false" *> pure (Bool False) C_t -> string "true" *> pure (Bool True) C_n -> string "null" *> pure Null _ | w >= 48 && w <= 57 || w == 45 -> do !n <- scientific return (Number n) | otherwise -> fail "not a valid json value" -- | Parse a quoted JSON string. jstring :: Parser Text jstring = A.word8 DOUBLE_QUOTE *> jstring_ -- | Parse a string without a leading quote. jstring_ :: Parser Text jstring_ = {-# SCC "jstring_" #-} do s <- A.scan False $ \s c -> if s then Just False else if c == DOUBLE_QUOTE then Nothing else Just (c == BACKSLASH) _ <- A.word8 DOUBLE_QUOTE s1 <- if BACKSLASH `B.elem` s then case unescape s of Right r -> return r Left err -> fail err else return s case decodeUtf8' s1 of Right r -> return r Left err -> fail $ show err {-# INLINE jstring_ #-} unescape :: ByteString -> Either String ByteString unescape s = unsafePerformIO $ do let len = B.length s fp <- B.mallocByteString len -- We perform no bounds checking when writing to the destination -- string, as unescaping always makes it shorter than the source. withForeignPtr fp $ \ptr -> do ret <- Z.parseT (go ptr) s case ret of Left err -> return (Left err) Right p -> do let newlen = p `minusPtr` ptr slop = len - newlen Right <$> if slop >= 128 && slop >= len `quot` 4 then B.create newlen $ \np -> B.memcpy np ptr newlen else return (PS fp 0 newlen) where go ptr = do h <- Z.takeWhile (/=BACKSLASH) let rest = do start <- Z.take 2 let !slash = B.unsafeHead start !t = B.unsafeIndex start 1 escape = case B.elemIndex t "\"\\/ntbrfu" of Just i -> i _ -> 255 if slash /= BACKSLASH || escape == 255 then fail "invalid JSON escape sequence" else if t /= 117 -- 'u' then copy h ptr >>= word8 (B.unsafeIndex mapping escape) >>= go else do a <- hexQuad if a < 0xd800 || a > 0xdfff then copy h ptr >>= charUtf8 (chr a) >>= go else do b <- Z.string "\\u" *> hexQuad if a <= 0xdbff && b >= 0xdc00 && b <= 0xdfff then let !c = ((a - 0xd800) `shiftL` 10) + (b - 0xdc00) + 0x10000 in copy h ptr >>= charUtf8 (chr c) >>= go else fail "invalid UTF-16 surrogates" done <- Z.atEnd if done then copy h ptr else rest mapping = "\"\\/\n\t\b\r\f" hexQuad :: Z.ZeptoT IO Int hexQuad = do s <- Z.take 4 let hex n | w >= C_0 && w <= C_9 = w - C_0 | w >= C_a && w <= C_f = w - 87 | w >= C_A && w <= C_F = w - 55 | otherwise = 255 where w = fromIntegral $ B.unsafeIndex s n a = hex 0; b = hex 1; c = hex 2; d = hex 3 if (a .|. b .|. c .|. d) /= 255 then return $! d .|. (c `shiftL` 4) .|. (b `shiftL` 8) .|. (a `shiftL` 12) else fail "invalid hex escape" decodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Maybe a decodeWith p to s = case L.parse p s of L.Done _ v -> case to v of Success a -> Just a _ -> Nothing _ -> Nothing {-# INLINE decodeWith #-} decodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString -> Maybe a decodeStrictWith p to s = case either Error to (A.parseOnly p s) of Success a -> Just a Error _ -> Nothing {-# INLINE decodeStrictWith #-} eitherDecodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Either String a eitherDecodeWith p to s = case L.parse p s of L.Done _ v -> case to v of Success a -> Right a Error msg -> Left msg L.Fail _ _ msg -> Left msg {-# INLINE eitherDecodeWith #-} eitherDecodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString -> Either String a eitherDecodeStrictWith p to s = case either Error to (A.parseOnly p s) of Success a -> Right a Error msg -> Left msg {-# INLINE eitherDecodeStrictWith #-} -- $lazy -- -- The 'json' and 'value' parsers decouple identification from -- conversion. Identification occurs immediately (so that an invalid -- JSON document can be rejected as early as possible), but conversion -- to a Haskell value is deferred until that value is needed. -- -- This decoupling can be time-efficient if only a smallish subset of -- elements in a JSON value need to be inspected, since the cost of -- conversion is zero for uninspected elements. The trade off is an -- increase in memory usage, due to allocation of thunks for values -- that have not yet been converted. -- $strict -- -- The 'json'' and 'value'' parsers combine identification with -- conversion. They consume more CPU cycles up front, but have a -- smaller memory footprint. -- | Parse a top-level JSON value followed by optional whitespace and -- end-of-input. See also: 'json'. jsonEOF :: Parser Value jsonEOF = json <* skipSpace <* endOfInput -- | Parse a top-level JSON value followed by optional whitespace and -- end-of-input. See also: 'json''. jsonEOF' :: Parser Value jsonEOF' = json' <* skipSpace <* endOfInput word8 :: Word8 -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) word8 w ptr = do liftIO $ poke ptr w return $! ptr `plusPtr` 1 copy :: ByteString -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) copy (PS fp off len) ptr = liftIO . withForeignPtr fp $ \src -> do B.memcpy ptr (src `plusPtr` off) len return $! ptr `plusPtr` len charUtf8 :: Char -> Ptr Word8 -> Z.ZeptoT IO (Ptr Word8) charUtf8 ch ptr | ch < '\x80' = liftIO $ do poke ptr (fromIntegral (ord ch)) return $! ptr `plusPtr` 1 | ch < '\x800' = liftIO $ do let (a,b) = ord2 ch poke ptr a poke (ptr `plusPtr` 1) b return $! ptr `plusPtr` 2 | ch < '\xffff' = liftIO $ do let (a,b,c) = ord3 ch poke ptr a poke (ptr `plusPtr` 1) b poke (ptr `plusPtr` 2) c return $! ptr `plusPtr` 3 | otherwise = liftIO $ do let (a,b,c,d) = ord4 ch poke ptr a poke (ptr `plusPtr` 1) b poke (ptr `plusPtr` 2) c poke (ptr `plusPtr` 3) d return $! ptr `plusPtr` 4
beni55/aeson
Data/Aeson/Parser/Internal.hs
bsd-3-clause
12,821
0
31
3,922
3,330
1,731
1,599
254
9
module Language.SOS.Data.Rule where newtype Rule = Rule Name [Premiss] Conclusion [CompileTimeCondition] [RuntimeCondidtion] deriving (Eq, Ord, Show) type Name = String type Premiss = Transformation type Conclusion = Transformation newtype CompileTimeCondition = CTC newtype RuntimeCondition = RTC
JanBessai/hsos
src/Language/SOS/Data/Rule.hs
bsd-3-clause
309
3
8
47
75
46
29
-1
-1
module Math.Probably.Student where import Numeric.LinearAlgebra import Math.Probably.FoldingStats import Text.Printf --http://www.haskell.org/haskellwiki/Gamma_and_Beta_function --cof :: [Double] cof = [76.18009172947146,-86.50532032941677,24.01409824083091, -1.231739572450155,0.001208650973866179,-0.000005395239384953] --ser :: Double ser = 1.000000000190015 --gammaln :: Double -> Double gammaln xx = let tmp' = (xx+5.5) - (xx+0.5)*log(xx+5.5) ser' = foldl (+) ser $ map (\(y,c) -> c/(xx+y)) $ zip [1..] cof in -tmp' + log(2.5066282746310005 * ser' / xx) beta z w = exp (gammaln z + gammaln w - gammaln (z+w)) fac :: (Enum a, Num a) => a -> a fac n = product [1..n] ixbeta :: (Enum a, Floating a) => a -> a -> a -> a ixbeta x a b = let top = fac $ a+b-1 down j = fac j * fac (a+b-1-j) in sum $ map (\j->(top/down j)*(x**j)*(1-x)**(a+b-1-j)) [a..a+b-1] studentIntegral :: (Enum a, Floating a) => a -> a -> a studentIntegral t v = 1-ixbeta (v/(v+t*t)) (v/2) (1/2) tTerms :: Vector Double tTerms = fromList $ map tTermUnmemo [1..100] tTermUnmemo :: Int -> Double tTermUnmemo nu = gammaln ((realToFrac nu+1)/2) - log(realToFrac nu*pi)/2 - gammaln (realToFrac nu/2) tTerm1 :: Int -> Double tTerm1 df | df <= 100 = tTerms@>df | otherwise = tTermUnmemo df tDist :: Int -> Double -> Double tDist df t = tTerm1 df - (realToFrac df +1/2) * log (1+(t*t)/(realToFrac df)) tDist3 :: Double -> Double -> Int -> Double -> Double tDist3 mean prec df x = tTerm1 df + log(prec)/2 - (realToFrac df +1/2) * log (1+(prec*xMinusMu*xMinusMu)/(realToFrac df)) where xMinusMu = x-mean oneSampleT :: Floating b => b -> Fold b b oneSampleT v0 = fmap (\(mean,sd,n)-> (mean - v0)/(sd/(sqrt n))) meanSDNF pairedSampleT :: Fold (Double, Double) Double pairedSampleT = before (fmap (\(mean,sd,n)-> (mean)/(sd/(sqrt n))) meanSDNF) (uncurry (-)) data TTestResult = TTestResult { degFreedom :: Int, tValue :: Double, pValue :: Double } ppTTestRes :: TTestResult -> String ppTTestRes (TTestResult df tval pval) = printf "paired t(%d)=%.3g, p=%.3g" df tval pval pairedTTest :: [(Double,Double)] -> TTestResult pairedTTest vls = let tval = runStat pairedSampleT vls df = length vls - 1 pval = (1-) $ studentIntegral (tval) (realToFrac df) in TTestResult df tval pval oneSampleTTest :: [Double] -> TTestResult oneSampleTTest vls = let tval = runStat (oneSampleT 0) vls df = length vls - 1 pval = (1-) $ studentIntegral (tval) (realToFrac df) in TTestResult df tval pval
glutamate/probably-baysig
src/Math/Probably/Student.hs
bsd-3-clause
2,739
0
16
688
1,259
662
597
56
1
{-# LANGUAGE TemplateHaskell #-} module Gifter.Giveaway.Internal where import Control.Lens import qualified Data.Text as T type Points = Integer data GiveawayStatus = Open Points | Closed | ContributorsOnly | AlreadyOwn | NoLogin | Entered | MissingBaseGame | ComingSoon | NotEnoughPoints deriving (Show, Eq) data Giveaway = Giveaway { _url :: T.Text , _status :: GiveawayStatus , _entries :: Integer , _formKey :: Maybe T.Text , _accPoints :: Integer } deriving (Show, Eq) makeLenses ''Giveaway
arjantop/gifter
src/Gifter/Giveaway/Internal.hs
bsd-3-clause
674
0
10
251
136
83
53
24
0
{- This file is part of the Haskell package cassava-streams. It is subject to the license terms in the LICENSE file found in the top-level directory of this distribution and at git://pmade.com/cassava-streams/LICENSE. No part of cassava-streams package, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the LICENSE file. -} -------------------------------------------------------------------------------- module Main (main) where -------------------------------------------------------------------------------- import System.Environment import System.IO import System.IO.Streams.Csv.Tutorial -------------------------------------------------------------------------------- main :: IO () main = do args <- getArgs case args of ["todo"] -> onlyTodo stdin stdout ["done", x] -> markDone x stdin stdout _ -> fail "give one of todo or done"
pjones/cassava-streams
bin/tutorial.hs
bsd-3-clause
938
0
10
140
102
57
45
11
3
{- Lets.RoseTree A Rose Tree (or multi-way tree) is a tree structure with a variable and unbounded number of branches at each node. This implementation allows for an empty tree. References [1] Wikipedia, "Rose Tree", http://en.wikipedia.org/wiki/Rose_tree [2] Jeremy Gibbons, "Origami Programming", appears in The Fun of Programming edited by J. Gibbons and O. de Moor, Palgrave McMillan, 2003, pages 41-60. PDF available at: http://www.staff.science.uu.nl/~3860418/msc/11_infomtpt/papers/origami-programming_Gibbons.pdf -} module Lets.RoseTree ( RoseTree -- constructors , node , singleton -- properties , value , children , forest , size , depth -- operations , insert , toList , flatten ) where -- -- definitions -- data RoseTree a = Empty | Node a (Forest a) deriving (Show, Eq) type Forest a = [RoseTree a] -- -- constructors -- node :: a -> [RoseTree a] -> RoseTree a node v t = Node v t singleton :: a -> RoseTree a singleton v = Node v [] -- -- operations -- value :: RoseTree a -> Maybe a value (Empty) = Nothing value (Node v _) = Just v children :: RoseTree a -> [RoseTree a] children (Empty) = [] children (Node _ t) = t -- [] or [...] -- also called forest forest = children size :: RoseTree a -> Int size (Empty) = 0 size (Node v ts) = 1 + sum (map size ts) depth :: RoseTree a -> Int depth (Empty) = 0 depth (Node _ []) = 1 depth (Node v ts) = 1 + maximum (map depth ts) toList :: RoseTree a -> [a] toList Empty = [] toList (Node v t) = v : concatMap toList t -- also called flatten flatten = toList -- -- a simple insert operation that places tree q at the head of the children -- of tree r insert :: RoseTree a -> RoseTree a -> RoseTree a insert Empty r = r insert q Empty = q insert q r@(Node v t) = Node v (q:t) -- -- sample -- rt1 = singleton 1 rt2 = singleton 2 rt3 = node 3 [rt1, rt2] rt4 = node 8 [node 3 [], node 4 []] rt5 = node 12 [rt4, rt3]
peterson/lets-tree
src/Lets/RoseTree.hs
bsd-3-clause
1,983
0
8
475
603
324
279
47
1
import Test.Hspec import Test.QuickCheck import Lib main :: IO () main = hspec $ do describe "Prelude.head" $ do it "returns the first element of a list" $ do head [23..] `shouldBe` (23 :: Int) it "returns the first element of an *arbitrary* list" $ property $ \x xs -> head (x:xs) == (x :: Int)
kazeula/haskell-json-sample
test/Spec.hs
bsd-3-clause
322
0
16
82
115
59
56
10
1
{- | Module : SAWScript.SBVModel Description : Abstract representation for .sbv file format. Maintainer : jhendrix Stability : provisional -} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module SAWScript.SBVModel where import Data.Binary import Data.List(sortBy) import Control.Monad (liftM, liftM2, liftM3) import System.IO (openBinaryFile, IOMode(..), hClose) import qualified Data.ByteString.Lazy as B -- Auxiliary Cryptol types type Major = Int type Minor = Int data Version = Version Major Minor deriving Show type TyCon = String type Name = String data Loc = Loc String Int{-line-} Int{-col-} | LocPrim String | LocDefault String | LocExpr | LocInternal | LocNone deriving Show data Scheme a = Scheme [String] [a] [Predicate a] (Type a) deriving Show schemeType :: Scheme a -> Type a schemeType (Scheme _ _ _ t) = t embedScheme :: Type a -> Scheme a embedScheme t = Scheme [] [] [] t data Predicate a = PredEq (Type a) (Type a) (Maybe (Predicate a)) [Loc] | PredSubst a (Type a) [Loc] | PredGrEq (Type a) (Type a) [Loc] | PredFin (Type a) [Loc] | PredImplied (Predicate a) deriving Show data Type a = TVar a | TInt Integer | TApp TyCon [Type a] | TRecord [(Name, Scheme a)] deriving Show type IRTyVar = TyVar Int data TyVar a = TyVar { tyvarName :: a, tyvarKind :: Kind , tyvarIgnorable :: Bool, tyvarDefaultable :: Bool } deriving Show type IRType = Type IRTyVar data Kind = KStar | KSize | KShape deriving Show -- SBV programs type Size = Integer type GroundVal = Integer type NodeId = Int data SBV = SBV !Size !(Either GroundVal NodeId) deriving Show data SBVCommand = Decl CtrlPath !SBV (Maybe SBVExpr) | Output !SBV deriving Show data Operator = BVAdd | BVSub | BVMul | BVDiv Loc | BVMod Loc | BVPow | BVIte | BVShl | BVShr | BVRol | BVRor | BVExt !Integer !Integer -- hi lo | BVAnd | BVOr | BVXor | BVNot | BVEq | BVGeq | BVLeq | BVGt | BVLt | BVApp -- append -- following is not essential, but simplifies lookups | BVLkUp !Integer !Integer -- index size, result size -- Uninterpreted constants | BVUnint Loc [(String, String)] (String, IRType) -- loc, code-gen info, name/type deriving Show data SBVExpr = SBVAtom !SBV | SBVApp !Operator ![SBV] deriving Show type CtrlPath = [Either SBV SBV] type VC = ( CtrlPath -- path to the VC , SBVExpr -- stipulated trap; need to prove this expr is not true , String) -- associated error message data SBVPgm = SBVPgm (Version, IRType, [SBVCommand], [VC] , [String] -- warnings , [((String, Loc), IRType, [(String, String)])] -- uninterpeted functions and code ) deriving Show -- make it an instance of Binary instance Binary Loc where put (Loc s i j) = putWord8 0 >> put s >> put i >> put j put (LocPrim s) = putWord8 1 >> put s put (LocDefault s) = putWord8 2 >> put s put LocExpr = putWord8 3 put LocInternal = putWord8 4 put LocNone = putWord8 5 get = do tag <- getWord8 case tag of 0 -> liftM3 Loc get get get 1 -> liftM LocPrim get 2 -> liftM LocDefault get 3 -> return LocExpr 4 -> return LocInternal 5 -> return LocNone n -> error $ "Binary.Loc: " ++ show n instance Binary Version where put (Version ma mi) = put ma >> put mi get = liftM2 Version get get instance Binary SBVPgm where put (SBVPgm cmds) = put cmds get = liftM SBVPgm get -- only monomorphic types supported below sortUnder :: (Ord b) => (a -> b) -> [a] -> [a] sortUnder f = sortBy (\a b -> compare (f a) (f b)) instance Binary IRType where put (TInt i) = putWord8 0 >> put i put (TApp t ts) = putWord8 1 >> put t >> put ts put (TRecord nss) = putWord8 2 >> put [(n, schemeType s) | (n, s) <- sortUnder fst nss] put TVar{} = error $ "internal: put not defined on TVar" get = do tag <- getWord8 case tag of 0 -> liftM TInt get 1 -> liftM2 TApp get get 2 -> do nts <- get return (TRecord [(n, embedScheme t) | (n, t) <- nts]) n -> error $ "Binary.IRType: " ++ show n instance Binary SBV where put (SBV i esn) = put i >> put esn get = liftM2 SBV get get instance Binary SBVCommand where put (Decl path v mbe) = putWord8 0 >> put path >> put v >> put mbe put (Output v) = putWord8 1 >> put v get = do tag <- getWord8 case tag of 0 -> liftM3 Decl get get get 1 -> liftM Output get n -> error $ "Binary.SBVCommand: " ++ show n instance Binary SBVExpr where put (SBVAtom s) = putWord8 0 >> put s put (SBVApp o es) = putWord8 1 >> put o >> put es get = do tag <- getWord8 case tag of 0 -> liftM SBVAtom get 1 -> liftM2 SBVApp get get n -> error $ "Binary.SBVExpr: " ++ show n instance Binary Operator where put BVAdd = putWord8 0 put BVSub = putWord8 1 put BVMul = putWord8 2 put (BVDiv l) = putWord8 3 >> put l put (BVMod l) = putWord8 4 >> put l put BVPow = putWord8 5 put BVIte = putWord8 6 put BVShl = putWord8 7 put BVShr = putWord8 8 put BVRol = putWord8 9 put BVRor = putWord8 10 put (BVExt hi lo) = putWord8 11 >> put hi >> put lo put BVAnd = putWord8 12 put BVOr = putWord8 13 put BVXor = putWord8 14 put BVNot = putWord8 15 put BVEq = putWord8 16 put BVGeq = putWord8 17 put BVLeq = putWord8 18 put BVGt = putWord8 19 put BVLt = putWord8 20 put BVApp = putWord8 21 put (BVLkUp i r) = putWord8 22 >> put i >> put r put (BVUnint l cgs nt) = putWord8 23 >> put l >> put cgs >> put nt get = do tag <- getWord8 case tag of 0 -> return BVAdd 1 -> return BVSub 2 -> return BVMul 3 -> liftM BVDiv get 4 -> liftM BVMod get 5 -> return BVPow 6 -> return BVIte 7 -> return BVShl 8 -> return BVShr 9 -> return BVRol 10 -> return BVRor 11 -> liftM2 BVExt get get 12 -> return BVAnd 13 -> return BVOr 14 -> return BVXor 15 -> return BVNot 16 -> return BVEq 17 -> return BVGeq 18 -> return BVLeq 19 -> return BVGt 20 -> return BVLt 21 -> return BVApp 22 -> liftM2 BVLkUp get get 23 -> liftM3 BVUnint get get get n -> error $ "Binary.Operator: " ++ show n loadSBV :: FilePath -> IO SBVPgm loadSBV f = do h <- openBinaryFile f ReadMode pgm <- B.hGetContents h B.length pgm `seq` hClose h -- oh, the horror.. return (decode pgm)
GaloisInc/saw-script
src/SAWScript/SBVModel.hs
bsd-3-clause
7,300
0
19
2,598
2,466
1,256
1,210
212
1
{-# LANGUAGE CPP #-} -- #hide -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.Types -- Copyright : (c) Sven Panne 2009 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : sven.panne@aedion.de -- Stability : stable -- Portability : portable -- -- All types from the OpenGL 3.1 core, see <http://www.opengl.org/registry/>. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.Types where import Data.Int import Data.Word import Foreign.C.Types import Foreign.Ptr type GLboolean = CUChar type GLubyte = CUChar type GLbyte = CSChar type GLchar = CChar type GLclampd = CDouble type GLdouble = CDouble type GLclampf = CFloat type GLfloat = CFloat type GLbitfield = CUInt type GLenum = CUInt type GLuint = CUInt type GLint = CInt type GLsizei = CInt type GLhalf = CUShort type GLushort = CUShort type GLshort = CShort type GLintptr = CPtrdiff type GLsizeiptr = CPtrdiff type GLint64 = Int64 type GLuint64 = Word64 -- Not part of the core, but it is very handy to define this here type GLhandle = CUInt type GLsync = Ptr () type GLvdpauSurface = GLintptr -- | Fixed point type for OES_fixed_point extension. type GLfixed = CInt newtype CLevent = CLEvent (Ptr CLevent) newtype CLcontext = CLContext (Ptr CLcontext) -- both are actually function pointers type GLdebugproc = FunPtr (GLenum -> GLenum -> GLuint -> GLenum -> GLsizei -> Ptr GLchar -> Ptr () -> IO ())
Laar/OpenGLRawgen
BuildSources/Types.hs
bsd-3-clause
1,632
0
15
342
278
178
100
34
0
import System.Environment (getArgs) import Data.List.Split (splitOn) import Data.List (intercalate, intersect) doIntersect :: Eq a => [[a]] -> [a] doIntersect l = intersect (head l) (last l) main :: IO () main = do [inpFile] <- getArgs input <- readFile inpFile putStr . unlines . map (intercalate "," . doIntersect . map (splitOn ",") . splitOn ";") $ lines input
nikai3d/ce-challenges
easy/intersection.hs
bsd-3-clause
380
0
15
74
171
87
84
10
1
module Render.Stmts.Poke.SiblingInfo where import Prettyprinter import Polysemy import Polysemy.Input import Relude import Error import Marshal.Scheme import Spec.Name data SiblingInfo a = SiblingInfo { siReferrer :: Doc () -- ^ How to refer to this sibling in code , siScheme :: MarshalScheme a -- ^ What type is this sibling } type HasSiblingInfo a r = Member (Input (CName -> Maybe (SiblingInfo a))) r getSiblingInfo :: forall a r . (HasErr r, HasSiblingInfo a r) => CName -> Sem r (SiblingInfo a) getSiblingInfo n = note ("Unable to find info for: " <> unCName n) . ($ n) =<< input
expipiplus1/vulkan
generate-new/src/Render/Stmts/Poke/SiblingInfo.hs
bsd-3-clause
688
0
12
201
178
101
77
-1
-1