code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Bio.Utils.Overlap ( overlapFragment , overlapNucl , coverage ) where import Bio.Data.Bed import Conduit import Lens.Micro ((^.)) import Control.Monad import qualified Data.ByteString.Char8 as B import Data.Function import qualified Data.HashMap.Strict as M import qualified Data.IntervalMap.Strict as IM import Data.List import qualified Data.Vector.Unboxed as V import qualified Data.Vector.Unboxed.Mutable as VM -- | convert lines of a BED file into a data structure - A hashmap of which the -- | chromosomes, and values are interval maps. toMap :: [(B.ByteString, (Int, Int))] -> M.HashMap B.ByteString (IM.IntervalMap Int Int) toMap input = M.fromList.map create.groupBy ((==) `on` (fst.fst)) $ zip input [0..] where f ((_, x), i) = (toInterval x, i) create xs = (fst.fst.head $ xs, IM.fromDistinctAscList.map f $ xs) {-# INLINE toMap #-} coverage :: [BED] -- ^ genomic locus in BED format -> ConduitT () BED IO () -- ^ reads in BED format -> IO (V.Vector Double, Int) coverage bin tags = liftM getResult $ runConduit $ tags .| sink where sink = do v <- lift $ VM.replicate (n+1) 0 mapM_C $ \t -> do let set = M.lookup (t^.chrom) featMap s = t^.chromStart e = t^.chromEnd b = (s, e) l = e - s + 1 intervals = case set of Just iMap -> IM.toList . IM.intersecting iMap . toInterval $ b _ -> [] forM_ intervals (\interval -> do let i = snd interval nucl = overlap b . fst $ interval VM.write v i . (+nucl) =<< VM.read v i ) VM.write v n . (+l) =<< VM.read v n lift $ V.freeze v getResult v = (V.zipWith normalize (V.slice 0 n v) featWidth, v V.! n) featMap = toMap.map (\x -> (x^.chrom, (x^.chromStart, x^.chromEnd))) $ bin featWidth = V.fromList $ map size bin n = length bin overlap (l, u) (IM.ClosedInterval l' u') | l' >= l = if u' <= u then u'-l'+1 else u-l'+1 | otherwise = if u' <= u then u'-l+1 else u-l+1 overlap _ _ = 0 normalize a b = fromIntegral a / fromIntegral b overlapFragment, overlapNucl :: [(Int, Int)] -- ^ Ascending order list -> [(Int, Int)] -- ^ tags in any order -> V.Vector Int overlapFragment xs ts = V.create (VM.replicate n 0 >>= go ts) where n = length xs iMap = IM.fromAscList $ zip (map toInterval xs) [0..] go ts' v = do forM_ ts' (\x -> do let indices = IM.elems . IM.intersecting iMap . toInterval $ x forM_ indices (\i -> VM.write v i . (+1) =<< VM.read v i) ) return v overlapNucl xs ts = V.create (VM.replicate n 0 >>= go ts) where n = length xs iMap = IM.fromAscList $ zip (map toInterval xs) [0..] go ts' v = do forM_ ts' (\x -> do let intervals = IM.toList . IM.intersecting iMap . toInterval $ x forM_ intervals (\interval -> do let i = snd interval nucl = overlap x . fst $ interval VM.write v i . (+nucl) =<< VM.read v i ) ) return v overlap (l, u) (IM.ClosedInterval l' u') | l' >= l = if u' <= u then u'-l'+1 else u-l'+1 | otherwise = if u' <= u then u'-l+1 else u-l+1 overlap _ _ = 0 toInterval :: (a, a) -> IM.Interval a toInterval (l, u) = IM.ClosedInterval l u {-# INLINE toInterval #-}
kaizhang/bioinformatics-toolkit
bioinformatics-toolkit/src/Bio/Utils/Overlap.hs
mit
3,836
0
24
1,441
1,405
739
666
80
5
module Main where import Data.Set (Set) import qualified Data.Set as S import Astar newtype State = State (Int, Int) deriving (Show, Eq, Ord) start :: State start = State (1,1) goal :: (Int, Int) goal = (31, 39) favNumber :: Int favNumber = 1362 atGoal :: State -> Bool atGoal (State (x, y)) = (x,y) == goal aStarParams :: Parameter State State aStarParams = Parameter heur surroundings atGoal id where heur (State (x,y)) = let (gx,gy) = goal in abs (gx-x) + abs (gy-y) surroundings :: State -> [State] surroundings pos = [ pos' | d <- directions , let pos' = move d pos , inside pos' , openSpace favNumber pos' ] findSurroundings :: Set State -> [(Int,State)] -> Set State findSurroundings visited [] = visited findSurroundings visited ((n,cur):nxts) | S.member cur visited = findSurroundings visited nxts | otherwise = let neighs = [ (n-1,pos) | pos <- surroundings cur, let n' = n-1, n' >= 0 ] visited' = S.insert cur visited in findSurroundings visited' (nxts ++ neighs) openSpace :: Int -> State -> Bool openSpace fav (State (x,y)) = not (calcWall fav x y) calcWall :: Int -> Int -> Int -> Bool calcWall fav x y = let d = x*x + 3*x + 2*x*y + y + y*y + fav ones = sumOnes d in odd ones sumOnes :: Int -> Int sumOnes 0 = 0 sumOnes 1 = 1 sumOnes n = let (d,m) = n `divMod` 2 in m + sumOnes d inside :: State -> Bool inside (State (x,y)) = x >= 0 && y >= 0 move :: (Int,Int) -> State -> State move (dx,dy) (State (x,y)) = State (x+dx,y+dy) directions :: [(Int,Int)] directions = [ (0,1), (0,-1), (1,0), (-1,0) ] solutionPath :: Path State solutionPath = aStar aStarParams start part2 :: Int part2 = let set = findSurroundings S.empty [(50,start)] in S.size set main :: IO () main = do let path = solutionPath showGrid favNumber 50 50 path putStrLn $ "part1 : " ++ show (length path - 1) putStrLn $ "part2 : " ++ show part2 putStrLn "all done" showSolution :: IO () showSolution = do let path = solutionPath showGrid favNumber 50 50 path showGrid :: Int -> Int -> Int -> Path State -> IO () showGrid fav w h poss = let cells = [ [ wall fav poss (x,y) | x <- [0..w] ] | y <- [0..h] ] in printLines cells where wall fav poss (x,y) = let isW = calcWall fav x y isP = State (x,y) `elem` poss in if isW && isP then 'X' else if isP then 'O' else if isW then '#' else '.' printLines = putStrLn . unlines
CarstenKoenig/AdventOfCode2016
Day13/Main.hs
mit
2,535
0
18
689
1,205
637
568
89
4
-- Constants for Asteroids module Constants where -- Game window position windowPosition = (100, 100) -- Ship rotation rate, in radians per second rotationRate = 5 :: Double -- Ship acceleration, in pixels/s^2 acceleration = 10 :: Double
Solonarv/Asteroids
Constants.hs
mit
241
0
5
41
35
24
11
4
1
{-# htermination (minimumTup0 :: (List Tup0) -> Tup0) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Tup0 = Tup0 ; data Ordering = LT | EQ | GT ; foldl :: (a -> b -> a) -> a -> (List b) -> a; foldl f z Nil = z; foldl f z (Cons x xs) = foldl f (f z x) xs; foldl1 :: (a -> a -> a) -> (List a) -> a; foldl1 f (Cons x xs) = foldl f x xs; compareTup0 :: Tup0 -> Tup0 -> Ordering compareTup0 Tup0 Tup0 = EQ; esEsOrdering :: Ordering -> Ordering -> MyBool esEsOrdering LT LT = MyTrue; esEsOrdering LT EQ = MyFalse; esEsOrdering LT GT = MyFalse; esEsOrdering EQ LT = MyFalse; esEsOrdering EQ EQ = MyTrue; esEsOrdering EQ GT = MyFalse; esEsOrdering GT LT = MyFalse; esEsOrdering GT EQ = MyFalse; esEsOrdering GT GT = MyTrue; not :: MyBool -> MyBool; not MyTrue = MyFalse; not MyFalse = MyTrue; fsEsOrdering :: Ordering -> Ordering -> MyBool fsEsOrdering x y = not (esEsOrdering x y); ltEsTup0 :: Tup0 -> Tup0 -> MyBool ltEsTup0 x y = fsEsOrdering (compareTup0 x y) GT; min0 x y MyTrue = y; otherwise :: MyBool; otherwise = MyTrue; min1 x y MyTrue = x; min1 x y MyFalse = min0 x y otherwise; min2 x y = min1 x y (ltEsTup0 x y); minTup0 :: Tup0 -> Tup0 -> Tup0 minTup0 x y = min2 x y; minimumTup0 :: (List Tup0) -> Tup0 minimumTup0 = foldl1 minTup0;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/minimum_1.hs
mit
1,358
0
9
331
573
310
263
39
1
{-# LANGUAGE TypeOperators, TypeFamilies #-} {-| Module : Peer Copyright : (c) Kai Lindholm, 2014 License : MIT Maintainer : megantti@gmail.com Stability : experimental For more info on actions, see "Network.RTorrent.Action". -} module Network.RTorrent.Peer ( PeerId (..) , PeerInfo (..) , PeerAction , getPeerPartial , allPeers , getTorrentPeers -- * Control peers , banPeer , disconnectPeer -- * Functions for single variables , getPeerHash , getPeerIp , getPeerClientVersion , getPeerUpRate , getPeerDownRate , getPeerUpTotal , getPeerDownTotal , getPeerEncrypted , getPeerCompletedPercent , getPeerPort ) where import Control.Applicative import Control.DeepSeq import Network.RTorrent.Action.Internals import Network.RTorrent.Torrent import Network.RTorrent.Command import Network.XmlRpc.Internals import Data.List.Split (splitOn) data PeerId = PeerId !TorrentId !String deriving Show instance XmlRpcType PeerId where toValue (PeerId (TorrentId tid) i) = ValueString $ tid ++ ":p" ++ i fromValue v = return . uncurry PeerId =<< parse =<< fromValue v where parse :: Monad m => String -> m (TorrentId, String) parse str = do [hash, s] <- return $ splitOn ":p" str return (TorrentId hash, s) getType _ = TString instance NFData PeerId where rnf (PeerId tid i) = rnf tid `seq` rnf i data PeerInfo = PeerInfo { peerClientVersion :: String , peerIp :: String , peerUpRate :: !Int , peerDownRate :: !Int , peerUpTotal :: !Int , peerDownTotal :: !Int , peerEncrypted :: !Bool , peerCompletedPercent :: !Int , peerPort :: !Int , peerId :: PeerId } deriving Show instance NFData PeerInfo where rnf (PeerInfo a0 a1 a2 a3 a4 a5 a6 a7 a8 a9) = rnf a0 `seq` rnf a1 `seq` rnf a2 `seq` rnf a3 `seq` rnf a4 `seq` rnf a5 `seq` rnf a6 `seq` rnf a7 `seq` rnf a8 `seq` rnf a9 getPeerHash :: PeerId -> PeerAction String getPeerHash = simpleAction "p.get_id" [] getPeerIp :: PeerId -> PeerAction String getPeerIp = simpleAction "p.get_address" [] getPeerClientVersion :: PeerId -> PeerAction String getPeerClientVersion = simpleAction "p.get_client_version" [] getPeerUpRate :: PeerId -> PeerAction Int getPeerUpRate = simpleAction "p.get_up_rate" [] getPeerDownRate :: PeerId -> PeerAction Int getPeerDownRate = simpleAction "p.get_down_rate" [] getPeerUpTotal :: PeerId -> PeerAction Int getPeerUpTotal = simpleAction "p.get_up_total" [] getPeerDownTotal :: PeerId -> PeerAction Int getPeerDownTotal = simpleAction "p.get_down_total" [] getPeerEncrypted :: PeerId -> PeerAction Bool getPeerEncrypted = fmap toEnum . simpleAction "p.is_encrypted" [] getPeerCompletedPercent :: PeerId -> PeerAction Int getPeerCompletedPercent = simpleAction "p.get_completed_percent" [] getPeerPort :: PeerId -> PeerAction Int getPeerPort = simpleAction "p.get_port" [] -- | Get a partial peer. @PeerId@ can be gotten by running @allPeers@. getPeerPartial :: PeerId -> PeerAction (PeerId -> PeerInfo) getPeerPartial = runActionB $ PeerInfo <$> b getPeerClientVersion <*> b getPeerIp <*> b getPeerUpRate <*> b getPeerDownRate <*> b getPeerUpTotal <*> b getPeerDownTotal <*> b getPeerEncrypted <*> b getPeerCompletedPercent <*> b getPeerPort where b = ActionB disconnectPeer :: PeerId -> PeerAction Int disconnectPeer = simpleAction "p.disconnect" [] banPeer :: PeerId -> PeerAction Int banPeer = simpleAction "p.banned.set" [PInt 1] type PeerAction = Action PeerId getTorrentPeers :: TorrentId -> TorrentAction [PeerInfo] getTorrentPeers = fmap (map contract) . allPeers getPeerPartial where contract (x :*: f) = f x -- | Run the peer action on all peers that a torrent has. allPeers :: (PeerId -> PeerAction a) -> TorrentId -> TorrentAction [PeerId :*: a] allPeers p = fmap addId . (getTorrentId <+> allToMulti (allP (getPeerHash <+> p))) where addId (hash :*: peers) = map (\(phash :*: f) -> PeerId hash phash :*: f) peers allP :: (PeerId -> PeerAction a) -> AllAction PeerId a allP = AllAction (PeerId (TorrentId "") "") "p.multicall"
megantti/rtorrent-rpc
Network/RTorrent/Peer.hs
mit
4,286
0
15
952
1,153
608
545
127
1
--2 --Each new term in the Fibonacci sequence is generated by adding the previous two terms. --By starting with 1 and 2, the first 10 terms will be: --1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... --By considering the terms in the Fibonacci sequence whose values do not exceed four million, --find the sum of the even-valued terms. fibs = 0 : 1 : zipWith (+) fibs (tail fibs) euler2 = sum $ filter (even) $ takeWhile(< 4000000) fibs
RossMeikleham/Project-Euler-Haskell
02.hs
mit
432
0
8
88
63
36
27
2
1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleInstances #-} module ChurchNumbers where class Boolean a where tru :: a -> a -> a tru = \ t -> \ f -> t fls :: a -> a -> a fls = \ t -> \ f -> f test :: (a -> a -> a) -> a -> a -> a test = \ l -> \ m -> \ n -> l m n instance (Boolean a) => (Boolean (a -> a -> a)) instance Boolean Bool class Number a where c0, c1, c2, c3 :: (a -> a) -> a -> a c0 = \ s -> \ z -> z c1 = \ s -> \ z -> s z c2 = \ s -> \ z -> s (s z) c3 = \ s -> \ z -> s (s (s z)) scc :: ((a -> a) -> a -> a) -> ((a -> a) -> a -> a) scc = \ n -> \ s -> \z -> n s (s z) plus :: ((a -> a) -> a -> a) -> ((a -> a) -> a -> a) -> (a -> a) -> a -> a plus = \ n -> \ m -> \ s -> \ z -> m s (n s z) times :: ((a -> a) -> a -> a) -> ((a -> a) -> a -> a) -> (a -> a) -> a -> a times = \ m -> \ n -> \ s -> \ z -> m (n s) z instance (Number a) => (Number ((a -> a) -> a -> a)) instance Number Integer fix :: (a -> a) -> a fix = \ f -> f (fix f) fac = fix g where g = \ fct -> \ n -> if n == 0 then 1 else n * fct (n - 1)
triplepointfive/datatypes
src/ChurchNumbers.hs
mit
1,077
2
13
372
691
381
310
30
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module Cook.Docker.TLS where import Control.Lens ((&), (.~)) import Data.Default import Data.X509.CertificateStore import Data.X509.File import Network.Connection (TLSSettings(..)) import Network.HTTP.Client (ManagerSettings) import Network.HTTP.Client.TLS (mkManagerSettings) import Network.TLS import Network.TLS.Extra.Cipher import Network.Wreq import System.Directory import System.Environment import System.FilePath data UseCA = WithCA FilePath | NoCA data UseClientCert = WithClientCert FilePath FilePath | NoClientCert getTlsManagerSettings :: UseClientCert -> UseCA -> String -> IO ManagerSettings getTlsManagerSettings useCC useCA host = do cas <- case useCA of WithCA certPath -> readSignedObject certPath NoCA -> return [] creds <- case useCC of WithClientCert certPath keyPath -> either error Just <$> credentialLoadX509 certPath keyPath NoClientCert -> return Nothing let hooks = def { onCertificateRequest = \_ -> return creds , onServerCertificate = \store -> onServerCertificate def (store <> makeCertificateStore cas) } clientParams = (defaultParamsClient host "") { clientHooks = hooks , clientSupported = def { supportedCiphers = ciphersuite_strong } } tlsSettings = TLSSettings clientParams return $ mkManagerSettings tlsSettings Nothing tlsDockerOpts :: String -> IO Options tlsDockerOpts host = do explicitCertsPath <- lookupEnv "DOCKER_CERT_PATH" certsPath <- case explicitCertsPath of Just path -> return path Nothing -> (</> ".docker") <$> getEnv "HOME" let certPath = certsPath </> "cert.pem" keyPath = certsPath </> "key.pem" caPath = certsPath </> "ca.pem" clientCertsExist <- (&&) <$> doesFileExist certPath <*> doesFileExist keyPath let useCC = if clientCertsExist then WithClientCert certPath keyPath else NoClientCert useCA = WithCA caPath settings <- getTlsManagerSettings useCC useCA host return $ defaults & manager .~ Left settings
factisresearch/dockercook
src/lib/Cook/Docker/TLS.hs
mit
2,477
0
16
786
541
286
255
66
3
module Main where import Test.Hspec import Hackonad.LineParser main :: IO () main = hspec $ do describe "Hackonad" $ do context "Input line" $ do it "Empty line" $ do parseInputLine "" `shouldBe` ("", []) it "Plain command name" $ do parseInputLine "ls" `shouldBe` ("ls", []) it "Common args" $ do parseInputLine "ls -l ~" `shouldBe` ("ls", ["-l", "~"]) context "Parse input" $ do it "Arg contans a space" $ do parseCommandLine "ls One\\ Two" `shouldBe` [ Command (Raw "ls") [ Raw "One Two" ] ] it "separated with semicolon" $ do parseCommandLine "mkdir 1; cd 1" `shouldBe` [ Command (Raw "mkdir") [ Raw "1" ], Command (Raw "cd") [ Raw "1" ] ] it "Nested $(command) block" $ do parseCommandLine "echo hello1-$(echo hello2-$(echo hello3-$(echo hello4)))" `shouldBe` [ Command (Raw "echo") [ Arg [ Raw "hello1-", Command (Raw "echo") [ Arg [ Raw "hello2-", Command (Raw "echo") [ Arg [ Raw "hello3-", Command (Raw "echo") [ Raw "hello4" ] ] ] ] ] ] ] ]
triplepointfive/Hackonad
tests/Spec.hs
mit
1,578
0
33
793
381
188
193
40
1
{----------------------------------------------------------------------------------------- Module name: BufferedSocket Made by: Tomas Möre 2015 Usage: This module is mean to be imported qualified ex: import Headers qualified BS Notes: Buffered sockets are a data type that is a kind of overlay on normal sockets. All the exported read / write operations are build such that they ALLWAYS read / write the ammount of bytes requested This package allows some cases of lazy IO. Some people see Lazy io as the devil incarné. However it is excpected that anyone using this module is cabale of understanding any possible side effects. WARNINGS: This module uses a ton of IO and non functional ways of solving problems. This is because we want to be as spacetime efficient as possible. This module does NOT contain "beatiful" haskell code ------------------------------------------------------------------------------------------} {-# LANGUAGE OverloadedStrings #-} import qualified Data.ByteString as B import qualified Data.ByteString.Internal as BI import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Builder as BB import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Core as BS import qualified Reader as BS import qualified Writer as BS import Data.Word import Data.Int import Control.Monad import qualified Network.Socket as NS import Data.IORef import System.Timeout import Data.Maybe import Control.Concurrent import System.Exit type ErrorMessage = String type DataType = String testServerPort = 1337 testHost = "localhost" testServerMaxConnections = 1 bufferSize = 1024 * 10 makeTestTcpServer:: (BS.BufferedSocket -> IO ()) -> IO () makeTestTcpServer thunk = NS.withSocketsDo $ do -- create socket serverSock <- NS.socket NS.AF_INET NS.Stream 0 -- make socket immediately reusable - eases debugging. NS.setSocketOption serverSock NS.ReuseAddr 1 NS.bindSocket serverSock (NS.SockAddrInet testServerPort NS.iNADDR_ANY) NS.listen serverSock testServerMaxConnections socketData@(subSock,subSockaddr) <- NS.accept serverSock serverBSock <- BS.makeBufferedSocket socketData bufferSize bufferSize thunk serverBSock NS.sClose serverSock makeTestTcpClient :: IO BS.BufferedSocket makeTestTcpClient = do sock <- NS.socket NS.AF_INET NS.Stream 0 let myHints = NS.defaultHints { NS.addrFlags = [], NS.addrFamily = NS.AF_INET, NS.addrSocketType = NS.Stream} (adressInfo:_) <- NS.getAddrInfo (Just myHints) (Just testHost) (Just $ show testServerPort) let sockAddr = NS.addrAddress adressInfo putStrLn $ show adressInfo putStrLn $ show sockAddr NS.connect sock sockAddr clientSockAddr <- NS.getSocketName sock BS.makeBufferedSocket (sock, clientSockAddr) bufferSize bufferSize main = do quitMVar <- newEmptyMVar :: IO (MVar Bool) clientMvar <- newEmptyMVar let thunk = testingServerThunk quitMVar clientMvar forkIO $ makeTestTcpServer thunk clientBSock <- makeTestTcpClient putMVar clientMvar clientBSock readMVar quitMVar testByteString = "Hello world!!!" testLazyByteString = "Hello world!!!" testingServerThunk :: MVar Bool -> MVar BS.BufferedSocket -> BS.BufferedSocket -> IO () testingServerThunk quitMVar clientMvar serverBSock = do clientBSock <- readMVar clientMvar putStrLn "Starting tests: " testNumbersFunction serverBSock clientBSock "Word8" (255 :: Word8) testNumbersFunction serverBSock clientBSock "Word16" (456 :: Word16) testNumbersFunction serverBSock clientBSock "Word32" (16 :: Word32) testNumbersFunction serverBSock clientBSock "Word64" (32 :: Word64) testNumbersFunction serverBSock clientBSock "Int8" (123 :: Int8) testNumbersFunction serverBSock clientBSock "Int16" (456 :: Int16) testNumbersFunction serverBSock clientBSock "Int32" (789 :: Int32) testNumbersFunction serverBSock clientBSock "Int64" (9000 :: Int64) testNumbersFunction serverBSock clientBSock "Int8" (-123 :: Int8) testNumbersFunction serverBSock clientBSock "Int16" (-456 :: Int16) testNumbersFunction serverBSock clientBSock "Int32" (-789 :: Int32) testNumbersFunction serverBSock clientBSock "Int64" (-9000 :: Int64) testStringsFunction serverBSock clientBSock "ByteString" (B.length testByteString) (testByteString:: B.ByteString) testStringsFunction serverBSock clientBSock "Lazy ByteString" (fromIntegral $ BL.length testLazyByteString) (testLazyByteString :: BL.ByteString) {-- testStringsFunction serverBSock clientBSock "String" (length testNativeString) (testNativeString:: String) testStringsFunction serverBSock clientBSock "Text" (T.length testText) (testText :: T.Text) testStringsFunction serverBSock clientBSock "Lazy Text" (fromIntegral $ TL.length testLazyText) (testLazyText :: TL.Text) --} NS.sClose $ BS.nativeSocket serverBSock NS.sClose $ BS.nativeSocket clientBSock putMVar quitMVar True exitSuccess testNumbersFunction:: (BS.Sendable a, Show a, BS.Readable a, Eq a) => BS.BufferedSocket -> BS.BufferedSocket -> DataType -> a -> IO () testNumbersFunction serverBSock clientBSock dataType value = do putStrLn $ "--------- Testing data of type: " ++ dataType ++ " ---------" putStrLn $ "Value: " ++ (show value) BS.send clientBSock value BS.flush clientBSock putStrLn $ "Data sent!" inData <- BS.read serverBSock putStrLn "Data recieved!" putStrLn $ "Recieved value: " ++ (show inData) if inData == value then putStrLn $ "--------- " ++ dataType ++ " tests success ---------" else putStrLn $ "!!! ERROR: Recieved data not same as sent data" testStringsFunction:: (BS.Sendable a, Show a, BS.ReadableString a, Eq a) => BS.BufferedSocket -> BS.BufferedSocket -> DataType -> Int -> a -> IO () testStringsFunction serverBSock clientBSock dataType dataLength value = do putStrLn $ "--------- Testing data of type: " ++ dataType ++ " ---------" putStrLn $ "Value: " ++ (show value) BS.send clientBSock value BS.flush clientBSock putStrLn "Data sent!" inData <- BS.readString serverBSock dataLength putStrLn "Data recieved!" putStrLn $ "Recieved value: " ++ (show inData) if inData == value then putStrLn $ "--------- " ++ dataType ++ " tests success ---------" else putStrLn $ "!!! ERROR: Recieved data not same as sent data"
black0range/BufferedSocket
Network/BufferedSocket/test.hs
mit
6,671
0
12
1,334
1,392
697
695
104
2
-- Remove String Spaces -- https://www.codewars.com/kata/57eae20f5500ad98e50002c5 module Kata (noSpace) where import Data.Char (isSpace) noSpace :: String -> String noSpace = filter (not . isSpace)
gafiatulin/codewars
src/8 kyu/NoSpace.hs
mit
201
0
7
27
45
27
18
4
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module Data.XY where import Data.Aeson import Data.Data import qualified Data.Map as Map import GHC.Generics import Lucid.Js (ToJExpr(..)) data XY = XY { xXY:: Double, yXY:: Double } deriving (Show, Eq, Data, Typeable, Generic) instance FromJSON XY instance ToJSON XY instance ToJExpr XY where toJExpr (XY x y) = toJExpr (Map.fromList [ ("xXY", x) , ("yXY", y) ] :: Map.Map String Double)
tonyday567/hdcharts
src/Data/XY.hs
mit
574
0
10
156
167
96
71
19
0
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-} {- | Module : $Header$ Description : Instance of class Logic for THF. Copyright : (c) A. Tsogias, DFKI Bremen 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : Alexis.Tsogias@dfki.de Stability : provisional Portability : non-portable (imports Logic) Instance of class Logic for THF. -} module THF.Logic_THF where import Logic.Logic import ATC.ProofTree () import Common.ProofTree import Common.ProverTools import THF.ATC_THF () import THF.Cons import THF.StaticAnalysisTHF import THF.ProveLeoII import THF.Sign import THF.Print -------------------------------------------------------------------------------- -- TODO: -- * Ask Till or Christian about other methods of the instances that are -- important -------------------------------------------------------------------------------- data THF = THF deriving Show instance Language THF where description _ = "THF is a language for Higher Order Logic from the TPTP standard.\n" ++ "For further information please refer to" ++ "http://www.cs.miami.edu/~tptp/TPTP/SyntaxBNF.html" instance Logic.Logic.Syntax THF BasicSpecTHF () () where parse_basic_spec THF = Just (basicSpec BSTHF0) -- remaining default implementations are fine! instance Sentences THF SentenceTHF SignTHF MorphismTHF SymbolTHF where map_sen THF _ = return print_named THF = printNamedSentenceTHF -- sym_name THF = -- negation THF _ = -- other default implementations are fine instance StaticAnalysis THF BasicSpecTHF SentenceTHF () () SignTHF MorphismTHF SymbolTHF () where basic_analysis THF = Just basicAnalysis empty_signature THF = emptySign signature_union THF = sigUnion signatureDiff THF = sigDiff intersection THF = sigIntersect -- is_subsig THF _ _ = True -- subsig_inclusion THF = defaultInclusion -- In order to find the LeoII prover there must be an entry in the -- PATH environment variable leading to the leo executable -- (The executable leo.opt is not supported. In this case there should be a link -- callen leo, or something like that.) instance Logic THF () BasicSpecTHF SentenceTHF () () SignTHF MorphismTHF SymbolTHF () ProofTree where stability THF = Testing provers THF = [] ++ unsafeProverCheck "leo" "PATH" leoIIProver
nevrenato/Hets_Fork
THF/Logic_THF.hs
gpl-2.0
2,422
0
8
471
323
177
146
34
0
import Prelude import Test.QuickCheck -- QuickCheck implementation of Workshop 1, exercise 2 -- time spent: 30 minutes -- reason: Initial trial / error of QuickCheck main :: IO() main = do print "Checking Workshop 1, exercise 2" quickCheck prop_Exercise2 print "Checking Workshop 1, exercise 3" quickCheck prop_Exercise3 prop_Exercise2 (Positive n) = summedSquaredListOfNumbers n == otherSquaredListOfNumbers n summedSquaredListOfNumbers :: Integer -> Integer summedSquaredListOfNumbers n = sum [ a^2 | a <- [0..n]] otherSquaredListOfNumbers :: Integer -> Integer otherSquaredListOfNumbers n = div (n * (n+1) * (2*n+1)) 6 prop_Exercise3 (Positive n) = summedThirdPowerListOfNumbers n == otherThirdPowerListOfNumbers n summedThirdPowerListOfNumbers :: Integer -> Integer summedThirdPowerListOfNumbers n = sum [ a^3 | a <- [0..n]] otherThirdPowerListOfNumbers :: Integer -> Integer otherThirdPowerListOfNumbers n = (div (n * (n+1)) 2)^2
vdweegen/UvA-Software_Testing
Lab1/Bauke/Exercise1.hs
gpl-3.0
951
0
11
139
273
138
135
18
1
module BenchmarkScene3 where import Types import Materials import Objects bench3Lights :: [Light] bench3Lights = [Light (Vec3 25 0 25) (Vec3 1 0 0) (Vec3 0 1 0) (Color 0.5 0.5 0.5) ] bt0 :: Vec3 bt0 = Vec3 (-5) (-20) 20 bt1 :: Vec3 bt1 = Vec3 (-5) 20 20 bt2 :: Vec3 bt2 = Vec3 (-5) (-20) (-5) bt3 :: Vec3 bt3 = Vec3 (-5) 20 (-5) bt4 :: Vec3 bt4 = Vec3 20 (-20) (-5) bt5 :: Vec3 bt5 = Vec3 20 20 (-5) bench3Objects :: [Object] bench3Objects = [ makeTriangle bt0 bt2 bt1 whiteDull , makeTriangle bt2 bt3 bt1 whiteDull , makeTriangle bt2 bt4 bt3 whiteDull , makeTriangle bt4 bt5 bt3 whiteDull ] ++ (concat $ [ makeParallelPiped (Vec3 x y z) (Vec3 1 0 0) (Vec3 0 1 0) (Vec3 0 0 1) greenGlass | x <- [-4,0 .. 4] , y <- [-4,0 .. 4] , z <- [12,14 .. 16] ] ++ [ makeParallelPiped (Vec3 x y z) (Vec3 1 0 0) (Vec3 0 1 0) (Vec3 0 0 1) redM | x <- [-4,-0 .. 4] , y <- [12,14 .. 16] , z <- [-4,-0 .. 4] ] ++ [ makeParallelPiped (Vec3 x y z) (Vec3 1 0 0) (Vec3 0 1 0) (Vec3 0 0 1) blueM | x <- [12,14 .. 16] , y <- [-4,0 .. 4] , z <- [-4,-0 .. 4] ] ++ [ makeParallelPiped (Vec3 x y z) (Vec3 1 0 0) (Vec3 0 1 0) (Vec3 0 0 1) greenDiamond | x <- [-4,-0 .. 4] , y <- [-4,-0 .. 4] , z <- [-4,-0 .. 4] ] ++ [ makeParallelPiped (Vec3 x y z) (Vec3 1 0 0) (Vec3 0 1 0) (Vec3 0 0 1) goldM | x <- [-4,0 .. 4] , y <- [-16,-14 .. -12] , z <- [-4,-0 .. 4] ] )
jrraymond/ray-tracer
src/BenchmarkScene3.hs
gpl-3.0
1,464
0
16
445
890
482
408
39
1
-- Copyright (C) 2011,2012 Makoto Nishiura. -- This file is part of ERASM++. -- ERASM++ is free software; you can redistribute it and/or modify it under -- the terms of the GNU General Public License as published by the Free -- Software Foundation; either version 3, or (at your option) any later -- version. -- ERASM++ 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 ERASM++; see the file COPYING3. If not see -- <http://www.gnu.org/licenses/>. module ShellCommon ( module Text.Regex.TDFA , module Data.List , module Data.Char , module Data.Maybe , module Text.Printf , module HSH , module System.Console.CmdArgs.Implicit , module System.IO.Temp , module System.IO , module Control.Monad ) where import Text.Regex.TDFA import Data.List import Text.Printf import HSH import System.Console.CmdArgs.Implicit import System.IO.Temp import System.IO hiding (openTempFile,openBinaryTempFile) import Control.Monad import Data.Char import Data.Word import Data.List import Data.Maybe import Data.Function
nishiuramakoto/erasm-plusplus
src/haskell/ShellCommon.hs
gpl-3.0
1,427
0
5
349
157
108
49
24
0
{-| Module : Board Copyright : (c) 2014 Kaashif Hymabaccus License : GPL-3 Maintainer : kaashif@kaashif.co.uk Stability : experimental Portability : POSIX -} {-# LANGUAGE OverloadedStrings #-} module Board where import Paths_venture import Data.Aeson import Data.Maybe (fromJust) import qualified Data.Map as M import qualified Data.ByteString.Lazy as BS import Control.Monad import Control.Applicative import Vector import qualified Player -- | Essentially a sparse array of cells type Board = M.Map Vector2D Cell -- | The \"squares\" on the board the player moves through data Cell = Cell { contents :: [Thing] -- ^ Objects you can take , position :: [Integer] -- ^ Position vector in n-dimensional space. Also the Board key. , description :: String -- ^ Description you see after you visit for the first time , initial :: String -- ^ Description you see visiting for the first time , seen :: Bool -- ^ Whether you've been here before } instance FromJSON Cell where parseJSON (Object v) = Cell <$> v .: "contents" <*> v .: "position" <*> v .: "description" <*> v .: "initial" <*> v .: "seen" parseJSON _ = mzero -- | Placeholder - this will be a data type for quest items, weapons etc. type Thing = String -- | Reads board from wherever cabal hides \"board.json\" readBoard :: IO Board readBoard = getDataFileName "board.json" >>= BS.readFile >>= \s -> return $ decodeBoard s -- | Decodes ByteString JSON (read from a file) into a board decodeBoard :: BS.ByteString -> Board decodeBoard s = foldl insertCell M.empty decoded where decoded = fromJust (decode s :: Maybe [Cell]) -- | Inserts cell into the board map at the right position (i.e. with the right key) insertCell :: Board -> Cell -> Board insertCell m c = M.insert pos c m where pos = ( (position c !! 0),(position c !! 1) ) -- | Checks whether the player is actually on a cell of the /sparse/ board valid :: Player.Player -> Board -> Bool valid p b = M.member (Player.position p) b -- | Gets an appropriate description for a cell, based on whether it has been seen describe :: Board -> Vector2D -> String describe b pos = case (M.lookup pos b) of Just cell -> if (seen cell) then description cell else initial cell Nothing -> "How did this even happen?" -- | Marks the cell the player currently occupies as visited markVisited :: Player.Player -> Board -> Board markVisited p b = M.insert (Player.position p) newcell b where newcell = oldcell { seen = True } oldcell = fromJust $ M.lookup (Player.position p) b
kaashif/venture
src/Board.hs
gpl-3.0
2,836
0
15
795
555
307
248
45
3
module Data.NetworkDB.HostsEntry ( HostEntry(..) , readHostsFileContent , readHostsFile , hfLookup ) where import Data.Maybe import qualified Data.ByteString.Char8 as B import qualified Data.Attoparsec.ByteString.Char8 as P import Debug.Trace import Data.NetworkDB.Helpers.ByLineParser data IPAddress = IPAddress Int Int Int Int deriving (Eq, Ord, Show, Read) ipAddressToString (IPAddress a b c d) = show a ++ "." ++ show b ++ "." ++ show c ++ "." ++ show d data HostEntry = HostEntry { ipAddress :: IPAddress , names :: [B.ByteString] } deriving (Eq, Ord, Show, Read) parseEndOfLine = P.char '\n' parseHostsLine = do addr <- parseIPAddress names <- P.many1 (parseSpace >> parseName) return $ HostEntry addr names -- | Character Pridicates isSpace :: Char -> Bool isSpace c = (c == ' ') || (c == '\t') isSpaceOrLineFeed :: Char -> Bool isSpaceOrLineFeed c = isSpace c || (c == '\n') isAlpha = P.isAlpha_ascii isDigit = P.isDigit isAlphaNumeric c = isAlpha c || isDigit c isNameChar :: Char -> Bool isNameChar c = isAlphaNumeric c || (c == '-') || (c == '.') -- | isHostNameStrict :: B.ByteString -> Bool isHostNameStrict name = let l = B.length name in ( l > 0 && isAlpha (B.index name 0) && B.all isNameChar name && isAlphaNumeric (B.index name (l - 1)) ) -- | Basic Lexical Helpers skipSpace = P.takeWhile isSpace parseSpace = P.satisfy isSpace >> skipSpace parseName = P.takeWhile (not . isSpaceOrLineFeed) parseNameStrict = do name <- parseName if isHostNameStrict name then return name else fail "" parseNames = parseName `P.sepBy` parseSpace parseIPAddress = do octets <- P.decimal `P.sepBy` P.char '.' if length octets /= 4 || any (> 255) octets then fail "cannot parse ip address" else return $ IPAddress (octets!!0) (octets!!1) (octets!!2) (octets!!3) -- | Interface readHostsFileContent :: B.ByteString -> [HostEntry] readHostsFileContent = parseContentLines parseHostsLine readHostsFile :: String -> IO [HostEntry] readHostsFile = parseFileLines parseHostsLine hfLookup :: B.ByteString -> [HostEntry] -> B.ByteString hfLookup name rs = let xs = filter ((name `elem`) . names) rs in case xs of [] -> name (r:_) -> B.pack . ipAddressToString . ipAddress $ r
mjansen/network-db-parsers
Data/NetworkDB/HostsEntry.hs
gpl-3.0
2,308
0
14
480
818
434
384
62
2
module Helium.StaticAnalysis.Messages.Information where import Top.Types import Helium.Main.CompileUtils import Helium.Parser.OperatorTable import Helium.StaticAnalysis.Messages.Messages hiding (Constructor) import Helium.Syntax.UHA_Syntax hiding (Fixity) import Helium.Syntax.UHA_Utils import Helium.Syntax.UHA_Range import qualified Data.Map as M type Fixity = (Int, Assoc) data InfoItem = Function Name TpScheme (Maybe Fixity) | ValueConstructor Name TpScheme (Maybe Fixity) | TypeSynonym Name Int (Tps -> Tp) | DataTypeConstructor Name Int [(Name, TpScheme)] | TypeClass String Class | NotDefined String showInformation :: Bool -> [Option] -> ImportEnvironment -> IO () showInformation reportNotFound options importEnv = let items = concat [ makeInfoItem name | Information name <- options ] in showMessages items where makeInfoItem :: String -> [InfoItem] makeInfoItem string = let notFound items = if null items && reportNotFound then [ NotDefined string ] else items function = case lookupWithKey (nameFromString string) (typeEnvironment importEnv) of Just (name, scheme) -> [Function name scheme (M.lookup name (operatorTable importEnv))] Nothing -> [] constructor = case lookupWithKey (nameFromString string) (valueConstructors importEnv) of Just (name, (_, scheme)) -> [ValueConstructor name scheme (M.lookup name (operatorTable importEnv))] Nothing -> [] synonyms = case lookupWithKey (nameFromString string) (typeSynonyms importEnv) of Just (name, (i, f)) -> [TypeSynonym name i f] Nothing -> [] datatypeconstructor = case lookupWithKey (nameFromString string) (typeConstructors importEnv) of Just (name, (i,_)) | not (M.member name (typeSynonyms importEnv)) -> [DataTypeConstructor name i (findValueConstructors name importEnv)] _ -> [] typeclass = case M.lookup string (classEnvironment importEnv) of Just cl -> [TypeClass string cl] Nothing -> [] in notFound (function ++ constructor ++ synonyms ++ datatypeconstructor ++ typeclass) itemDescription :: InfoItem -> [String] itemDescription infoItem = case infoItem of Function name ts _ -> let tp = unqualify (unquantify ts) start | isOperatorName name = "operator" | isFunctionType tp = "function" | otherwise = "value" in [ "-- " ++ start ++ " " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ] ValueConstructor name _ _ -> [ "-- value constructor " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ] TypeSynonym name _ _ -> [ "-- type synonym " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ] DataTypeConstructor name _ _ -> [ "-- type constructor " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ] TypeClass s _ -> [ " -- type class " ++ s ] NotDefined _ -> [ ] definedOrImported :: Range -> String definedOrImported range | isImportRange range = "imported from " ++ show range | otherwise = "defined at " ++ show range showMaybeFixity :: Name -> Maybe Fixity -> MessageBlocks showMaybeFixity name = let f (prio', associativity) = show associativity ++ " " ++ show prio' ++ " " ++ showNameAsOperator name in maybe [] ((:[]) . MessageString . f) instance HasMessage InfoItem where getMessage infoItem = map (MessageOneLiner . MessageString) (itemDescription infoItem) ++ case infoItem of Function name ts mFixity -> map MessageOneLiner ( MessageString (showNameAsVariable name ++ " :: " ++ show ts) : showMaybeFixity name mFixity ) ValueConstructor name ts mFixity -> map MessageOneLiner ( MessageString (showNameAsVariable name ++ " :: " ++ show ts) : showMaybeFixity name mFixity ) TypeSynonym name i f -> let tps = take i [ TCon [c] | c <- ['a'..] ] text = unwords ("type" : show name : map show tps ++ ["=", show (f tps)]) in [ MessageOneLiner (MessageString text) ] DataTypeConstructor name i cons -> let tps = take i [ TCon [c] | c <- ['a'..] ] text = unwords ("data" : show name : map show tps) related = let f (name', ts) = " " ++ showNameAsVariable name' ++ " :: " ++ show ts in if null cons then [] else " -- value constructors" : map f cons in map MessageOneLiner ( MessageString text : map MessageString related ) TypeClass name (supers, theInstances) -> let f s = s ++ " a" text = "class " ++ showContextSimple (map f supers) ++ f name related = let ef (p, ps) = " instance " ++ show (generalizeAll (ps .=>. p)) in if null theInstances then [] else " -- instances" : map ef theInstances in map MessageOneLiner ( MessageString text : map MessageString related ) NotDefined name -> map MessageOneLiner [ MessageString (show name ++ " not defined") ] findValueConstructors :: Name -> ImportEnvironment -> [(Name, TpScheme)] findValueConstructors name = let test = isName . fst . leftSpine . snd . functionSpine . unqualify . unquantify isName (TCon s) = s == show name isName _ = False toSchemeMap = M.map (\(_, scheme) -> scheme) in M.assocs . M.filter test . toSchemeMap . valueConstructors lookupWithKey :: Ord key => key -> M.Map key a -> Maybe (key, a) lookupWithKey key = M.lookup key . M.mapWithKey (,)
Helium4Haskell/helium
src/Helium/StaticAnalysis/Messages/Information.hs
gpl-3.0
6,251
0
23
2,086
1,883
946
937
122
7
module Data.DotsAndBoxes.Types where import Data.Set as Set import qualified Data.Map.Strict as Map import Data.Maybe import qualified Data.List as L import Control.Arrow import Data.Char -- | Orientation of a move data Orientation = Horizontal | Vertical deriving (Show, Eq, Ord) -- | A move in the game. -- The player is not specified because it can be inferred from the previous moves. data Move = Move { _moveOrientation :: Orientation, _moveX :: Int, _moveY :: Int } deriving (Show, Eq, Ord) -- | The player whose turn it is data Player = Player1 | Player2 deriving (Show, Eq) -- | The result of the game data GameResult = NotFinished | Player1Win | Player2Win | Draw deriving (Show, Eq) -- | Represents a 'winnable' box on the board data Box = Box { _posX :: Int, _posY :: Int} deriving (Show, Ord, Eq) -- | Board information at a point in the game data BoardCurrentState = BoardCurrentState { _boardCurrentStateWidthInDots :: Int, _boardCurrentStateHeightInDots :: Int, _boardCurrentStateMoves :: Set.Set Move, _boardCurrentStateBoxes :: Map.Map Box Player, -- | Maps a box to the winner of that box _boardCurrentStatePlayer :: Player } deriving Eq emptyBoardCurrentState :: Int -> Int -> BoardCurrentState emptyBoardCurrentState w h = BoardCurrentState w h Set.empty Map.empty Player1 instance Show BoardCurrentState where show (BoardCurrentState w h ms bs _) = let isDot x y = mod x 2 == 0 && mod y 2 == 0 in let _lines = Map.fromList $ Prelude.map (lineCoordinate &&& lineChar) (Set.toList ms) in let _wins = Map.mapKeys boxCoordinate. Map.map playerDigit $ bs in concatMap (\y -> Prelude.map (\x -> if isDot x y then '.' else fromMaybe3 ' ' (marking x y) (Map.lookup (x, y) _lines) (Map.lookup (x, y) _wins) ) [1..displayWidth] ++ "\n") [1..displayHeight] where marking 1 y = if mod y 2 == 0 then Just (chr (ord 'a' + quot y 2 - 1)) else Nothing marking x 1 = if mod x 2 == 0 then Just (chr (ord 'a' + quot x 2 - 1)) else Nothing marking _ _ = Nothing displayWidth = w * 2 displayHeight = h * 2 playerDigit Player1 = '1' playerDigit Player2 = '2' boxCoordinate (Box x y) = (x * 2 + 1, y * 2 + 1) lineCoordinate (Move Horizontal x y) = (x * 2 + 1, y * 2) lineCoordinate (Move Vertical x y) = (x * 2, y * 2 + 1) lineChar (Move Horizontal _ _) = '-' lineChar (Move Vertical _ _) = '|' fromMaybe2 def m1 = fromMaybe (fromMaybe def m1) fromMaybe3 def m1 = fromMaybe2 (fromMaybe def m1)
mcapodici/dotsandboxes
src/Data/DotsAndBoxes/Types.hs
gpl-3.0
2,612
0
23
651
881
473
408
49
1
<?xml version='1.0' encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0"> <title>SeaDAS Help</title> <maps> <homeID>top</homeID> <mapref location="map.xml"/> </maps> <view mergetype="javax.help.UniteAppendMerge"> <name>TOC</name> <label>Contents</label> <type>javax.help.TOCView</type> <data>toc.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine">JavaHelpSearch</data> </view> </helpset>
seadas/beam
beam-gpf/src/main/resources/doc/help/gpf.hs
gpl-3.0
767
54
44
164
281
142
139
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Main (main) where -------------------------------------------------------------------------------- import Options.Applicative ((<**>)) #if (__GLASGOW_HASKELL__ < 710) import Control.Applicative ((<$>), (<*>), pure) import Data.Monoid (mconcat, mempty) #endif -------------------------------------------------------------------------------- import qualified Options.Applicative as Optparse -------------------------------------------------------------------------------- import qualified Enqueue import qualified MusicBrainz.Messaging as Messaging -------------------------------------------------------------------------------- main :: IO () main = Optparse.execParser parser >>= Enqueue.run where parser = Optparse.info (Enqueue.Options <$> Optparse.subparser (mconcat commands) <*> Messaging.rabbitOptparse <**> Optparse.helper) mempty commands = [ Optparse.command "retry" $ Optparse.info (Enqueue.Retry <$> Optparse.subparser (mconcat retryCommand) <**> Optparse.helper) (Optparse.progDesc "Retry sending failed or unroutable emails") ] retryCommand = [ Optparse.command "unroutable" $ Optparse.info (pure [Enqueue.Unroutable] <**> Optparse.helper) (Optparse.progDesc "Retry all unroutable emails") , Optparse.command "invalid" $ Optparse.info (pure [Enqueue.Invalid] <**> Optparse.helper) (Optparse.progDesc "Retry all invalid emails") , Optparse.command "everything" $ Optparse.info (pure [Enqueue.Invalid, Enqueue.Unroutable] <**> Optparse.helper) (Optparse.progDesc "Retry all invalid or unroutable emails") ]
metabrainz/musicbrainz-email
enqueue/Main.hs
gpl-3.0
2,063
0
15
597
355
197
158
32
1
module Titim.Game where import Titim.Grid import Data.Set (Set) import qualified Data.Set as Set -- Data structure that represents the entire -- game being played. data Game = Game { getGameScore :: Int , getGameGrid :: Grid , getGameWords :: Set String , getGameUsedWords :: Set String } countUsedWords :: Game -> Int countUsedWords = Set.size . getGameUsedWords countWords :: Game -> Int countWords = Set.size . getGameWords instance Show Game where show (Game score grid _ _) = let (rs, cs) = getGridSize grid in concat ["Score: ", show score , " | ", show rs, "x", show cs , "\n\n" , show grid ] -- Represents a word validation error for the game. data ValidationError = AlreadyUsed | NotAWord deriving (Eq) -- Generates a game with the given dictionary and -- size of the grid. makeGame :: FilePath -> (Int, Int) -> IO Game makeGame dict size = do dictionary <- readFile dict let wordz = Set.fromList . lines $ dictionary let usedWords = Set.empty return $ Game 0 (makeGrid size) wordz usedWords -- Checks if there are more debris than houses. isGameOver :: Game -> Bool isGameOver (Game _ grid _ _) = countEntity Debris grid > countEntity House grid -- Hits the game with the given word, updating the -- corresponding sets and the grid itself. hitGame :: String -> Game -> Game hitGame [] game = game hitGame word (Game score grid ws uws) = let (s, grid') = hitGrid word grid score' = score + s ws' = Set.delete word ws uws' = Set.insert word uws in Game score' grid' ws' uws' -- Updating a game just forwards the update to -- the grid. updateGame :: Game -> IO Game updateGame (Game score grid ws uws) = do grid' <- updateGrid grid return $ Game score grid' ws uws -- Checks if a word can be used and if it can't -- it returns a proper error message. validateWord :: String -> Game -> Either ValidationError String validateWord [] _ = Right [] validateWord word (Game _ _ ws uws) = case (Set.member word ws, Set.member word uws) of (True, _) -> Right word (False, True) -> Left AlreadyUsed (False, False) -> Left NotAWord
Jefffrey/Titim
src/Titim/Game.hs
gpl-3.0
2,299
0
12
639
658
344
314
51
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -- | -- Module : Network.Google.Auth -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : provisional -- Portability : non-portable (GHC extensions) -- -- Explicitly specify your Google credentials, or retrieve them -- from the underlying OS. module Network.Google.Auth ( -- * Credentials Credentials (..) -- ** Application Default Credentials , getApplicationDefault , fromWellKnownPath , fromFilePath , saveAuthorizedUserToWellKnownPath , saveAuthorizedUser -- ** Installed Application Credentials , installedApplication , formURL -- ** Authorizing Requests , authorize -- ** Thread-safe Storage , Store , initStore , retrieveAuthFromStore , Auth (..) , authToAuthorizedUser , exchange , refresh -- ** Default Constants , checkGCEVar , cloudSDKConfigDir , defaultCredentialsFile -- ** Handling Errors , AsAuthError (..) , AuthError (..) -- * OAuth Types , OAuthClient (..) , OAuthToken (..) , OAuthCode (..) , OAuthScope (..) -- * Re-exported Types , AccessToken (..) , RefreshToken (..) , Secret (..) , ServiceId (..) , ClientId (..) -- * Re-exported Modules , module Network.Google.Auth.Scope ) where import Control.Concurrent import Control.Monad.Catch (MonadCatch) import Control.Monad.IO.Class (MonadIO (..)) import Data.Time (getCurrentTime) import GHC.TypeLits (Symbol) import Network.Google.Auth.ApplicationDefault import Network.Google.Auth.InstalledApplication import Network.Google.Auth.Scope import Network.Google.Auth.ServiceAccount import Network.Google.Compute.Metadata (checkGCEVar) import Network.Google.Internal.Auth import Network.Google.Internal.Logger (Logger) import Network.Google.Prelude import Network.HTTP.Conduit (Manager) import qualified Network.HTTP.Conduit as Client import Network.HTTP.Types (hAuthorization) -- | 'authToAuthorizedUser' converts 'Auth' into an 'AuthorizedUser' -- by returning 'Right' if there is a 'FromClient'-constructed -- Credentials and a refreshed token; otherwise, returning -- 'Left' with error message. authToAuthorizedUser :: AllowScopes s => Auth s -> Either Text AuthorizedUser authToAuthorizedUser a = AuthorizedUser <$> (_clientId <$> getClient) <*> maybe (Left "no refresh token") Right (_tokenRefresh (_token a)) <*> (_clientSecret <$> getClient) where getClient = case _credentials a of FromClient c _ -> Right c _ -> Left "not FromClient" -- | An 'OAuthToken' that can potentially be expired, with the original -- credentials that can be used to perform a refresh. data Auth (s :: [Symbol]) = Auth { _credentials :: !(Credentials s) , _token :: !(OAuthToken s) } -- | Check if the given token is still valid, ie. younger than the projected -- expiry time. -- -- This deliberately makes no external calls due to the absolute construction of -- the '_tokenExpiry' field, unlike the -- <https://developers.google.com/accounts/docs/OAuth2Login#validatingtoken documented> -- validation method. validate :: MonadIO m => Auth s -> m Bool validate a = (< _tokenExpiry (_token a)) <$> liftIO getCurrentTime -- | Data store which ensures thread-safe access of credentials. newtype Store (s :: [Symbol]) = Store (MVar (Auth s)) -- | Construct storage containing the credentials which have not yet been -- exchanged or refreshed. initStore :: (MonadIO m, MonadCatch m, AllowScopes s) => Credentials s -> Logger -> Manager -> m (Store s) initStore c l m = exchange c l m >>= fmap Store . liftIO . newMVar -- | Retrieve auth from storage retrieveAuthFromStore :: (MonadIO m, MonadCatch m, AllowScopes s) => Store s -> m (Auth s) retrieveAuthFromStore (Store s) = liftIO (readMVar s) -- | Concurrently read the current token, and if expired, then -- safely perform a single serial refresh. getToken :: (MonadIO m, MonadCatch m, AllowScopes s) => Store s -> Logger -> Manager -> m (OAuthToken s) getToken (Store s) l m = do x <- liftIO (readMVar s) mx <- validate x if mx then pure (_token x) else liftIO . modifyMVar s $ \y -> do my <- validate y if my then pure (y, _token y) else do z <- refresh y l m pure (z, _token z) -- | Perform the initial credentials exchange to obtain a valid 'OAuthToken' -- suitable for authorizing requests. exchange :: forall m s. (MonadIO m, MonadCatch m, AllowScopes s) => Credentials s -> Logger -> Manager -> m (Auth s) exchange c l = fmap (Auth c) . action l where action = case c of FromMetadata s -> metadataToken s FromAccount a -> serviceAccountToken a (Proxy :: Proxy s) FromClient x n -> exchangeCode x n FromUser u -> authorizedUserToken u Nothing -- | Refresh an existing 'OAuthToken'. refresh :: forall m s. (MonadIO m, MonadCatch m, AllowScopes s) => Auth s -> Logger -> Manager -> m (Auth s) refresh (Auth c t) l = fmap (Auth c) . action l where action = case c of FromMetadata s -> metadataToken s FromAccount a -> serviceAccountToken a (Proxy :: Proxy s) FromClient x _ -> refreshToken x t FromUser u -> authorizedUserToken u (_tokenRefresh t) -- | Apply the (by way of possible token refresh) a bearer token to the -- authentication header of a request. authorize :: (MonadIO m, MonadCatch m, AllowScopes s) => Client.Request -> Store s -> Logger -> Manager -> m Client.Request authorize rq s l m = bearer <$> getToken s l m where bearer t = rq { Client.requestHeaders = ( hAuthorization , "Bearer " <> toHeader (_tokenAccess t) ) : Client.requestHeaders rq }
rueshyna/gogol
gogol/src/Network/Google/Auth.hs
mpl-2.0
6,845
0
17
2,185
1,396
771
625
132
4
{-# 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.CloudResourceManager.Projects.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) -- -- Request that a new project be created. The result is an \`Operation\` -- which can be used to track the creation process. This process usually -- takes a few seconds, but can sometimes take much longer. The tracking -- \`Operation\` is automatically deleted after a few hours, so there is no -- need to call \`DeleteOperation\`. -- -- /See:/ <https://cloud.google.com/resource-manager Cloud Resource Manager API Reference> for @cloudresourcemanager.projects.create@. module Network.Google.Resource.CloudResourceManager.Projects.Create ( -- * REST Resource ProjectsCreateResource -- * Creating a Request , projectsCreate , ProjectsCreate -- * Request Lenses , pcXgafv , pcUploadProtocol , pcAccessToken , pcUploadType , pcPayload , pcCallback ) where import Network.Google.Prelude import Network.Google.ResourceManager.Types -- | A resource alias for @cloudresourcemanager.projects.create@ method which the -- 'ProjectsCreate' request conforms to. type ProjectsCreateResource = "v3" :> "projects" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Project :> Post '[JSON] Operation -- | Request that a new project be created. The result is an \`Operation\` -- which can be used to track the creation process. This process usually -- takes a few seconds, but can sometimes take much longer. The tracking -- \`Operation\` is automatically deleted after a few hours, so there is no -- need to call \`DeleteOperation\`. -- -- /See:/ 'projectsCreate' smart constructor. data ProjectsCreate = ProjectsCreate' { _pcXgafv :: !(Maybe Xgafv) , _pcUploadProtocol :: !(Maybe Text) , _pcAccessToken :: !(Maybe Text) , _pcUploadType :: !(Maybe Text) , _pcPayload :: !Project , _pcCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcXgafv' -- -- * 'pcUploadProtocol' -- -- * 'pcAccessToken' -- -- * 'pcUploadType' -- -- * 'pcPayload' -- -- * 'pcCallback' projectsCreate :: Project -- ^ 'pcPayload' -> ProjectsCreate projectsCreate pPcPayload_ = ProjectsCreate' { _pcXgafv = Nothing , _pcUploadProtocol = Nothing , _pcAccessToken = Nothing , _pcUploadType = Nothing , _pcPayload = pPcPayload_ , _pcCallback = Nothing } -- | V1 error format. pcXgafv :: Lens' ProjectsCreate (Maybe Xgafv) pcXgafv = lens _pcXgafv (\ s a -> s{_pcXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pcUploadProtocol :: Lens' ProjectsCreate (Maybe Text) pcUploadProtocol = lens _pcUploadProtocol (\ s a -> s{_pcUploadProtocol = a}) -- | OAuth access token. pcAccessToken :: Lens' ProjectsCreate (Maybe Text) pcAccessToken = lens _pcAccessToken (\ s a -> s{_pcAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pcUploadType :: Lens' ProjectsCreate (Maybe Text) pcUploadType = lens _pcUploadType (\ s a -> s{_pcUploadType = a}) -- | Multipart request metadata. pcPayload :: Lens' ProjectsCreate Project pcPayload = lens _pcPayload (\ s a -> s{_pcPayload = a}) -- | JSONP pcCallback :: Lens' ProjectsCreate (Maybe Text) pcCallback = lens _pcCallback (\ s a -> s{_pcCallback = a}) instance GoogleRequest ProjectsCreate where type Rs ProjectsCreate = Operation type Scopes ProjectsCreate = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsCreate'{..} = go _pcXgafv _pcUploadProtocol _pcAccessToken _pcUploadType _pcCallback (Just AltJSON) _pcPayload resourceManagerService where go = buildClient (Proxy :: Proxy ProjectsCreateResource) mempty
brendanhay/gogol
gogol-resourcemanager/gen/Network/Google/Resource/CloudResourceManager/Projects/Create.hs
mpl-2.0
4,975
0
16
1,119
711
418
293
100
1
--Zaoqilc --Copyright (C) 2017 Zaoqi --This program is free software: you can redistribute it and/or modify --it under the terms of the GNU Affero General Public License as published --by the Free Software Foundation, either version 3 of the License, or --(at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --GNU Affero General Public License for more details. --You should have received a copy of the GNU Affero General Public License --along with this program. If not, see <http://www.gnu.org/licenses/>. module Data.Nat where import Control.Exception data Nat = Z | S Nat deriving (Eq, Ord) instance Enum Nat where succ = S pred (S x) = x pred _ = throw Underflow toEnum 0 = Z toEnum x | x < 0 = throw Underflow | otherwise = S . toEnum $ pred x fromEnum Z = 0 fromEnum (S x) = succ $ fromEnum x enumFrom x = x : enumFrom (S x) instance Num Nat where Z + x = x (S x) + y = S $ x + y Z * _ = Z (S x) * y = y + (x * y) abs = id signum Z = Z signum _ = S Z fromInteger 0 = Z fromInteger x | x < 0 = throw Underflow | otherwise = S . fromInteger $ pred x x - Z = x (S x) - (S y) = x - y _ - _ = throw Underflow negate Z = Z negate _ = throw Underflow instance Real Nat where toRational = toRational . toInteger instance Integral Nat where quot x y = fromInteger $ quot (toInteger x) (toInteger y) rem x y = fromInteger $ rem (toInteger x) (toInteger y) div x y = fromInteger $ div (toInteger x) (toInteger y) mod x y = fromInteger $ mod (toInteger x) (toInteger y) quotRem x y = let (x, y) = quotRem (toInteger x) (toInteger y) in (fromInteger x, fromInteger y) divMod x y = let (x, y) = divMod (toInteger x) (toInteger y) in (fromInteger x, fromInteger y) toInteger Z = 0 toInteger (S x) = succ $ toInteger x
zaoqi/zaoqilc
featuring/Data/Nat.hs
agpl-3.0
2,062
0
12
557
702
347
355
40
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {- | Module : $Header$ Description : Types for tests. Copyright : (c) plaimi 2014 License : AGPL-3 Maintainer : tempuhs@plaimi.net -} module Tempuhs.Spoc.Type where import Data.String ( IsString, ) import Data.Stringable ( Stringable, ) import Network.HTTP.Types.QueryLike ( QueryKeyLike, QueryValueLike, toQueryKey, ) type Specified = String type AttributePair = (AttributeKey, AttributeValue) newtype AttributeKey = MkAttrKey String deriving (IsString, Stringable) newtype AttributeValue = MkAttrVal String deriving (IsString, QueryValueLike, Stringable) instance QueryKeyLike AttributeKey where toQueryKey (MkAttrKey s) = toQueryKey $ s ++ "_"
plaimi/tempuhs-server
test/Tempuhs/Spoc/Type.hs
agpl-3.0
796
0
8
190
140
85
55
21
0
import Faceted import Control.Monad(liftM, join) import System.IO(IOMode(WriteMode)) prod = liftM join . swap rep :: Monad m => m a -> Int -> m a rep x 1 = x rep x n = do x rep x (n-1) ------------------------------------------------------------------------ -- Experiment 1: Faceted monad -- Quadratic complexity (worse than expected) x0 = makeFacets "k" 'a' 'b' x1 = rep x0 (ceiling $ n*3475) x2 = rep x1 (ceiling $ n*3475) main_x1 = flip runFIO [] $ do h <- openFileF [] "output.txt" WriteMode hPutCharF h x2 hCloseF h main_x2 = flip runFIO [] $ do prod $ do c <- x2 return $ do h <- openFileF [] "output.txt" WriteMode hPutCharF h (makePublic c) hCloseF h return $ makePublic () ------------------------------------------------------------------------ -- Experiment 2: IO monad -- Quadratic complexity (unfortunate, but expected) y0 = return () y1 = rep y0 (ceiling $ n*6750) y2 = rep y1 (ceiling $ n*6750) main_y = do y2 print "foo" ------------------------------------------------------------------------ -- Experiment 3: Totally pure code -- Linear complexity (as expected) pure_rep m = f 0 where f acc 0 = acc f acc n = (f $! (m + acc)) $! (n-1) z0 = 1 z1 = pure_rep z0 (ceiling $ n*4097000) z2 = pure_rep z1 (ceiling $ n*4097000) main_z = do print z2 ------------------------------------------------------------------------ -- Experiment 4: Maybe monad -- Linear complexity (as expected) m0 = Just "foo" m1 = rep m0 (ceiling $ n*13808000) m2 = rep m1 (ceiling $ n*13808000) main_m = do print m2 ------------------------------------------------------------------------ -- Main: Run all the experiments n = 2 main = do main_x1
tommy-schmitz/haskell-faceted
code/main.hs
apache-2.0
1,727
18
16
355
620
286
334
47
2
{- 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. -} program = drawingOf(diamond) diamonds = rotated(rectangle(2, 2), 45)
pranjaltale16/codeworld
codeworld-compiler/test/testcase/test_nesting/source.hs
apache-2.0
679
1
8
123
39
20
19
2
1
newtype StateT s m a = StateT { runStateT :: (s -> m (a,s)) } instance (Monad m) => Functor (StateT s m) where -- fmap :: (a->b) -> State s m a -> State s m b fmap f (StateT ms) = StateT $ \s -> do (a,s') <- ms s return (f a, s') -- ms :: s -> m (a,s) instance (Monad m) => Applicative (StateT s m) where pure = return (StateT mf) <*> (StateT mx) = StateT $ \s -> do (f,s') <- mf s (x,s'') <- mx s' return (f x, s'') instance (Monad m) => Monad (StateT s m) where -- return :: a -> StateT s m a return x = StateT $ \s -> return (x,s) -- (>>=) :: StateT s m a -> (a -> State s m b) -> State s m b (StateT mx) >>= f = StateT $ \s -> do (x,s') <- mx s (runStateT $ f x) s'
egaburov/funstuff
Haskell/monads/mt02.hs
apache-2.0
943
0
13
436
336
176
160
18
0
-- {-# LANGUAGE PatternSynonyms #-} -- {-# LANGUAGE ViewPatterns #-} -- -- data Foo a = Foo a a -- -- pattern A a1 a2 = Foo a1 a2 -- pattern B a1 a2 = A a1 a2 {-# UndecidableSuperClasses #-} {-# AllowAmbiguousTypes #-} {-# TypeFamilies #-} class A (T a) => A a where type T a
mikeizbicki/homoiconic
old/Bug1.hs
bsd-3-clause
282
2
6
64
29
19
10
-1
-1
------------------------------------------------------------------------------ -- File: Handler/Search.hs -- Creation Date: Dec 16 2012 [22:12:57] -- Last Modified: Dec 27 2012 [15:27:48] -- Created By: Samuli Thomasson [SimSaladin] samuli.thomassonAtpaivola.fi ------------------------------------------------------------------------------ module Handler.Search where import Import -- import Handler.Media -- import Handler.Blog ( import qualified Text.Search.Sphinx as S import qualified Text.Search.Sphinx as ST data Result = RBlogPost { rId :: BlogpostId } | RDirectory | RFile -- | run the search and return results in a page. getSearchR :: Handler Html getSearchR = do ((formRes, searchWidget),_) <- runFormGet searchForm searchResults <- case formRes of FormSuccess qstring -> getResults qstring _ -> return [] defaultLayout $ [whamlet| whoops... (results here?) |] -- | Query sphinx and return results. getResults :: Text -> Handler [Result] getResults qstring = do sphinxRes' <- liftIO $ S.query config "searcher" qstring case sphinxRes' of ST.Ok sphinxRes -> do let dids = map (Key . PersistInt64 . ST.documentId) $ ST.matches sphinxRes fmap catMaybes $ runDB $ forM dids $ \docid -> do mdoc <- get docid case mdoc of Nothing -> return Nothing Just doc -> liftIO $ Just <$> getResult docid doc qstring _ -> error $ show sphinxRes' where config = S.defaultConfig { S.port = 9312 , S.mode = ST.Any } getResult :: *
SimSaladin/rnfssp
Handler/Search.hs
bsd-3-clause
1,581
0
20
362
356
189
167
-1
-1
module Yesod.Admin.Crud (Admin, getAdmin, mkYesodAdmin) where import Yesod.Admin.Crud.Handlers () import Yesod.Admin.Crud.TH (mkYesodAdmin) import Yesod.Admin.Crud.Type (Admin(..)) getAdmin :: x -> Admin getAdmin = const Admin
yairchu/yesod-admin-crud
Yesod/Admin/Crud.hs
bsd-3-clause
229
0
6
26
73
47
26
6
1
{-# LANGUAGE MagicHash, DeriveFunctor, DeriveFoldable, DeriveTraversable, ImplicitParams, GeneralizedNewtypeDeriving #-} module Data.TrieMap.Sized where import Data.TrieMap.TrieKey.Subset import Data.Foldable import Data.Traversable import Data.Functor.Immoral import GHC.Exts class Sized a where getSize# :: a -> Int# data Assoc k a = Assoc {getK :: k, getValue :: a} deriving (Eq, Show, Functor, Foldable, Traversable) newtype Elem a = Elem {getElem :: a} deriving (Functor, Foldable, Traversable, ImmoralMap a) instance Subset Elem where Elem a <=? Elem b = ?le a b instance Subset (Assoc k) where Assoc _ a <=? Assoc _ b = ?le a b instance Sized (Elem a) where getSize# _ = 1# instance Sized (Assoc k a) where getSize# _ = 1# instance Sized a => Sized (Maybe a) where getSize# (Just a) = getSize# a getSize# _ = 0# {-# INLINE getSize #-} getSize :: Sized a => a -> Int getSize a = I# (getSize# a) {-# INLINE unbox #-} unbox :: Int -> Int# unbox (I# i#) = i#
lowasser/TrieMap
Data/TrieMap/Sized.hs
bsd-3-clause
987
0
8
186
355
187
168
28
1
{-# LANGUAGE OverloadedStrings #-} module Convert.LDAG.JSON (convert) where import Control.Lens ((^.), (^..), (<.), _2, asIndex, at, filtered, itraversed, to) import Convert.Misc.String (NodeLabel, showBools, showNodeLabel) import Data.Aeson (Value, (.=), object, toJSON) import Data.Aeson.Encode (encodeToTextBuilder) import Data.Aeson.Types (Pair) import Data.Function (on) import Data.LDAG import Data.List (groupBy, nub) import Data.Maybe (catMaybes) import Data.String (fromString) import Data.Text.Lazy (Text) import Data.Text.Lazy.Builder (toLazyText) import Data.Universe.Class (Finite(universeF)) import qualified Data.IntMap as IM import qualified Data.Map as M -- | (!) assumes there is at least one layer convert :: LDAG NodeLabel Bool -> [String] -> Text convert ldag grouping = toLazyText . encodeToTextBuilder $ ldagGroupingToValue ldag grouping ldagGroupingToValue ldag grouping = object [ "steps" .= stepsToValue (ldagGroupingToSteps ldag grouping) , "outputs" .= [outputs ldag] ] ldagGroupingToSteps :: (Eq pos, Finite e, Ord e) => LDAG n e -> [pos] -> [(pos, [([e], [[Bool]])])] ldagGroupingToSteps ldag grouping = findAllPaths . map (\pairs@((_, label):_) -> (label, map fst pairs)) . groupBy ((==) `on` snd) $ zip (ldag ^.. allLayers) (cycle grouping) -- (!) assumes each grouping has at least one layer findAllPaths ((label, layers):groups@((_, layer':_):_)) = (label, findPathsTo (nodeIDs layer') layers) : findAllPaths groups findAllPaths [(label, layers@(_:_:_))] = [(label, findPathsTo (nodeIDs (last layers)) (init layers))] findAllPaths _ = [] findPathsTo :: (Finite e, Ord e) => [NodeID] -> [Layer n e] -> [([e], [[Bool]])] findPathsTo endNodeIDs layers = filter nonZero [ (path, [ [ maybeEndNodeID == Just endNodeID | endNodeID <- endNodeIDs ] | startNodeID <- nodeIDs (head layers) , let maybeEndNodeID = transition startNodeID path layers ] ) | path <- mapM (const universeF) layers ] where nonZero = or . map or . snd nodeIDs :: Layer n e -> [NodeID] nodeIDs layer = layer ^.. (allNodes <. dead . filtered not) . asIndex transition :: Ord e => NodeID -> [e] -> [Layer n e] -> Maybe NodeID transition nodeID [] [] = Just nodeID transition nodeID (e:es) (layer:layers) = do node <- layer ^. at nodeID children <- node ^. outgoing transition (children e) es layers transition nodeID _ _ = Nothing stepsToValue :: [(String, [([Bool], [[Bool]])])] -> Value stepToValue :: (String, [([Bool], [[Bool]])]) -> Value stepsToValue = toJSON . map stepToValue stepToValue (position, mappings) = object $ "position" .= position : map mappingToPair mappings mappingToPair :: ([Bool], [[Bool]]) -> Pair mappingToPair (label, matrix) = k .= v where k = fromString (showBools label) v = map (map fromEnum) matrix outputs :: LDAG NodeLabel e -> [String] outputs ldag = ldag ^.. layers . to IM.findMax . _2 . allNodes . filtered (not . (^. dead)) . nodeLabel . to showNodeLabel
GaloisInc/cryfsm
Convert/LDAG/JSON.hs
bsd-3-clause
3,029
0
14
564
1,221
681
540
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} module Types.API.Requests where import ClassyPrelude
JoeMShanahan/blizzard-haskell-api
src/Types/API/Requests.hs
bsd-3-clause
127
0
3
17
12
9
3
4
0
{-# LANGUAGE MagicHash, TypeFamilies, MultiParamTypeClasses, FlexibleInstances, BangPatterns, CPP, ViewPatterns, TypeSynonymInstances #-} {-# OPTIONS -funbox-strict-fields #-} module Data.TrieMap.RadixTrie.Label where import Control.Monad.Unpack import Control.Monad.Trans.Reader import Data.TrieMap.TrieKey import Data.TrieMap.RadixTrie.Slice import Data.TrieMap.WordMap.Base hiding (Root, Path) import Data.TrieMap.WordMap.Buildable import Data.TrieMap.WordMap () import Data.Word import Data.Vector.Generic hiding (empty) import qualified Data.Vector as V import qualified Data.Vector.Primitive as P import Prelude hiding (length) #define V(ty) (ty (V.Vector) (k)) #define U(ty) (ty (P.Vector) Word) type EdgeLoc v k = Zipper (Edge v k) class (Unpackable (v k), Vector v k, TrieKey k) => Label v k where data Edge v k :: * -> * data Path v k :: * -> * data Stack v k :: * -> * edge :: Sized a => v k -> Maybe a -> Branch v k a -> Edge v k a edge' :: Int -> v k -> Maybe a -> Branch v k a -> Edge v k a root :: Path v k a deep :: Path v k a -> v k -> Maybe a -> BHole v k a -> Path v k a loc :: v k -> Branch v k a -> Path v k a -> EdgeLoc v k a stack :: v k -> Maybe a -> Maybe (DAMStack k (Edge v k a)) -> Maybe (k, Stack v k a) -> Stack v k a eView :: Edge v k a -> EView v k a pView :: Path v k a -> PView v k a locView :: EdgeLoc v k a -> LocView v k a sView :: Stack v k a -> StackView v k a type BHole v k a = Hole k (Edge v k a) type Branch v k a = TrieMap k (Edge v k a) data EView v k a = Edge Int (v k) (Maybe a) (Branch v k a) data LocView v k a = Loc !( v k) (Branch v k a) (Path v k a) data PView v k a = Root | Deep (Path v k a) (v k) (Maybe a) (BHole v k a) data StackView v k a = Stack (v k) (Maybe a) (Maybe (DAMStack k (Edge v k a))) (Maybe (k, Stack v k a)) type MEdge v k a = Maybe (Edge v k a) instance Sized (EView v k a) where getSize# (Edge sz _ _ _) = unbox sz instance Label v k => Sized (Edge v k a) where {-# SPECIALIZE instance TrieKey k => Sized (V(Edge) a) #-} {-# SPECIALIZE instance Sized (U(Edge) a) #-} getSize# e = getSize# (eView e) data instance Zipper (Edge V.Vector k) a = VLoc !(V()) (V(Branch) a) (V(Path) a) instance TrieKey k => Label V.Vector k where data Edge V.Vector k a = VEdge !Int !(V()) (V(Branch) a) | VEdgeX !Int !(V()) a (V(Branch) a) data Path V.Vector k a = VRoot | VDeep (V(Path) a) !(V()) (V(BHole) a) | VDeepX (V(Path) a) !(V()) a (V(BHole) a) data Stack V.Vector k a = VStackAZ !(V()) a (DAMStack k (V(Edge) a)) k (V(Stack) a) | VStackA !(V()) a k (V(Stack) a) | VStackZ !(V()) (DAMStack k (V(Edge) a)) k (V(Stack) a) | VTip !(V()) a {-# INLINE edge #-} edge !ks Nothing ts = VEdge (sizeM ts) ks ts edge !ks (Just a) ts = VEdgeX (sizeM ts + getSize a) ks a ts edge' s !ks Nothing ts = VEdge s ks ts edge' s !ks (Just a) ts = VEdgeX s ks a ts root = VRoot deep path !ks Nothing tHole = VDeep path ks tHole deep path !ks (Just a) tHole = VDeepX path ks a tHole loc = VLoc eView (VEdge s ks ts) = Edge s ks Nothing ts eView (VEdgeX s ks v ts) = Edge s ks (Just v) ts pView VRoot = Root pView (VDeep path ks tHole) = Deep path ks Nothing tHole pView (VDeepX path ks v tHole) = Deep path ks (Just v) tHole locView (VLoc ks ts path) = Loc ks ts path {-# INLINE stack #-} stack !ks (Just a) (Just z) (Just (k, stack)) = VStackAZ ks a z k stack stack !ks (Just a) Nothing (Just (k, stack)) = VStackA ks a k stack stack !ks Nothing (Just z) (Just (k, stack)) = VStackZ ks z k stack stack !ks (Just a) Nothing Nothing = VTip ks a stack _ _ _ _ = error "Error: bad stack" {-# INLINE sView #-} sView (VTip ks v) = Stack ks (Just v) Nothing Nothing sView (VStackAZ ks a z k stack) = Stack ks (Just a) (Just z) (Just (k, stack)) sView (VStackA ks a k stack) = Stack ks (Just a) Nothing (Just (k, stack)) sView (VStackZ ks z k stack) = Stack ks Nothing (Just z) (Just (k, stack)) instance TrieKey k => Unpackable (V(EdgeLoc) a) where newtype UnpackedReaderT (EdgeLoc V.Vector k a) m r = VLocRT {runVLocRT :: UnpackedReaderT (V.Vector k) (ReaderT (V(Branch) a) (ReaderT (V(Path) a) m)) r} runUnpackedReaderT func (VLoc ks ts path) = runVLocRT func `runUnpackedReaderT` ks `runReaderT` ts `runReaderT` path unpackedReaderT func = VLocRT $ unpackedReaderT $ \ ks -> ReaderT $ \ ts -> ReaderT $ \ path -> func (VLoc ks ts path) data instance Zipper (Edge P.Vector Word) a = SLoc !(U()) !(SNode (U(Edge) a)) (U(Path) a) instance Label P.Vector Word where data Edge P.Vector Word a = SEdge !(U()) !(SNode (U(Edge) a)) | SEdgeX !Int !(U()) a !(SNode (U(Edge) a)) data Path P.Vector Word a = SRoot | SDeep (U(Path) a) !(U()) !(WHole (U(Edge) a)) | SDeepX (U(Path) a) !(U()) a !(WHole (U(Edge) a)) data Stack P.Vector Word a = PStackAZ !(U()) a !(WordStack (U(Edge) a)) !Word (U(Stack) a) | PStackA !(U()) a !Word (U(Stack) a) | PStackZ !(U()) !(WordStack (U(Edge) a)) !Word (U(Stack) a) | PTip !(U()) a {-# INLINE stack #-} stack !ks a z stack = case (a, z, stack) of (Just a, Just z, Just (k, stack)) -> PStackAZ ks a z k stack (Just a, Nothing, Just (k, stack)) -> PStackA ks a k stack (Nothing, Just z, Just (k, stack)) -> PStackZ ks z k stack (Just a, Nothing, Nothing) -> PTip ks a _ -> error "Error: bad stack" {-# INLINE sView #-} sView (PStackAZ ks a z k stack) = Stack ks (Just a) (Just z) (Just (k, stack)) sView (PStackA ks a k stack) = Stack ks (Just a) Nothing (Just (k, stack)) sView (PStackZ ks z k stack) = Stack ks Nothing (Just z) (Just (k, stack)) sView (PTip ks a) = Stack ks (Just a) Nothing Nothing edge !ks Nothing ts = SEdge ks (getWordMap ts) edge !ks (Just v) ts = SEdgeX (getSize v + sizeM ts) ks v (getWordMap ts) edge' _ !ks Nothing ts = SEdge ks (getWordMap ts) edge' sz !ks (Just v) ts = SEdgeX sz ks v (getWordMap ts) root = SRoot deep path !ks Nothing tHole = SDeep path ks (getHole tHole) deep path !ks (Just v) tHole = SDeepX path ks v (getHole tHole) loc ks ts path = SLoc ks (getWordMap ts) path eView (SEdge ks ts) = Edge (getSize ts) ks Nothing (WordMap ts) eView (SEdgeX s ks v ts) = Edge s ks (Just v) (WordMap ts) pView SRoot = Root pView (SDeep path ks tHole) = Deep path ks Nothing (Hole tHole) pView (SDeepX path ks v tHole) = Deep path ks (Just v) (Hole tHole) locView (SLoc ks ts path) = Loc ks (WordMap ts) path instance Unpackable (U(EdgeLoc) a) where newtype UnpackedReaderT (U(EdgeLoc) a) m r = ULocRT {runULocRT :: UnpackedReaderT (U()) (UnpackedReaderT (SNode (U(Edge) a)) (ReaderT (U(Path) a) m)) r} runUnpackedReaderT func (SLoc ks ts path) = runULocRT func `runUnpackedReaderT` ks `runUnpackedReaderT` ts `runReaderT` path unpackedReaderT func = ULocRT $ unpackedReaderT $ \ ks -> unpackedReaderT $ \ ts -> ReaderT $ \ path -> func (SLoc ks ts path) {-# SPECIALIZE singletonEdge :: (TrieKey k, Sized a) => V() -> a -> V(Edge) a, Sized a => U() -> a -> U(Edge) a #-} singletonEdge :: (Label v k, Sized a) => v k -> a -> Edge v k a singletonEdge !ks a = edge' (getSize a) ks (Just a) empty {-# SPECIALIZE singleLoc :: TrieKey k => V() -> V(EdgeLoc) a, U() -> U(EdgeLoc) a #-} singleLoc :: Label v k => v k -> EdgeLoc v k a singleLoc ks = loc ks empty root {-# SPECIALIZE getSimpleEdge :: TrieKey k => V(Edge) a -> Simple a, U(Edge) a -> Simple a #-} getSimpleEdge :: Label v k => Edge v k a -> Simple a getSimpleEdge !(eView -> Edge _ _ v ts) | isNull ts = maybe Null Singleton v | otherwise = NonSimple {-# SPECIALIZE dropEdge :: TrieKey k => Int -> V(Edge) a -> V(Edge) a, Int -> U(Edge) a -> U(Edge) a #-} {-# SPECIALIZE unDropEdge :: TrieKey k => Int -> V(Edge) a -> V(Edge) a, Int -> U(Edge) a -> U(Edge) a #-} dropEdge, unDropEdge :: Label v k => Int -> Edge v k a -> Edge v k a dropEdge !n !(eView -> Edge sz# ks v ts) = edge' sz# (dropSlice n ks) v ts unDropEdge !n !(eView -> Edge sz# ks v ts) = edge' sz# (unDropSlice n ks) v ts {-# SPECIALIZE cEdge :: (TrieKey k, Sized a) => V() -> Maybe a -> V(Branch) a -> V(MEdge) a, Sized a => U() -> Maybe a -> U(Branch) a -> U(MEdge) a #-} cEdge :: (Label v k, Sized a) => v k -> Maybe a -> Branch v k a -> MEdge v k a cEdge !ks v ts = case v of Nothing -> case getSimpleM ts of Null -> Nothing Singleton e' -> Just (unDropEdge (length ks + 1) e') NonSimple -> Just (edge ks Nothing ts) _ -> Just (edge ks v ts) -- data StackView v k a z = Stack (v k) a (TrieMap Word (Hang a z)) data HangView a z = Branch !Int (Maybe a) (Maybe z) data Hang a z = H !Int z | HT !Int a z | T !Int a branch :: Int -> Maybe a -> Maybe z -> Hang a z branch !i Nothing (Just z) = H i z branch !i (Just a) Nothing = T i a branch !i (Just a) (Just z) = HT i a z branch _ _ _ = error "Error: bad branch" bView :: Hang a z -> HangView a z bView (H i z) = Branch i Nothing (Just z) bView (HT i a z) = Branch i (Just a) (Just z) bView (T i a) = Branch i (Just a) Nothing instance Sized (Hang a z) where getSize# _ = 1# {-# RULES "sView/stack" forall ks a z branch . sView (stack ks a z branch) = Stack ks a z branch #-}
lowasser/TrieMap
Data/TrieMap/RadixTrie/Label.hs
bsd-3-clause
9,257
22
16
2,240
4,494
2,269
2,225
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Test.Templates where import Test.Common import Test.Import spec :: Spec spec = describe "template API" $ do it "can create a template" $ withTestEnv $ do let idxTpl = IndexTemplate [IndexPattern "tweet-*"] (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) (toJSON TweetMapping) resp <- putTemplate idxTpl (TemplateName "tweet-tpl") liftIO $ validateStatus resp 200 it "can detect if a template exists" $ withTestEnv $ do exists <- templateExists (TemplateName "tweet-tpl") liftIO $ exists `shouldBe` True it "can delete a template" $ withTestEnv $ do resp <- deleteTemplate (TemplateName "tweet-tpl") liftIO $ validateStatus resp 200 it "can detect if a template doesn't exist" $ withTestEnv $ do exists <- templateExists (TemplateName "tweet-tpl") liftIO $ exists `shouldBe` False
bitemyapp/bloodhound
tests/Test/Templates.hs
bsd-3-clause
907
0
20
195
260
123
137
20
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module React.Flux.Mui.BottomNavigation.BottomNavigationItem where import Protolude import Data.Aeson import Data.Aeson.Casing import Data.String (String) import React.Flux import React.Flux.Mui.Util data BottomNavigationItem = BottomNavigationItem { } deriving (Generic, Show) instance ToJSON BottomNavigationItem where toJSON = genericToJSON $ aesonDrop (length ("BottomNavigationItem" :: String)) camelCase defBottomNavigationItem :: BottomNavigationItem defBottomNavigationItem = BottomNavigationItem {} bottomNavigationItem_ :: BottomNavigationItem -> [PropertyOrHandler handler] -> ReactElementM handler () bottomNavigationItem_ args props = foreign_ "BottomNavigationItem" (fromMaybe [] (toProps args) ++ props) mempty
pbogdan/react-flux-mui
react-flux-mui/src/React/Flux/Mui/BottomNavigation/BottomNavigationItem.hs
bsd-3-clause
823
1
10
109
180
102
78
23
1
module Network.XmlPush.Tls.Server ( TlsArgs(..) ) where import Data.X509 import Data.X509.CertificateStore import Network.PeyoTLS.Client import Text.XML.Pipe data TlsArgs = TlsArgs { getClientName :: XmlNode -> Maybe String, checkCertificate :: XmlNode -> Maybe (SignedCertificate -> Bool), cipherSuites :: [CipherSuite], certificateAuthorities :: Maybe CertificateStore, keyChains :: [(CertSecretKey, CertificateChain)] }
YoshikuniJujo/xml-push
src/Network/XmlPush/Tls/Server.hs
bsd-3-clause
433
16
12
55
131
79
52
12
0
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE AllowAmbiguousTypes #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Distributed.Process.ManagedProcess.Server.Priority -- Copyright : (c) Tim Watson 2012 - 2017 -- License : BSD3 (see the file LICENSE) -- -- Maintainer : Tim Watson <watson.timothy@gmail.com> -- Stability : experimental -- Portability : non-portable (requires concurrency) -- -- The Server Portion of the /Managed Process/ API, as presented by the -- 'GenProcess' monad. These functions are generally intended for internal -- use, but the API is relatively stable and therefore they have been re-exported -- here for general use. Note that if you modify a process' internal state -- (especially that of the internal priority queue) then you are responsible for -- any alteratoin that makes to the semantics of your processes behaviour. -- -- See "Control.Distributed.Process.ManagedProcess.Internal.GenProcess" ----------------------------------------------------------------------------- module Control.Distributed.Process.ManagedProcess.Server.Gen ( -- * Server actions reply , replyWith , noReply , continue , timeoutAfter , hibernate , stop , reject , rejectWith , become , haltNoReply , lift , Gen.recvLoop , Gen.precvLoop , Gen.currentTimeout , Gen.systemTimeout , Gen.drainTimeout , Gen.processState , Gen.processDefinition , Gen.processFilters , Gen.processUnhandledMsgPolicy , Gen.processQueue , Gen.gets , Gen.getAndModifyState , Gen.modifyState , Gen.setUserTimeout , Gen.setProcessState , GenProcess , Gen.peek , Gen.push , Gen.enqueue , Gen.dequeue , Gen.addUserTimer , Gen.removeUserTimer , Gen.eval , Gen.act , Gen.runAfter , Gen.evalAfter ) where import Control.Distributed.Process.Extras ( ExitReason ) import Control.Distributed.Process.Extras.Time ( TimeInterval , Delay ) import Control.Distributed.Process.ManagedProcess.Internal.Types ( lift , ProcessAction(..) , GenProcess , ProcessReply(..) , ProcessDefinition ) import qualified Control.Distributed.Process.ManagedProcess.Internal.GenProcess as Gen ( recvLoop , precvLoop , currentTimeout , systemTimeout , drainTimeout , processState , processDefinition , processFilters , processUnhandledMsgPolicy , processQueue , gets , getAndModifyState , modifyState , setUserTimeout , setProcessState , GenProcess , peek , push , enqueue , dequeue , addUserTimer , removeUserTimer , eval , act , runAfter , evalAfter ) import Control.Distributed.Process.ManagedProcess.Internal.GenProcess ( processState ) import qualified Control.Distributed.Process.ManagedProcess.Server as Server ( replyWith , continue ) import Control.Distributed.Process.Serializable (Serializable) -- | Reject the message we're currently handling. reject :: forall r s . String -> GenProcess s (ProcessReply r s) reject rs = processState >>= \st -> lift $ Server.continue st >>= return . ProcessReject rs -- | Reject the message we're currently handling, giving an explicit reason. rejectWith :: forall r m s . (Show r) => r -> GenProcess s (ProcessReply m s) rejectWith rs = reject (show rs) -- | Instructs the process to send a reply and continue running. reply :: forall r s . (Serializable r) => r -> GenProcess s (ProcessReply r s) reply r = processState >>= \s -> lift $ Server.continue s >>= Server.replyWith r -- | Instructs the process to send a reply /and/ evaluate the 'ProcessAction'. replyWith :: forall r s . (Serializable r) => r -> ProcessAction s -> GenProcess s (ProcessReply r s) replyWith r s = return $ ProcessReply r s -- | Instructs the process to skip sending a reply /and/ evaluate a 'ProcessAction' noReply :: (Serializable r) => ProcessAction s -> GenProcess s (ProcessReply r s) noReply = return . NoReply -- | Halt process execution during a call handler, without paying any attention -- to the expected return type. haltNoReply :: forall s r . Serializable r => ExitReason -> GenProcess s (ProcessReply r s) haltNoReply r = stop r >>= noReply -- | Instructs the process to continue running and receiving messages. continue :: GenProcess s (ProcessAction s) continue = processState >>= return . ProcessContinue -- | Instructs the process loop to wait for incoming messages until 'Delay' -- is exceeded. If no messages are handled during this period, the /timeout/ -- handler will be called. Note that this alters the process timeout permanently -- such that the given @Delay@ will remain in use until changed. -- -- Note that @timeoutAfter NoDelay@ will cause the timeout handler to execute -- immediately if no messages are present in the process' mailbox. -- timeoutAfter :: Delay -> GenProcess s (ProcessAction s) timeoutAfter d = processState >>= \s -> return $ ProcessTimeout d s -- | Instructs the process to /hibernate/ for the given 'TimeInterval'. Note -- that no messages will be removed from the mailbox until after hibernation has -- ceased. This is equivalent to calling @threadDelay@. -- hibernate :: TimeInterval -> GenProcess s (ProcessAction s) hibernate d = processState >>= \s -> return $ ProcessHibernate d s -- | The server loop will execute against the supplied 'ProcessDefinition', allowing -- the process to change its behaviour (in terms of message handlers, exit handling, -- termination, unhandled message policy, etc) become :: forall s . ProcessDefinition s -> GenProcess s (ProcessAction s) become def = processState >>= \st -> return $ ProcessBecome def st -- | Instructs the process to terminate, giving the supplied reason. If a valid -- 'shutdownHandler' is installed, it will be called with the 'ExitReason' -- returned from this call, along with the process state. stop :: ExitReason -> GenProcess s (ProcessAction s) stop r = return $ ProcessStop r
haskell-distributed/distributed-process-client-server
src/Control/Distributed/Process/ManagedProcess/Server/Gen.hs
bsd-3-clause
6,149
0
11
1,090
986
584
402
116
1
module Permutation where import qualified Data.Set as S type Proof = () trivial :: Proof trivial = () -- Not a sufficient condition for something to be a permutation, but we can work -- with this for now. {-@ predicate Permutation X Y = (listElts X = listElts Y) && (len X = len Y) @-} -- Should fail {-@ notPerm :: ([Int], [Int])<{\x y -> Permutation x y}> @-} notPerm :: ([Int], [Int]) notPerm = ([1,1], [1,2]) -- Should succeed {-@ goodPerm :: ([Int], [Int])<{\x y -> Permutation x y}> @-} goodPerm :: ([Int], [Int]) goodPerm = ([1, 2, 3, 4], [3, 4, 2, 1]) {-@ equalLengths :: xs:[a] -> ys:[a] -> { _:Proof | Permutation xs ys } -> { _:Proof | len xs = len ys } @-} equalLengths :: [a] -> [a] -> Proof -> Proof equalLengths _ _ _ = trivial {-@ commutative :: xs:[a] -> ys:[a] -> { _:Proof | Permutation xs ys } -> { _:Proof | Permutation ys xs } @-} commutative :: [a] -> [a] -> Proof -> Proof commutative _ _ _ = trivial -- Things to prove -- The lengths of permutations are equal: Done -- Permutation is commutative: Done -- [1,1] is not a permutation of [1,2]: Done (fails as expected) -- [1,2,3,4] is a permutation of [3,4,2,1]: Done
raymoo/lh-vfa-stuff
Permutation.hs
bsd-3-clause
1,185
0
7
265
208
133
75
13
1
module Eval ( eval ) where import AST (Nat) import qualified AST as A import Data.STRef import Control.Monad.ST -- | A chunk represents a piece of code that is either unevaluated or evaluated. -- Forcing a chunk evaluates the code it contains, if it hasn't already been -- evaluated, and updates all copies of the chunk with the evaluated value. data Chunk s = Eval (STRef s (Either (Repr s) (Repr s))) | AddIndex Nat (STRef s (Either (Chunk s) (Repr s))) | Subst Nat (STRef s (Either (Chunk s) (Repr s))) (Chunk s) -- | The internal representation of the untyped lambda calculus as used by the -- evaluator. It's basically the same as the AST, except that every branch in -- the tree is a potentially unevaluated chunk. data Repr s = Var String Nat | Lambda String (Chunk s) | Apply (Chunk s) (Chunk s) fromUneval :: Repr s -> ST s (Chunk s) fromUneval term = do ref <- newSTRef (Left term) return (Eval ref) fromEval :: Repr s -> ST s (Chunk s) fromEval term = do ref <- newSTRef (Right term) return (Eval ref) fromAddIndex :: Nat -> Chunk s -> ST s (Chunk s) fromAddIndex depth chunk = do ref <- newSTRef (Left chunk) return (AddIndex depth ref) fromSubst :: Nat -> Chunk s -> Chunk s -> ST s (Chunk s) fromSubst depth chunk x = do ref <- newSTRef (Left chunk) return (Subst depth ref x) force :: Chunk s -> ST s (Repr s) force (Eval ref) = do code <- readSTRef ref case code of Left term -> do term' <- eval' term writeSTRef ref (Right term') return term' Right term -> return term force (AddIndex depth ref) = do code <- readSTRef ref case code of Left chunk -> do term <- force chunk term' <- addIndex depth term writeSTRef ref (Right term') return term' Right term -> return term force (Subst depth ref x) = do code <- readSTRef ref case code of Left chunk -> do term <- force chunk chunk' <- subst depth term x term' <- force chunk' writeSTRef ref (Right term') return term' Right term -> return term -- | Increments all free variables in the second argument. The first argument -- gives the number of bound variables in the second argument. addIndex :: Nat -> Repr s -> ST s (Repr s) addIndex depth (Var var idx) = return $ if idx < depth then Var var idx else Var var (idx + 1) addIndex depth (Lambda var body) = Lambda var <$> (fromAddIndex (depth + 1) body) addIndex depth (Apply e1 e2) = Apply <$> (fromAddIndex depth e1) <*> (fromAddIndex depth e2) -- | Substitutes the third argument into the second argument. The first argument -- gives the number of bound variables in the second argument. subst :: Nat -> Repr s -> Chunk s -> ST s (Chunk s) subst depth v@(Var var idx) x = if idx < depth then fromEval v else if idx == depth then return x else fromEval (Var var (idx - 1)) subst depth (Lambda var body) x = do x' <- fromAddIndex 0 x l <- Lambda var <$> (fromSubst (depth + 1) body x') fromUneval l subst depth (Apply e1 e2) x = do ap <- Apply <$> (fromSubst depth e1 x) <*> (fromSubst depth e2 x) fromUneval ap -- | Evaluates a term. This basically just performs substitutions on all lambda -- applications. eval' :: Repr s -> ST s (Repr s) eval' ap@(Apply fst snd) = do fst' <- force fst case fst' of Lambda _ body -> do chunk <- fromSubst 0 body snd force chunk _ -> return ap eval' term = return term fromAST :: A.Expr -> ST s (Repr s) fromAST (A.Var var idx) = return (Var var idx) fromAST (A.Lambda var body) = do body' <- fromAST body Lambda var <$> (fromUneval body') fromAST (A.Apply e1 e2) = do e1' <- fromAST e1 e2' <- fromAST e2 Apply <$> (fromUneval e1') <*> (fromUneval e2') toAST :: Repr s -> ST s A.Expr toAST (Var var idx) = return (A.Var var idx) toAST (Lambda var body) = do body' <- force body A.Lambda var <$> (toAST body') toAST (Apply e1 e2) = do e1' <- force e1 e2' <- force e2 A.Apply <$> (toAST e1') <*> (toAST e2') -- | Evaluates an expression to its normal form, if possible. eval :: A.Expr -> A.Expr eval term = runST $ do term' <- fromAST term term'' <- eval' term' toAST term''
lambda-11235/lambda-calc
src/Eval.hs
bsd-3-clause
4,476
0
14
1,314
1,646
786
860
100
4
{-# LANGUAGE CPP #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} #ifdef __GHCJS__ {-# LANGUAGE JavaScriptFFI #-} #endif module Foreign.JavaScript.TH ( module Foreign.JavaScript.TH , Safety (..) ) where import Reflex.Class import Reflex.Deletable.Class import Reflex.DynamicWriter import Reflex.PerformEvent.Base import Reflex.PerformEvent.Class import Reflex.PostBuild.Class import Reflex.Host.Class import Language.Haskell.TH #ifdef __GHCJS__ import qualified GHCJS.Buffer as JS import GHCJS.DOM import GHCJS.DOM.Types hiding (Text, fromJSString) import qualified GHCJS.DOM.Types as JS import qualified GHCJS.Foreign as JS import qualified GHCJS.Foreign.Callback as JS import qualified GHCJS.Foreign.Callback.Internal (Callback (..)) import qualified GHCJS.Marshal as JS import qualified GHCJS.Marshal.Pure as JS import qualified GHCJS.Types as JS import qualified JavaScript.Array as JS import qualified JavaScript.Array.Internal (SomeJSArray (..)) import qualified JavaScript.Object as JS import qualified JavaScript.Object.Internal (Object (..)) import qualified JavaScript.TypedArray.ArrayBuffer as JSArrayBuffer import Data.Hashable import Data.Word import Foreign.C.Types import Foreign.Ptr import Text.Encoding.Z #else import Foreign.Marshal import Graphics.UI.Gtk.WebKit.DOM.Node import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSBase import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSObjectRef import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSStringRef import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSValueRef import Graphics.UI.Gtk.WebKit.JavaScriptCore.WebFrame import Graphics.UI.Gtk.WebKit.WebView import System.Glib.FFI #endif import Control.Concurrent import Control.Monad import Control.Monad.Exception import Control.Monad.Fix import Control.Monad.IO.Class import Control.Monad.Reader import Control.Monad.Ref import Control.Monad.State import qualified Control.Monad.State.Strict as Strict import Control.Monad.Trans.Control import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.Coerce import Data.Monoid import Data.Text (Text) import qualified Data.Text as T class Monad m => HasWebView m where type WebViewPhantom m :: * askWebView :: m (WebViewSingleton (WebViewPhantom m)) instance HasWebView m => HasWebView (ReaderT r m) where type WebViewPhantom (ReaderT r m) = WebViewPhantom m askWebView = lift askWebView instance HasWebView m => HasWebView (StateT r m) where type WebViewPhantom (StateT r m) = WebViewPhantom m askWebView = lift askWebView instance HasWebView m => HasWebView (Strict.StateT r m) where type WebViewPhantom (Strict.StateT r m) = WebViewPhantom m askWebView = lift askWebView instance HasWebView m => HasWebView (PostBuildT t m) where type WebViewPhantom (PostBuildT t m) = WebViewPhantom m askWebView = lift askWebView instance (ReflexHost t, HasWebView (HostFrame t)) => HasWebView (PerformEventT t m) where type WebViewPhantom (PerformEventT t m) = WebViewPhantom (HostFrame t) askWebView = PerformEventT $ lift askWebView instance HasWebView m => HasWebView (DynamicWriterT t w m) where type WebViewPhantom (DynamicWriterT t w m) = WebViewPhantom m askWebView = lift askWebView newtype WithWebView x m a = WithWebView { unWithWebView :: ReaderT (WebViewSingleton x) m a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadTrans, MonadException, MonadAsyncException) instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (WithWebView x m) where {-# INLINABLE newEventWithTrigger #-} newEventWithTrigger = lift . newEventWithTrigger {-# INLINABLE newFanEventWithTrigger #-} newFanEventWithTrigger f = lift $ newFanEventWithTrigger f instance MonadSubscribeEvent t m => MonadSubscribeEvent t (WithWebView x m) where {-# INLINABLE subscribeEvent #-} subscribeEvent = lift . subscribeEvent instance MonadReflexHost t m => MonadReflexHost t (WithWebView x m) where type ReadPhase (WithWebView x m) = ReadPhase m {-# INLINABLE fireEventsAndRead #-} fireEventsAndRead dm a = lift $ fireEventsAndRead dm a {-# INLINABLE runHostFrame #-} runHostFrame = lift . runHostFrame instance MonadSample t m => MonadSample t (WithWebView x m) where {-# INLINABLE sample #-} sample = lift . sample instance MonadHold t m => MonadHold t (WithWebView x m) where {-# INLINABLE hold #-} hold v0 = lift . hold v0 {-# INLINABLE holdDyn #-} holdDyn v0 = lift . holdDyn v0 {-# INLINABLE holdIncremental #-} holdIncremental v0 = lift . holdIncremental v0 instance MonadTransControl (WithWebView x) where type StT (WithWebView x) a = StT (ReaderT (WebViewSingleton x)) a {-# INLINABLE liftWith #-} liftWith = defaultLiftWith WithWebView unWithWebView {-# INLINABLE restoreT #-} restoreT = defaultRestoreT WithWebView instance PerformEvent t m => PerformEvent t (WithWebView x m) where type Performable (WithWebView x m) = WithWebView x (Performable m) {-# INLINABLE performEvent_ #-} performEvent_ e = liftWith $ \run -> performEvent_ $ fmap run e {-# INLINABLE performEvent #-} performEvent e = liftWith $ \run -> performEvent $ fmap run e instance Deletable t m => Deletable t (WithWebView x m) where {-# INLINABLE deletable #-} deletable = liftThrough . deletable runWithWebView :: WithWebView x m a -> WebViewSingleton x -> m a runWithWebView = runReaderT . unWithWebView instance (Monad m) => HasWebView (WithWebView x m) where type WebViewPhantom (WithWebView x m) = x askWebView = WithWebView ask instance MonadRef m => MonadRef (WithWebView x m) where type Ref (WithWebView x m) = Ref m newRef = lift . newRef readRef = lift . readRef writeRef r = lift . writeRef r instance MonadAtomicRef m => MonadAtomicRef (WithWebView x m) where atomicModifyRef r = lift . atomicModifyRef r withWebViewSingleton :: WebView -> (forall x. WebViewSingleton x -> r) -> r withWebViewSingleton wv f = f $ WebViewSingleton wv -- | A singleton type for a given WebView; we use this to statically guarantee that different WebViews (and thus different javscript contexts) don't get mixed up newtype WebViewSingleton x = WebViewSingleton { unWebViewSingleton :: WebView } #ifdef __GHCJS__ type JSFFI_Internal = JS.MutableJSArray -> IO JS.JSVal newtype JSFFI = JSFFI JSFFI_Internal #else newtype JSFFI = JSFFI String #endif newtype JSFun x = JSFun { unJSFun :: JSRef x } instance ToJS x (JSFun x) where withJS (JSFun r) f = f r instance FromJS x (JSFun x) where fromJS = return . JSFun class IsJSContext x where data JSRef x class (Monad m, MonadIO (JSM m), MonadFix (JSM m), MonadJS x (JSM m)) => HasJS x m | m -> x where type JSM m :: * -> * liftJS :: JSM m a -> m a instance HasJS x m => HasJS x (ReaderT r m) where type JSM (ReaderT r m) = JSM m liftJS = lift . liftJS instance (HasJS x m, ReflexHost t) => HasJS x (PostBuildT t m) where type JSM (PostBuildT t m) = JSM m liftJS = lift . liftJS instance (HasJS x (HostFrame t), ReflexHost t) => HasJS x (PerformEventT t m) where type JSM (PerformEventT t m) = JSM (HostFrame t) liftJS = PerformEventT . lift . liftJS instance HasJS x m => HasJS x (DynamicWriterT t w m) where type JSM (DynamicWriterT t w m) = JSM m liftJS = lift . liftJS -- | A Monad that is capable of executing JavaScript class Monad m => MonadJS x m | m -> x where runJS :: JSFFI -> [JSRef x] -> m (JSRef x) forkJS :: m () -> m ThreadId mkJSUndefined :: m (JSRef x) isJSNull :: JSRef x -> m Bool isJSUndefined :: JSRef x -> m Bool fromJSBool :: JSRef x -> m Bool fromJSString :: JSRef x -> m String fromJSArray :: JSRef x -> m [JSRef x] fromJSUint8Array :: JSRef x -> m ByteString fromJSNumber :: JSRef x -> m Double withJSBool :: Bool -> (JSRef x -> m r) -> m r withJSString :: String -> (JSRef x -> m r) -> m r withJSNumber :: Double -> (JSRef x -> m r) -> m r withJSArray :: [JSRef x] -> (JSRef x -> m r) -> m r withJSUint8Array :: ByteString -> (JSUint8Array x -> m r) -> m r -- | Create a JSFun with zero arguments; should be equilvant to `syncCallback AlwaysRetain True` in GHCJS mkJSFun :: ([JSRef x] -> m (JSRef x)) -> m (JSFun x) --TODO: Support 'this', exceptions freeJSFun :: JSFun x -> m () setJSProp :: String -> JSRef x -> JSRef x -> m () getJSProp :: String -> JSRef x -> m (JSRef x) withJSNode :: Node -> (JSRef x -> m r) -> m r #ifdef __GHCJS__ data JSCtx_IO instance MonadIO m => HasJS JSCtx_IO (WithWebView x m) where type JSM (WithWebView x m) = IO liftJS = liftIO instance IsJSContext JSCtx_IO where newtype JSRef JSCtx_IO = JSRef_IO { unJSRef_IO :: JS.JSVal } instance MonadJS JSCtx_IO IO where runJS (JSFFI f) l = fmap JSRef_IO . f =<< JS.fromListIO (coerce l) forkJS = forkIO mkJSUndefined = return $ JSRef_IO JS.jsUndefined isJSNull (JSRef_IO r) = return $ JS.isNull r isJSUndefined (JSRef_IO r) = return $ JS.isUndefined r fromJSBool (JSRef_IO r) = return $ JS.fromJSBool r fromJSString (JSRef_IO r) = return $ JS.fromJSString $ JS.pFromJSVal r fromJSArray (JSRef_IO r) = fmap coerce $ JS.toListIO $ coerce r fromJSUint8Array (JSRef_IO r) = fmap (JS.toByteString 0 Nothing . JS.createFromArrayBuffer) $ JSArrayBuffer.unsafeFreeze $ JS.pFromJSVal r --TODO: Assert that this is immutable fromJSNumber (JSRef_IO r) = do Just n <- JS.fromJSVal r return n withJSBool b f = f $ JSRef_IO $ JS.toJSBool b withJSString s f = f $ JSRef_IO $ JS.pToJSVal $ JS.toJSString s withJSNumber n f = do r <- JS.toJSVal n f $ JSRef_IO r withJSArray l f = do r <- JS.fromListIO $ coerce l f $ JSRef_IO $ coerce r withJSUint8Array payload f = BS.useAsCString payload $ \cStr -> do ba <- extractByteArray cStr $ BS.length payload f $ JSUint8Array $ JSRef_IO ba mkJSFun f = do cb <- JS.syncCallback1' $ \args -> do l <- JS.toListIO $ coerce args JSRef_IO result <- f $ coerce l return result fmap (JSFun . JSRef_IO) $ funWithArguments $ coerce cb freeJSFun (JSFun (JSRef_IO r)) = JS.releaseCallback $ coerce r setJSProp s (JSRef_IO v) (JSRef_IO o) = JS.setProp (JS.toJSString s) v $ coerce o getJSProp s (JSRef_IO o) = do r <- JS.getProp (JS.toJSString s) $ coerce o return $ JSRef_IO r withJSNode n f = f $ JSRef_IO $ unNode n foreign import javascript unsafe "new Uint8Array($1_1.buf, $1_2, $2)" extractByteArray :: Ptr CChar -> Int -> IO JS.JSVal foreign import javascript unsafe "function(){ return $1(arguments); }" funWithArguments :: JS.Callback (JS.MutableJSArray -> IO a) -> IO JS.JSVal #else -- | Make a JS string available that is not wrapped up as a JSValueRef withJSStringRaw :: MonadAsyncException m => String -> (JSStringRef -> m r) -> m r withJSStringRaw str a = do bracket (liftIO $ jsstringcreatewithutf8cstring str) (liftIO . jsstringrelease) $ \strRef -> do a strRef fromJSNumberRaw :: (MonadIO m, HasJSContext m) => JSValueRef -> m Double fromJSNumberRaw val = do jsContext <- askJSContext liftIO $ jsvaluetonumber jsContext val nullPtr --TODO: Exceptions data JSCtx_JavaScriptCore x instance IsJSContext (JSCtx_JavaScriptCore x) where newtype JSRef (JSCtx_JavaScriptCore x) = JSRef_JavaScriptCore { unJSRef_JavaScriptCore :: JSValueRef } instance MonadIO m => HasJS (JSCtx_JavaScriptCore x) (WithWebView x m) where type JSM (WithWebView x m) = WithWebView x IO liftJS a = do wv <- askWebView liftIO $ runWithWebView a wv newtype WithJSContext x m a = WithJSContext { unWithJSContext :: ReaderT JSContextRef m a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadTrans, MonadException, MonadAsyncException) runWithJSContext :: WithJSContext x m a -> JSContextRef -> m a runWithJSContext = runReaderT . unWithJSContext class Monad m => HasJSContext m where askJSContext :: m JSContextRef instance MonadIO m => HasJSContext (WithWebView x m) where askJSContext = do wv <- askWebView liftIO $ webFrameGetGlobalContext =<< webViewGetMainFrame (unWebViewSingleton wv) instance Monad m => HasJSContext (WithJSContext x m) where askJSContext = WithJSContext ask lowerWithJSContext :: (HasJSContext m, MonadIO m) => WithJSContext x IO a -> m a lowerWithJSContext a = do c <- askJSContext liftIO $ runWithJSContext a c liftWithWebViewThroughWithJSContext :: (HasJSContext m, HasWebView m, MonadIO m, MonadTrans t, Monad m1) => ((t1 -> t m1 a) -> WithJSContext x IO b) -> (t1 -> WithWebView (WebViewPhantom m) m1 a) -> m b liftWithWebViewThroughWithJSContext f a = do wv <- askWebView lowerWithJSContext $ f $ \b' -> lift $ runWithWebView (a b') wv instance MonadJS (JSCtx_JavaScriptCore x) (WithWebView x IO) where forkJS a = do wv <- askWebView liftIO $ forkIO $ runWithWebView a wv mkJSFun a = do wv <- askWebView lowerWithJSContext $ mkJSFun $ \args -> lift $ runWithWebView (a args) wv runJS expr args = lowerWithJSContext $ runJS expr args mkJSUndefined = lowerWithJSContext mkJSUndefined isJSNull = lowerWithJSContext . isJSNull isJSUndefined = lowerWithJSContext . isJSUndefined fromJSBool = lowerWithJSContext . fromJSBool fromJSString = lowerWithJSContext . fromJSString fromJSArray = lowerWithJSContext . fromJSArray fromJSUint8Array = lowerWithJSContext . fromJSUint8Array fromJSNumber = lowerWithJSContext . fromJSNumber freeJSFun = lowerWithJSContext . freeJSFun withJSBool = liftWithWebViewThroughWithJSContext . withJSBool withJSString = liftWithWebViewThroughWithJSContext . withJSString withJSNumber = liftWithWebViewThroughWithJSContext . withJSNumber withJSArray = liftWithWebViewThroughWithJSContext . withJSArray withJSUint8Array = liftWithWebViewThroughWithJSContext . withJSUint8Array withJSNode = liftWithWebViewThroughWithJSContext . withJSNode setJSProp propName valRef objRef = lowerWithJSContext $ setJSProp propName valRef objRef getJSProp propName objRef = lowerWithJSContext $ getJSProp propName objRef instance MonadJS (JSCtx_JavaScriptCore x) (WithJSContext x IO) where runJS (JSFFI body) args = do jsContext <- askJSContext withJSArray args $ \(JSRef_JavaScriptCore this) -> liftIO $ do result <- bracket (jsstringcreatewithutf8cstring body) jsstringrelease $ \script -> jsevaluatescript jsContext script this nullPtr 1 nullPtr return $ JSRef_JavaScriptCore result --TODO: Protect and unprotect result forkJS a = do c <- askJSContext liftIO $ forkIO $ runWithJSContext a c mkJSUndefined = do jsContext <- askJSContext fmap JSRef_JavaScriptCore $ liftIO $ jsvaluemakeundefined jsContext isJSNull (JSRef_JavaScriptCore r) = do jsContext <- askJSContext liftIO $ jsvalueisnull jsContext r isJSUndefined (JSRef_JavaScriptCore r) = do jsContext <- askJSContext liftIO $ jsvalueisundefined jsContext r fromJSBool (JSRef_JavaScriptCore r) = do jsContext <- askJSContext liftIO $ jsvaluetoboolean jsContext r fromJSString (JSRef_JavaScriptCore r) = do jsContext <- askJSContext liftIO $ do s <- jsvaluetostringcopy jsContext r nullPtr --TODO: Deal with exceptions l <- jsstringgetmaximumutf8cstringsize s allocaBytes (fromIntegral l) $ \ps -> do _ <- jsstringgetutf8cstring'_ s ps (fromIntegral l) peekCString ps withJSBool b a = do jsContext <- askJSContext valRef <- liftIO $ jsvaluemakeboolean jsContext b a $ JSRef_JavaScriptCore valRef withJSString str a = do jsContext <- askJSContext withJSStringRaw str $ \strRef -> do valRef <- liftIO $ jsvaluemakestring jsContext strRef a $ JSRef_JavaScriptCore valRef --TODO: Protect/unprotect valRef withJSNumber n a = do jsContext <- askJSContext valRef <- liftIO $ jsvaluemakenumber jsContext n a $ JSRef_JavaScriptCore valRef --TODO: Protect/unprotect valRef withJSArray elems a = do jsContext <- askJSContext let numElems = length elems bracket (liftIO $ mallocArray numElems) (liftIO . free) $ \elemsArr -> do liftIO $ pokeArray elemsArr $ coerce elems bracket (liftIO $ jsobjectmakearray jsContext (fromIntegral numElems) elemsArr nullPtr) (const $ return ()) $ \arrRef -> do --TODO: Do we need to protect/unprotect the array object? a $ JSRef_JavaScriptCore arrRef --TODO: Protect/unprotect valRef --TODO: When supported by webkitgtk3-javascriptcore, go directly from C string to Uint8Array without creating each item individually withJSUint8Array payload f = withJSArrayFromList (BS.unpack payload) $ \x -> do payloadRef <- runJS (JSFFI "new Uint8Array(this[0])") [x] f $ JSUint8Array payloadRef fromJSArray (JSRef_JavaScriptCore a) = do jsContext <- askJSContext lenRef <- withJSStringRaw "length" $ \lengthStr -> do liftIO $ jsobjectgetproperty jsContext a lengthStr nullPtr --TODO: Exceptions lenDouble <- fromJSNumberRaw lenRef let len = round lenDouble liftIO $ forM [0..len-1] $ \i -> do JSRef_JavaScriptCore <$> jsobjectgetpropertyatindex jsContext a i nullPtr --TODO: Exceptions fromJSUint8Array a = do vals <- fromJSArray a doubles <- mapM fromJSNumber vals return $ BS.pack $ map round doubles fromJSNumber (JSRef_JavaScriptCore val) = do jsContext <- askJSContext liftIO $ jsvaluetonumber jsContext val nullPtr --TODO: Exceptions mkJSFun a = do jsContext <- askJSContext cb <- liftIO $ mkJSObjectCallAsFunctionCallback $ \_ _ _ argc argv _ -> do --TODO: Use the exception pointer to handle haskell exceptions args <- forM [0..fromIntegral (argc-1)] $ \n -> do x <- peekElemOff argv n jsvalueprotect jsContext x return $ JSRef_JavaScriptCore x --TODO: Unprotect eventually unJSRef_JavaScriptCore <$> runWithJSContext (a args) jsContext cbRef <- liftIO $ jsobjectmakefunctionwithcallback jsContext nullPtr cb liftIO $ jsvalueprotect jsContext cbRef return $ JSFun $ JSRef_JavaScriptCore cbRef freeJSFun (JSFun (JSRef_JavaScriptCore f)) = do jsContext <- askJSContext liftIO $ jsvalueunprotect jsContext f setJSProp propName (JSRef_JavaScriptCore valRef) (JSRef_JavaScriptCore objRef) = do withJSStringRaw propName $ \propNameRaw -> do jsContext <- askJSContext liftIO $ jsobjectsetproperty jsContext objRef propNameRaw valRef 0 nullPtr --TODO: property attribute, exceptions getJSProp propName (JSRef_JavaScriptCore objRef) = do withJSStringRaw propName $ \propNameRaw -> do jsContext <- askJSContext liftIO $ JSRef_JavaScriptCore <$> jsobjectgetproperty jsContext objRef propNameRaw nullPtr --TODO: property attribute, exceptions withJSNode = error "withJSNode is only supported in ghcjs" #endif class FromJS x a where fromJS :: MonadJS x m => JSRef x -> m a instance FromJS x () where fromJS _ = return () --TODO: Should this do some kind of checking for the js value? instance FromJS x Bool where fromJS = fromJSBool instance ToJS x Bool where withJS = withJSBool instance FromJS x String where fromJS = fromJSString instance FromJS x Text where fromJS s = T.pack <$> fromJSString s instance FromJS x a => FromJS x (Maybe a) where fromJS x = do n <- isJSNull x if n then return Nothing else Just <$> fromJS x class ToJS x a where withJS :: MonadJS x m => a -> (JSRef x -> m r) -> m r instance ToJS x (JSRef x) where withJS r = ($ r) instance FromJS x (JSRef x) where fromJS = return instance ToJS x String where withJS = withJSString instance ToJS x Text where withJS = withJSString . T.unpack newtype JSArray a = JSArray { unJSArray :: [a] } instance ToJS x a => ToJS x (JSArray a) where withJS = withJSArrayFromList . unJSArray instance FromJS x a => FromJS x (JSArray a) where fromJS = fmap JSArray . mapM fromJS <=< fromJSArray withJSArrayFromList :: (ToJS x a, MonadJS x m) => [a] -> (JSRef x -> m r) -> m r withJSArrayFromList as f = go as [] where go [] jsRefs = withJSArray (reverse jsRefs) f go (h:t) jsRefs = withJS h $ \hRef -> go t (hRef : jsRefs) newtype JSUint8Array x = JSUint8Array { unJSUint8Array :: JSRef x } instance ToJS x (JSUint8Array x) where withJS (JSUint8Array r) = ($ r) instance FromJS x (JSUint8Array x) where fromJS = return . JSUint8Array instance ToJS x Word8 where withJS n = withJSNumber $ fromIntegral n --TODO: Check things; throw exceptions instance ToJS x Int where withJS n = withJSNumber $ fromIntegral n --TODO: Check things; throw exceptions instance FromJS x Int where fromJS = fmap round . fromJSNumber --TODO: Check things; throw exceptions instance ToJS x Double where withJS = withJSNumber instance FromJS x Double where fromJS = fromJSNumber instance ToJS x Node where withJS = withJSNode importJS :: Safety -> String -> String -> Q Type -> Q [Dec] importJS safety body name qt = do t <- qt let (argTypes, _) = parseType t argNames <- forM argTypes $ \_ -> do arg <- newName "arg" argRef <- newName "argRef" return (arg, argRef) (jsffiDecs, jsffiExp) <- mkJSFFI safety body let go [] = [| runJS $(return jsffiExp) $(listE $ map (varE . snd) argNames) >>= fromJS |] go ((arg, argRef) : args) = [| withJS $(varE arg) $ $(lamE [varP argRef] $ go args) |] e <- lamE (map (varP. fst) argNames) $ go argNames let n = mkName name return $ jsffiDecs ++ [ SigD n t , ValD (VarP n) (NormalB e) [] ] mkJSFFI :: Safety -> String -> Q ([Dec], Exp) #ifdef __GHCJS__ mkJSFFI safety body = do -- n <- newName "jsffi" --TODO: Should use newName, but that doesn't seem to work with ghcjs l <- location n <- newName $ "jsffi_" <> zEncodeString (loc_package l <> ":" <> loc_module l) <> "_" <> show (abs (hash (show safety, body))) t <- [t| JSFFI_Internal |] let wrappedBody = "(function(){ return (" <> body <> "); }).apply($1)" let decs = [ForeignD $ ImportF JavaScript safety wrappedBody n t] e <- [| JSFFI $(varE n) |] return (decs, e) #else mkJSFFI _ body = do e <- [| JSFFI body |] return ([], e) #endif parseType :: Type -> ([Type], Type) parseType (ForallT _ [AppT (AppT (ConT monadJs) (VarT _)) (VarT m)] funType) | monadJs == ''MonadJS = go funType where go t = case t of AppT (AppT ArrowT arg) t' -> let (args, result) = go t' in (arg : args, result) AppT (VarT m') result | m' == m -> ([], result) _ -> error $ "parseType: can't parse type " <> show t parseType t = error $ "parseType: can't parse type " <> show t
manyoo/reflex-dom
src/Foreign/JavaScript/TH.hs
bsd-3-clause
23,053
9
15
4,524
4,811
2,486
2,325
-1
-1
{-# language FlexibleContexts #-} {-# language ScopedTypeVariables #-} {-# language TypeFamilies #-} module Casting where import Feldspar import Feldspar.Software import Feldspar.Software as Soft (icompile) import Feldspar.Hardware import Feldspar.Hardware as Hard (icompileWrap) import Prelude hiding (toInteger, (&&), Ord(..)) -------------------------------------------------------------------------------- -- * ... -------------------------------------------------------------------------------- type HRef = Reference Hardware example :: Hardware () example = do {- a :: HRef (HExp Word8) <- initRef (value 10) b :: HRef (HExp Int8) <- initRef (value 5) c :: HRef (HExp Int16) <- initRef (value 300) va <- getRef a vb <- getRef b vc <- getRef c setRef b (i2n va) setRef c (i2n va) setRef a (i2n vc) x0 <- shareM (10 :: HExp Word16) for 0 10 $ \(i :: HExp Integer) -> setRef a (i2n (x0 `shiftR` (i * 8))) -} t :: HRef (HExp Word32) <- initRef (value 12) setRef t (k (value 20)) -------------------------------------------------------------------------------- k :: HExp Integer -> HExp Word32 k t = (0 <= t && t <= 19) ?? 0x5a827999 $ (20 <= t && t <= 39) ?? 0x6ed9eba1 $ (40 <= t && t <= 59) ?? 0x8f1bbcdc $ 0xca62c1d6 (??) :: HExp Bool -> HExp Word32 -> HExp Word32 -> HExp Word32 (??) = (?) -------------------------------------------------------------------------------- test = Hard.icompileWrap example --------------------------------------------------------------------------------
markus-git/co-feldspar
examples/Casting.hs
bsd-3-clause
1,649
0
14
367
287
161
126
24
1
-- | -- Module : Network.TLS.Handshake.Process -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- -- process handshake message received -- module Network.TLS.Handshake.Process ( processHandshake , startHandshake , getHandshakeDigest ) where import Control.Concurrent.MVar import Control.Monad.State.Strict (gets) import Control.Monad import Control.Monad.IO.Class (liftIO) import Network.TLS.Types (Role(..), invertRole) import Network.TLS.Util import Network.TLS.Packet import Network.TLS.ErrT import Network.TLS.Struct import Network.TLS.State import Network.TLS.Context.Internal import Network.TLS.Crypto import Network.TLS.Imports import Network.TLS.Handshake.State import Network.TLS.Handshake.Key import Network.TLS.Extension import Network.TLS.Parameters import Data.X509 (CertificateChain(..), Certificate(..), getCertificate) processHandshake :: Context -> Handshake -> IO () processHandshake ctx hs = do role <- usingState_ ctx isClientContext case hs of ClientHello cver ran _ cids _ ex _ -> when (role == ServerRole) $ do mapM_ (usingState_ ctx . processClientExtension) ex -- RFC 5746: secure renegotiation -- TLS_EMPTY_RENEGOTIATION_INFO_SCSV: {0x00, 0xFF} when (secureRenegotiation && (0xff `elem` cids)) $ usingState_ ctx $ setSecureRenegotiation True startHandshake ctx cver ran Certificates certs -> processCertificates role certs ClientKeyXchg content -> when (role == ServerRole) $ do processClientKeyXchg ctx content Finished fdata -> processClientFinished ctx fdata _ -> return () let encoded = encodeHandshake hs when (certVerifyHandshakeMaterial hs) $ usingHState ctx $ addHandshakeMessage encoded when (finishHandshakeTypeMaterial $ typeOfHandshake hs) $ usingHState ctx $ updateHandshakeDigest encoded where secureRenegotiation = supportedSecureRenegotiation $ ctxSupported ctx -- RFC5746: secure renegotiation -- the renegotiation_info extension: 0xff01 processClientExtension (ExtensionRaw 0xff01 content) | secureRenegotiation = do v <- getVerifiedData ClientRole let bs = extensionEncode (SecureRenegotiation v Nothing) unless (bs `bytesEq` content) $ throwError $ Error_Protocol ("client verified data not matching: " ++ show v ++ ":" ++ show content, True, HandshakeFailure) setSecureRenegotiation True -- unknown extensions processClientExtension _ = return () processCertificates :: Role -> CertificateChain -> IO () processCertificates ServerRole (CertificateChain []) = return () processCertificates ClientRole (CertificateChain []) = throwCore $ Error_Protocol ("server certificate missing", True, HandshakeFailure) processCertificates _ (CertificateChain (c:_)) = usingHState ctx $ setPublicKey pubkey where pubkey = certPubKey $ getCertificate c -- process the client key exchange message. the protocol expects the initial -- client version received in ClientHello, not the negotiated version. -- in case the version mismatch, generate a random master secret processClientKeyXchg :: Context -> ClientKeyXchgAlgorithmData -> IO () processClientKeyXchg ctx (CKX_RSA encryptedPremaster) = do (rver, role, random) <- usingState_ ctx $ do (,,) <$> getVersion <*> isClientContext <*> genRandom 48 ePremaster <- decryptRSA ctx encryptedPremaster usingHState ctx $ do expectedVer <- gets hstClientVersion case ePremaster of Left _ -> setMasterSecretFromPre rver role random Right premaster -> case decodePreMasterSecret premaster of Left _ -> setMasterSecretFromPre rver role random Right (ver, _) | ver /= expectedVer -> setMasterSecretFromPre rver role random | otherwise -> setMasterSecretFromPre rver role premaster processClientKeyXchg ctx (CKX_DH clientDHValue) = do rver <- usingState_ ctx getVersion role <- usingState_ ctx isClientContext serverParams <- usingHState ctx getServerDHParams dhpriv <- usingHState ctx getDHPrivate let premaster = dhGetShared (serverDHParamsToParams serverParams) dhpriv clientDHValue usingHState ctx $ setMasterSecretFromPre rver role premaster processClientKeyXchg ctx (CKX_ECDH bytes) = do ServerECDHParams grp _ <- usingHState ctx getServerECDHParams case decodeGroupPublic grp bytes of Left _ -> throwCore $ Error_Protocol ("client public key cannot be decoded", True, HandshakeFailure) Right clipub -> do srvpri <- usingHState ctx getECDHPrivate case groupGetShared clipub srvpri of Just premaster -> do rver <- usingState_ ctx getVersion role <- usingState_ ctx isClientContext usingHState ctx $ setMasterSecretFromPre rver role premaster Nothing -> throwCore $ Error_Protocol ("cannote generate a shared secret on ECDH", True, HandshakeFailure) processClientFinished :: Context -> FinishedData -> IO () processClientFinished ctx fdata = do (cc,ver) <- usingState_ ctx $ (,) <$> isClientContext <*> getVersion expected <- usingHState ctx $ getHandshakeDigest ver $ invertRole cc when (expected /= fdata) $ do throwCore $ Error_Protocol("bad record mac", True, BadRecordMac) usingState_ ctx $ updateVerifiedData ServerRole fdata return () -- initialize a new Handshake context (initial handshake or renegotiations) startHandshake :: Context -> Version -> ClientRandom -> IO () startHandshake ctx ver crand = let hs = Just $ newEmptyHandshake ver crand in liftIO $ void $ swapMVar (ctxHandshake ctx) hs
erikd/hs-tls
core/Network/TLS/Handshake/Process.hs
bsd-3-clause
6,018
0
19
1,415
1,440
714
726
98
8
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.World -- Copyright : (c) Peter Robinson 2009 -- License : BSD-like -- -- Maintainer : thaldyron@gmail.com -- Stability : provisional -- Portability : portable -- -- Interface to the world-file that contains a list of explicitly -- requested packages. Meant to be imported qualified. -- -- A world file entry stores the package-name, package-version, and -- user flags. -- For example, the entry generated by -- # cabal install stm-io-hooks --flags="-debug" -- looks like this: -- # stm-io-hooks -any --flags="-debug" -- To rebuild/upgrade the packages in world (e.g. when updating the compiler) -- use -- # cabal install world -- ----------------------------------------------------------------------------- module Distribution.Client.World ( WorldPkgInfo(..), insert, delete, getContents, ) where import Distribution.Package ( Dependency(..) ) import Distribution.PackageDescription ( FlagAssignment, FlagName(FlagName) ) import Distribution.Verbosity ( Verbosity ) import Distribution.Simple.Utils ( die, info, chattyTry, writeFileAtomic ) import Distribution.Text ( Text(..), display, simpleParse ) import qualified Distribution.Compat.ReadP as Parse import qualified Text.PrettyPrint as Disp import Text.PrettyPrint ( (<>), (<+>) ) import Data.Char as Char import Control.Exception (catch) import Data.List ( unionBy, deleteFirstsBy, nubBy ) import Data.Maybe ( isJust, fromJust ) import System.IO.Error ( isDoesNotExistError ) import qualified Data.ByteString.Lazy.Char8 as B import Prelude hiding (getContents) data WorldPkgInfo = WorldPkgInfo Dependency FlagAssignment deriving (Show,Eq) -- | Adds packages to the world file; creates the file if it doesn't -- exist yet. Version constraints and flag assignments for a package are -- updated if already present. IO errors are non-fatal. insert :: Verbosity -> FilePath -> [WorldPkgInfo] -> IO () insert = modifyWorld $ unionBy equalUDep -- | Removes packages from the world file. -- Note: Currently unused as there is no mechanism in Cabal (yet) to -- handle uninstalls. IO errors are non-fatal. delete :: Verbosity -> FilePath -> [WorldPkgInfo] -> IO () delete = modifyWorld $ flip (deleteFirstsBy equalUDep) -- | WorldPkgInfo values are considered equal if they refer to -- the same package, i.e., we don't care about differing versions or flags. equalUDep :: WorldPkgInfo -> WorldPkgInfo -> Bool equalUDep (WorldPkgInfo (Dependency pkg1 _) _) (WorldPkgInfo (Dependency pkg2 _) _) = pkg1 == pkg2 -- | Modifies the world file by applying an update-function ('unionBy' -- for 'insert', 'deleteFirstsBy' for 'delete') to the given list of -- packages. IO errors are considered non-fatal. modifyWorld :: ([WorldPkgInfo] -> [WorldPkgInfo] -> [WorldPkgInfo]) -- ^ Function that defines how -- the list of user packages are merged with -- existing world packages. -> Verbosity -> FilePath -- ^ Location of the world file -> [WorldPkgInfo] -- ^ list of user supplied packages -> IO () modifyWorld _ _ _ [] = return () modifyWorld f verbosity world pkgs = chattyTry "Error while updating world-file. " $ do pkgsOldWorld <- getContents world -- Filter out packages that are not in the world file: let pkgsNewWorld = nubBy equalUDep $ f pkgs pkgsOldWorld -- 'Dependency' is not an Ord instance, so we need to check for -- equivalence the awkward way: if not (all (`elem` pkgsOldWorld) pkgsNewWorld && all (`elem` pkgsNewWorld) pkgsOldWorld) then do info verbosity "Updating world file..." writeFileAtomic world $ unlines [ (display pkg) | pkg <- pkgsNewWorld] else info verbosity "World file is already up to date." -- | Returns the content of the world file as a list getContents :: FilePath -> IO [WorldPkgInfo] getContents world = do content <- safelyReadFile world let result = map simpleParse (lines $ B.unpack content) if all isJust result then return $ map fromJust result else die "Could not parse world file." where safelyReadFile :: FilePath -> IO B.ByteString safelyReadFile file = B.readFile file `catch` handler where handler e | isDoesNotExistError e = return B.empty | otherwise = ioError e instance Text WorldPkgInfo where disp (WorldPkgInfo dep flags) = disp dep <+> dispFlags flags where dispFlags [] = Disp.empty dispFlags fs = Disp.text "--flags=" <> Disp.doubleQuotes (flagAssToDoc fs) flagAssToDoc = foldr (\(FlagName fname,val) flagAssDoc -> (if not val then Disp.char '-' else Disp.empty) Disp.<> Disp.text fname Disp.<+> flagAssDoc) Disp.empty parse = do dep <- parse Parse.skipSpaces flagAss <- Parse.option [] parseFlagAssignment return $ WorldPkgInfo dep flagAss where parseFlagAssignment :: Parse.ReadP r FlagAssignment parseFlagAssignment = do _ <- Parse.string "--flags" Parse.skipSpaces _ <- Parse.char '=' Parse.skipSpaces inDoubleQuotes $ Parse.many1 flag where inDoubleQuotes :: Parse.ReadP r a -> Parse.ReadP r a inDoubleQuotes = Parse.between (Parse.char '"') (Parse.char '"') flag = do Parse.skipSpaces val <- negative Parse.+++ positive name <- ident Parse.skipSpaces return (FlagName name,val) negative = do _ <- Parse.char '-' return False positive = return True ident :: Parse.ReadP r String ident = do -- First character must be a letter/digit to avoid flags -- like "+-debug": c <- Parse.satisfy Char.isAlphaNum cs <- Parse.munch (\ch -> Char.isAlphaNum ch || ch == '_' || ch == '-') return (c:cs)
IreneKnapp/Faction
faction/Distribution/Client/World.hs
bsd-3-clause
6,419
0
21
1,801
1,264
677
587
107
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveDataTypeable #-} module Types where import Test.QuickCheck import Control.Applicative import Control.Arrow import Numeric import Data.Data data Tree a b = Leaf a b | Branch a [Tree a b] deriving (Eq,Show) class HaveVolume a where volume :: a -> Float instance HaveVolume b => HaveVolume (Tree a b) where volume (Leaf a b) = volume b volume (Branch s ts) = sum $ map volume ts instance (Eq a,Eq b,HaveVolume b) => Ord (Tree a b) where t1 <= t2 = (volume t1 <= volume t2) instance HaveVolume Float where volume = id instance HaveVolume Int where volume = fromIntegral type Label = String type Html = String -- | Rect with information whichever Portrait or Horizontal. data RectPH = RectPH { rect :: Rect, isPortrait :: Bool, depth :: Int } deriving (Eq,Show) data Color = Color { r :: Int, g :: Int, b :: Int, a :: Int } deriving (Eq,Show) colorCode :: Color -> String colorCode Color{..} = "#" ++ toBeTwoChar r ++ toBeTwoChar g ++ toBeTwoChar b where toBeTwoChar n = (if n < 16 then "0" else "") ++ showHex n "" floatAlpha :: Color -> Float floatAlpha color = (fromIntegral $ a color) / 255.0 data PreNode = PreRectNode Rect RectAttr | PreTextNode Rect TextAttr deriving (Eq,Show) forget :: PreNode -> Rect forget pre_node = case pre_node of PreRectNode rect _ -> rect PreTextNode rect _ -> rect data RectAttr = RectAttr { color :: Color } deriving (Eq,Show) data TextAttr = TextAttr { fontColor :: Color, text :: String, fontSize :: Maybe Float, isVertical :: Bool } deriving (Eq,Show) data Rect = Rect { centerX :: Float, centerY :: Float, width :: Float, height :: Float } deriving (Eq,Show) left :: Rect -> Float left = uncurry (-) . (centerX &&& ((/2).width)) top :: Rect -> Float top = uncurry (-) . (centerY &&& ((/2).width)) right :: Rect -> Float right = uncurry (+) . (centerX &&& ((/2).width)) bottom :: Rect -> Float bottom = uncurry (+) . (centerY &&& ((/2).width)) ---------------------------------------------------------------------- instance Arbitrary RectPH where arbitrary = RectPH <$> (arbitrary :: Gen Rect) <*> (arbitrary :: Gen Bool) <*> (arbitrary :: Gen Int) instance Arbitrary Rect where arbitrary = Rect <$> (arbitrary :: Gen Float) <*> (arbitrary :: Gen Float) <*> (arbitrary :: Gen Float) <*> (arbitrary :: Gen Float) instance (Arbitrary a,Arbitrary b) => Arbitrary (Tree a b) where arbitrary = oneof [ Leaf <$> arbitrary <*> arbitrary, Branch <$> arbitrary <*> listOf arbitrary ] data Option = Option { output :: Maybe String, input :: Maybe String } deriving (Data,Show,Typeable)
mathfur/Treemap-Directory-Viewer
src/Types.hs
bsd-3-clause
2,743
0
11
587
1,014
560
454
81
2
module P594 ( p594 ) where choose :: Int -> [a] -> [[a]] choose 0 _ = [[]] choose _ [] = [] choose n (x:xs) = map (x:) (choose (n-1) xs) ++ choose n xs vertices :: Int -> Int -> [[(Int,Int)]] vertices a b = choose (b*b) $ (,) <$> [0..a] <*> [0..a] arguments :: Int -> [[Int]] arguments b = (:) <$> [1..b+1] <*> (sequence . replicate 2 $ [1..b]) makeSearchable :: [(Int,Int)] -> [[Int]] -> [[Int]] makeSearchable xs ys = zipWith (\(a,b) (_:i:j:_) -> [i,j,a,b]) xs ys combinationFormula :: Double -> Double -> Double combinationFormula n k | n < 0 = 0 | k < 0 = 0 | n < k = 0 | otherwise = fac n / (fac k * fac (n-k)) where fac n' = product [1..n'] searchVertices :: [[Int]] -> Int -> Int -> Int -> Int -> [Int] searchVertices [] _ _ _ _= [] searchVertices ((x:x2:xs):xss) i j a b | j == 0 = [0,0] | i == 0 = [0,a] | j == b + 1 = [a,a] | i == b + 1 = [a,0] | x == i && x2 == j = xs | otherwise = searchVertices xss i j a b searchVertices _ _ _ _ _ = [] matrixElementsM :: [[Int]] -> [Int] -> Int -> Int -> Double matrixElementsM xs (u:i:j:_) a b = let searching x y n = searchVertices xs x y a b !! n top' = searching j u 0 - searching i (u-1) 0 + searching j u 1 - searching i (u-1) 1 bottom' = searching j u 0 - searching i (u-1) 0 + j - i in combinationFormula (fromIntegral top') (fromIntegral bottom') matrixElementsM _ _ _ _ = 0 matrixElementsP :: [[Int]] -> [Int] -> Int -> Int -> Double matrixElementsP xs (v:i:j:_) a b = let searching x y n = searchVertices xs x y a b !! n top' = searching v j 0 - searching (v-1) i 0 + searching v j 1 - searching (v-1) i 0 bottom' = searching v j 0 - searching (v-1) i 0 + j - i in combinationFormula (fromIntegral top') (fromIntegral bottom') matrixElementsP _ _ _ _ = 0 matrixBuilderP :: [[Int]] -> [[Int]] -> Int -> Int -> [Double] matrixBuilderP _ [] _ _ = [] matrixBuilderP v (x:args) a b = matrixElementsP v x a b : matrixBuilderP v args a b matrixBuilderM :: [[Int]] -> [[Int]] -> Int -> Int -> [Double] matrixBuilderM _ [] _ _ = [] matrixBuilderM v (x:args) a b = matrixElementsM v x a b : matrixBuilderM v args a b matrixFormater :: Int -> [Double] -> [[[Double]]] matrixFormater _ [] = [] matrixFormater b xs = formatAgain (take (b*b) xs) b : matrixFormater b (drop (b*b) xs) where formatAgain [] _ = [] formatAgain ys b' = take b' ys : formatAgain (drop b' ys) b' determinant :: [[Double]] -> Double determinant [] = 0 determinant [_] = 0 determinant (x:x2:_) = (x !! 0) * (x2 !! 1) - (x !! 1) * (x2 !! 0) runCalc :: Int -> Int -> [[(Int,Int)]] -> [Double] runCalc _ _ [] = [] runCalc a b (x:xs) = let findProduct = product . map determinant . matrixFormater b arg1 = makeSearchable x arg2 arg2 = arguments b in (findProduct . matrixBuilderP arg1 arg2 a $ b) * (findProduct . matrixBuilderM arg1 arg2 a $ b) : runCalc a b xs p594 :: IO () p594 = print $ sum . runCalc 3 2 $ (vertices 3 2)
pyuk/euler2
src/P594.hs
bsd-3-clause
3,046
0
14
806
1,747
907
840
74
2
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} module Web.Routing.Router where #if MIN_VERSION_base(4,8,0) #else import Control.Applicative #endif import Control.Monad.RWS.Strict import qualified Data.HashMap.Strict as HM import Data.Hashable import Data.Maybe import qualified Data.Text as T import Web.Routing.SafeRouting newtype RegistryT n b middleware reqTypes (m :: * -> *) a = RegistryT { runRegistryT :: RWST (PathInternal '[]) [middleware] (RegistryState n b reqTypes) m a } deriving ( Monad, Functor, Applicative, MonadIO, MonadReader (PathInternal '[]), MonadWriter [middleware], MonadState (RegistryState n b reqTypes), MonadTrans ) data RegistryState n b reqTypes = RegistryState { rs_registry :: !(HM.HashMap reqTypes (Registry n b)), rs_anyMethod :: !(Registry n b) } hookAny :: (Monad m, Eq reqTypes, Hashable reqTypes) => reqTypes -> ([T.Text] -> n b) -> RegistryT n b middleware reqTypes m () hookAny reqType action = modify $ \rs -> rs { rs_registry = let reg = fromMaybe emptyRegistry (HM.lookup reqType (rs_registry rs)) in HM.insert reqType (fallbackRoute action reg) (rs_registry rs) } hookAnyMethod :: (Monad m) => ([T.Text] -> n b) -> RegistryT n b middleware reqTypes m () hookAnyMethod action = modify $ \rs -> rs { rs_anyMethod = fallbackRoute action (rs_anyMethod rs) } hookRoute :: (Monad m, Eq reqTypes, Hashable reqTypes) => reqTypes -> PathInternal as -> HVectElim' (n b) as -> RegistryT n b middleware reqTypes m () hookRoute reqType path action = do basePath <- ask modify $ \rs -> rs { rs_registry = let reg = fromMaybe emptyRegistry (HM.lookup reqType (rs_registry rs)) reg' = defRoute (basePath </!> path) action reg in HM.insert reqType reg' (rs_registry rs) } hookRouteAnyMethod :: (Monad m) => PathInternal as -> HVectElim' (n b) as -> RegistryT n b middleware reqTypes m () hookRouteAnyMethod path action = do basePath <- ask modify $ \rs -> rs { rs_anyMethod = defRoute (basePath </!> path) action (rs_anyMethod rs) } middleware :: Monad m => middleware -> RegistryT n b middleware reqTypes m () middleware x = tell [x] swapMonad :: Monad m => (forall b. n b -> m b) -> RegistryT x y middleware reqTypes n a -> RegistryT x y middleware reqTypes m a swapMonad liftLower (RegistryT subReg) = do parentSt <- get basePath <- ask (a, parentSt', middleware') <- lift $ liftLower $ runRWST subReg basePath parentSt put parentSt' tell middleware' return a runRegistry :: (Monad m, Hashable reqTypes, Eq reqTypes) => RegistryT n b middleware reqTypes m a -> m (a, reqTypes -> [T.Text] -> [n b], [middleware]) runRegistry (RegistryT rwst) = do (val, st, w) <- runRWST rwst PI_Empty initSt return (val, handleF (rs_anyMethod st) (rs_registry st), w) where handleF anyReg hm ty route = let froute = filter (not . T.null) route in case HM.lookup ty hm of Nothing -> matchRoute anyReg froute Just registry -> (matchRoute registry froute ++ matchRoute anyReg froute) initSt = RegistryState { rs_registry = HM.empty, rs_anyMethod = emptyRegistry }
agrafix/Spock
reroute/src/Web/Routing/Router.hs
bsd-3-clause
3,544
0
19
920
1,189
619
570
115
2
-- -- Solution: solution of one position on the board -- module Sudoku.Solution ( Position , Value , Solution , posToXy , xyToPos , solutionX , solutionY , solutionVal ) where import Data.Maybe import Sudoku.Config type Position = Int type Value = Int type Solution = (Position, Value) posToXy :: Position -> Maybe (Int, Int) posToXy pos | pos < 0 = Nothing | pos >= boardSize^2 = Nothing | otherwise = Just (x, y) where x = pos `mod` boardSize + 1 y = pos `div` boardSize + 1 xyToPos :: (Int, Int) -> Maybe Position xyToPos (x,y) | p < 0 = Nothing | p >= boardSize^2 = Nothing | otherwise = Just p where p = (x - 1) + (y - 1) * boardSize solutionX :: Solution -> Maybe Int solutionX (p, v) | xy == Nothing = Nothing | otherwise = Just (fst (fromJust(xy))) where xy = posToXy p solutionY :: Solution -> Maybe Int solutionY (p, v) | xy == Nothing = Nothing | otherwise = Just (snd (fromJust(xy))) where xy = posToXy p solutionVal :: Solution -> Value solutionVal (p, v) = v
eiji-a/sudoku
src/Sudoku/Solution.hs
bsd-3-clause
1,084
0
11
301
441
236
205
39
1
{-| Module : Data.Algorithm.PPattern.Perm.Random Description : Short description Copyright : (c) Laurent Bulteau, Romeo Rizzi, Stéphane Vialette, 2016-2017 License : MIT Maintainer : vialette@gmaiList.com Stability : experimental Random permutations -} module Data.Algorithm.PPattern.Perm.Random ( -- * generating rand, rand' ) where import qualified System.Random import qualified Data.Algorithm.PPattern.Perm as Perm import qualified Data.Algorithm.PPattern.Random as Random {-| 'rand' takes a permutation 'p' and a random generator 'g', and returns a random permutation of 'p', together with a new generatoRandom. -} rand :: System.Random.RandomGen g => Perm.Perm -> g -> (Perm.Perm, g) rand p g = (Perm.fromList xs, g') where (xs, g') = Random.randPerm (Perm.points p) g {-| 'rand'' takes an integer 'n' and a random generator 'g', and returns a random permutation of '[1..n]', together with a new random generator. -} rand' :: System.Random.RandomGen g => Int -> g -> (Perm.Perm, g) rand' n = rand p where p = Perm.mk [1..n]
vialette/ppattern
src/Data/Algorithm/PPattern/Perm/Random.hs
mit
1,123
0
10
241
189
111
78
13
1
module DataMining.LargeScaleLearning.Macro where import Types import Functions.Application.Macro -- * Regret -- | Regret sign regsign :: Note regsign = "R" -- | Regret reg :: Note -> Note reg = fn regsign -- | Optimal feasable fixed point opt :: Note -> Note opt = fn "OPT" -- | Average regret areg :: Note -> Note areg = fn $ overline regsign
NorfairKing/the-notes
src/DataMining/LargeScaleLearning/Macro.hs
gpl-2.0
371
0
6
89
86
51
35
11
1
{-# LANGUAGE TemplateHaskell #-} {-| Utility Template Haskell functions for working with types. -} {- Copyright (C) 2013 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 Ganeti.THH.Types ( typeOfFun , funArgs , tupleArgs , argumentType , uncurryVarType , uncurryVar , curryN , OneTuple(..) ) where import Control.Arrow (first) import Control.Monad (liftM, replicateM) import Language.Haskell.TH import qualified Text.JSON as J -- | This fills the gap between @()@ and @(,)@, providing a wrapper for -- 1-element tuples. It's needed for RPC, where arguments for a function are -- sent as a list of values, and therefore for 1-argument functions we need -- this wrapper, which packs/unpacks 1-element lists. newtype OneTuple a = OneTuple { getOneTuple :: a } deriving (Eq, Ord, Show) instance Functor OneTuple where fmap f (OneTuple x) = OneTuple (f x) -- The value is stored in @JSON@ as a 1-element list. instance J.JSON a => J.JSON (OneTuple a) where showJSON (OneTuple a) = J.JSArray [J.showJSON a] readJSON (J.JSArray [x]) = liftM OneTuple (J.readJSON x) readJSON _ = J.Error "Unable to read 1 tuple" -- | Returns the type of a function. If the given name doesn't correspond to a -- function, fails. typeOfFun :: Name -> Q Type typeOfFun name = reify name >>= args where args :: Info -> Q Type args (VarI _ tp _ _) = return tp args _ = fail $ "Not a function: " ++ show name -- | Splits a function type into the types of its arguments and the result. funArgs :: Type -> ([Type], Type) funArgs = first reverse . f [] where f ts (ForallT _ _ x) = f ts x f ts (AppT (AppT ArrowT t) x) = f (t:ts) x f ts x = (ts, x) tupleArgs :: Type -> Maybe [Type] tupleArgs = fmap reverse . f [] where f ts (TupleT _) = Just ts f ts (AppT (AppT ArrowT x) t) = f (t:ts) x f _ _ = Nothing -- | Given a type of the form @m a@, this function extracts @a@. -- If the given type is of another form, it fails with an error message. argumentType :: Type -> Q Type argumentType (AppT _ t) = return t argumentType t = fail $ "Not a type of the form 'm a': " ++ show t -- | Generic 'uncurry' that counts the number of function arguments in a type -- and constructs the appropriate uncurry function into @i -> o@. -- It the type has no arguments, it's converted into @() -> o@. uncurryVarType :: Type -> Q Exp uncurryVarType = uncurryN . length . fst . funArgs where uncurryN 0 = do f <- newName "f" return $ LamE [VarP f, TupP []] (VarE f) uncurryN 1 = [| (. getOneTuple) |] uncurryN n = do f <- newName "f" ps <- replicateM n (newName "x") return $ LamE [VarP f, TupP $ map VarP ps] (foldl AppE (VarE f) $ map VarE ps) -- | Creates an uncurried version of a function. -- If the function has no arguments, it's converted into @() -> o@. uncurryVar :: Name -> Q Exp uncurryVar name = do t <- typeOfFun name appE (uncurryVarType t) (varE name) -- | Generic 'curry' that constructs a curring function of a given arity. curryN :: Int -> Q Exp curryN 0 = [| ($ ()) |] curryN 1 = [| (. OneTuple) |] curryN n = do f <- newName "f" ps <- replicateM n (newName "x") return $ LamE (VarP f : map VarP ps) (AppE (VarE f) (TupE $ map VarE ps))
kawamuray/ganeti
src/Ganeti/THH/Types.hs
gpl-2.0
4,045
0
15
1,001
956
494
462
63
3
{-# LANGUAGE DeriveFunctor, DeriveFoldable, LambdaCase, TypeFamilies #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveTraversable #-} module HN.Intermediate (Const(..), Definition(..), Expression(..), ASTDefinition, ASTExpression, ASTLetIn, ExpressionList, GType, letWhere, letValue, makeLet, ExpressionF(..), LetIn(..), LetInF(..), Root, DefinitionBase(..), UTermF(..)) where import qualified Data.Set as S import Data.Functor.Foldable import Data.Functor.Foldable.TH import Control.Unification import Parser.AST import SPL.Types (T) type Program = [Definition String] type ASTLetIn = LetIn String letValue (Let _ l) = letValue l letValue (In v) = v letWhere (Let d l) = d : letWhere l letWhere (In _) = [] type ASTDefinition = Definition String data DefinitionBase a b = DefinitionF a [a] (Expression a) [b] | AssignF a (Expression a) [b] deriving (Show, Functor) type instance Base (Definition a) = DefinitionBase a instance Recursive (Definition a) where project x = case x of Definition a b l -> DefinitionF a b (letValue l) (letWhere l) Assign a l -> AssignF a (letValue l) (letWhere l) instance Corecursive (Definition a) where embed x = case x of DefinitionF name args value prg -> Definition name args $ makeLet value prg AssignF name value prg -> Assign name $ makeLet value prg type ASTExpression = Expression String type ExpressionList = [ASTExpression] type GType = (S.Set String, T) type Root = Program data UTermF t v a = UVarF v | UTermF (t a) deriving (Show, Functor, Traversable, Foldable) type instance Base (UTerm t v) = UTermF t v instance Functor t => Recursive (UTerm t v) where project = \case UVar a -> UVarF a UTerm a -> UTermF a instance Functor t => Corecursive (UTerm t v) where embed = \case UVarF a -> UVar a UTermF a -> UTerm a makeBaseFunctor ''Expression makeBaseFunctor ''LetIn
kayuri/HNC
HN/Intermediate.hs
lgpl-3.0
1,861
4
11
323
718
387
331
46
1
{-# LANGUAGE CPP #-} module Network.Bluetooth.Protocol ( #if defined(mingw32_HOST_OS) module Network.Bluetooth.Windows.Protocol #elif defined(darwin_HOST_OS) module Network.Bluetooth.OSX.Protocol #elif defined(linux_HOST_OS) module Network.Bluetooth.Linux.Protocol #elif defined(freebsd_HOST_OS) module Network.Bluetooth.FreeBSD.Protocol #endif ) where #if defined(mingw32_HOST_OS) import Network.Bluetooth.Windows.Protocol #elif defined(darwin_HOST_OS) import Network.Bluetooth.OSX.Protocol #elif defined(linux_HOST_OS) import Network.Bluetooth.Linux.Protocol #elif defined(freebsd_HOST_OS) import Network.Bluetooth.FreeBSD.Protocol #endif
RyanGlScott/bluetooth
src/Network/Bluetooth/Protocol.hs
bsd-3-clause
673
0
5
75
30
23
7
2
0
module Language.Brainfuck.Buffalo where import Prelude () import Language.Brainfuck.Internals.GenericParser program :: GenericParser program = genparser Symbols { incr = "buffalo buffalo", decr = "buffalo Buffalo", right = "Buffalo buffalo", left = "Buffalo Buffalo", read = "Buffalo Buuffalo", print = "buffalo Buuffalo", openl = "Buuffalo Buuffalo", closel = "Buuffalo buuffalo", reserved = "bBuffalo" }
remusao/Hodor
src/Language/Brainfuck/Buffalo.hs
bsd-3-clause
472
0
7
118
89
58
31
14
1
-------------------------------------------------------------------------------- module Language.Haskell.Stylish.Step ( Lines , Module , Step (..) , makeStep ) where -------------------------------------------------------------------------------- import qualified Language.Haskell.Exts.Annotated as H -------------------------------------------------------------------------------- type Lines = [String] -------------------------------------------------------------------------------- -- | Concrete module type type Module = (H.Module H.SrcSpanInfo, [H.Comment]) -------------------------------------------------------------------------------- data Step = Step { stepName :: String , stepFilter :: Lines -> Module -> Lines } -------------------------------------------------------------------------------- makeStep :: String -> (Lines -> Module -> Lines) -> Step makeStep = Step
eigengrau/stylish-haskell
src/Language/Haskell/Stylish/Step.hs
bsd-3-clause
923
0
10
114
134
86
48
13
1
module Main ( main ) where import Prelude hiding (lookup) import System.Environment (getArgs) import System.Exit import Moo.Core import Moo.Main main :: IO () main = do args <- getArgs (_, opts, _) <- procArgs args conf <- loadConfiguration $ _configFilePath opts case conf of Left e -> putStrLn e >> exitFailure Right c -> mainWithConf args c
nathankot/dbmigrations
programs/Moo.hs
bsd-3-clause
381
0
11
94
135
70
65
15
2
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Haddock -- Copyright : Isaac Jones 2003-2005 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This module deals with the @haddock@ and @hscolour@ commands. -- It uses information about installed packages (from @ghc-pkg@) to find the -- locations of documentation for dependent packages, so it can create links. -- -- The @hscolour@ support allows generating HTML versions of the original -- source, with coloured syntax highlighting. module Distribution.Simple.Haddock ( haddock, hscolour, haddockPackagePaths ) where import qualified Distribution.Simple.GHC as GHC import qualified Distribution.Simple.GHCJS as GHCJS -- local import Distribution.Package ( PackageIdentifier(..) , Package(..) , PackageName(..), packageName, LibraryName(..) ) import qualified Distribution.ModuleName as ModuleName import Distribution.PackageDescription as PD ( PackageDescription(..), BuildInfo(..), usedExtensions , hcSharedOptions , Library(..), hasLibs, Executable(..) , TestSuite(..), TestSuiteInterface(..) , Benchmark(..), BenchmarkInterface(..) ) import Distribution.Simple.Compiler ( Compiler, compilerInfo, CompilerFlavor(..) , compilerFlavor, compilerCompatVersion ) import Distribution.Simple.Program.GHC ( GhcOptions(..), GhcDynLinkMode(..), renderGhcOptions ) import Distribution.Simple.Program ( ConfiguredProgram(..), lookupProgramVersion, requireProgramVersion , rawSystemProgram, rawSystemProgramStdout , hscolourProgram, haddockProgram ) import Distribution.Simple.PreProcess ( PPSuffixHandler, preprocessComponent) import Distribution.Simple.Setup ( defaultHscolourFlags , Flag(..), toFlag, flagToMaybe, flagToList, fromFlag , HaddockFlags(..), HscolourFlags(..) ) import Distribution.Simple.Build (initialBuildSteps) import Distribution.Simple.InstallDirs ( InstallDirs(..) , PathTemplateEnv, PathTemplate, PathTemplateVariable(..) , toPathTemplate, fromPathTemplate , substPathTemplate, initialPathTemplateEnv ) import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..), Component(..), ComponentLocalBuildInfo(..) , withAllComponentsInBuildOrder ) import Distribution.Simple.BuildPaths ( haddockName, hscolourPref, autogenModulesDir) import Distribution.Simple.PackageIndex (dependencyClosure) import qualified Distribution.Simple.PackageIndex as PackageIndex import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo ( InstalledPackageInfo_(..) ) import Distribution.InstalledPackageInfo ( InstalledPackageInfo ) import Distribution.Simple.Utils ( die, copyFileTo, warn, notice, intercalate, setupMessage , createDirectoryIfMissingVerbose , TempFileOptions(..), defaultTempFileOptions , withTempFileEx, copyFileVerbose , withTempDirectoryEx, matchFileGlob , findFileWithExtension, findFile ) import Distribution.Text ( display, simpleParse ) import Distribution.Utils.NubList ( toNubListR ) import Distribution.Verbosity import Language.Haskell.Extension import Control.Monad ( when, forM_ ) import Data.Either ( rights ) import Data.Foldable ( traverse_ ) import Data.Monoid import Data.Maybe ( fromMaybe, listToMaybe ) import System.Directory (doesFileExist) import System.FilePath ( (</>), (<.>) , normalise, splitPath, joinPath, isAbsolute ) import System.IO (hClose, hPutStrLn, hSetEncoding, utf8) import Distribution.Version -- ------------------------------------------------------------------------------ -- Types -- | A record that represents the arguments to the haddock executable, a product -- monoid. data HaddockArgs = HaddockArgs { argInterfaceFile :: Flag FilePath, -- ^ Path to the interface file, relative to argOutputDir, required. argPackageName :: Flag PackageIdentifier, -- ^ Package name, required. argHideModules :: (All,[ModuleName.ModuleName]), -- ^ (Hide modules ?, modules to hide) argIgnoreExports :: Any, -- ^ Ignore export lists in modules? argLinkSource :: Flag (Template,Template,Template), -- ^ (Template for modules, template for symbols, template for lines). argCssFile :: Flag FilePath, -- ^ Optional custom CSS file. argContents :: Flag String, -- ^ Optional URL to contents page. argVerbose :: Any, argOutput :: Flag [Output], -- ^ HTML or Hoogle doc or both? Required. argInterfaces :: [(FilePath, Maybe String)], -- ^ [(Interface file, URL to the HTML docs for links)]. argOutputDir :: Directory, -- ^ Where to generate the documentation. argTitle :: Flag String, -- ^ Page title, required. argPrologue :: Flag String, -- ^ Prologue text, required. argGhcOptions :: Flag (GhcOptions, Version), -- ^ Additional flags to pass to GHC. argGhcLibDir :: Flag FilePath, -- ^ To find the correct GHC, required. argTargets :: [FilePath] -- ^ Modules to process. } -- | The FilePath of a directory, it's a monoid under '(</>)'. newtype Directory = Dir { unDir' :: FilePath } deriving (Read,Show,Eq,Ord) unDir :: Directory -> FilePath unDir = joinPath . filter (\p -> p /="./" && p /= ".") . splitPath . unDir' type Template = String data Output = Html | Hoogle -- ------------------------------------------------------------------------------ -- Haddock support haddock :: PackageDescription -> LocalBuildInfo -> [PPSuffixHandler] -> HaddockFlags -> IO () haddock pkg_descr _ _ haddockFlags | not (hasLibs pkg_descr) && not (fromFlag $ haddockExecutables haddockFlags) && not (fromFlag $ haddockTestSuites haddockFlags) && not (fromFlag $ haddockBenchmarks haddockFlags) = warn (fromFlag $ haddockVerbosity haddockFlags) $ "No documentation was generated as this package does not contain " ++ "a library. Perhaps you want to use the --executables, --tests or" ++ " --benchmarks flags." haddock pkg_descr lbi suffixes flags = do setupMessage verbosity "Running Haddock for" (packageId pkg_descr) (confHaddock, version, _) <- requireProgramVersion verbosity haddockProgram (orLaterVersion (Version [2,0] [])) (withPrograms lbi) -- various sanity checks when ( flag haddockHoogle && version < Version [2,2] []) $ die "haddock 2.0 and 2.1 do not support the --hoogle flag." haddockGhcVersionStr <- rawSystemProgramStdout verbosity confHaddock ["--ghc-version"] case (simpleParse haddockGhcVersionStr, compilerCompatVersion GHC comp) of (Nothing, _) -> die "Could not get GHC version from Haddock" (_, Nothing) -> die "Could not get GHC version from compiler" (Just haddockGhcVersion, Just ghcVersion) | haddockGhcVersion == ghcVersion -> return () | otherwise -> die $ "Haddock's internal GHC version must match the configured " ++ "GHC version.\n" ++ "The GHC version is " ++ display ghcVersion ++ " but " ++ "haddock is using GHC version " ++ display haddockGhcVersion -- the tools match the requests, we can proceed initialBuildSteps (flag haddockDistPref) pkg_descr lbi verbosity when (flag haddockHscolour) $ hscolour' (warn verbosity) pkg_descr lbi suffixes (defaultHscolourFlags `mappend` haddockToHscolour flags) libdirArgs <- getGhcLibDir verbosity lbi let commonArgs = mconcat [ libdirArgs , fromFlags (haddockTemplateEnv lbi (packageId pkg_descr)) flags , fromPackageDescription pkg_descr ] let pre c = preprocessComponent pkg_descr c lbi False verbosity suffixes withAllComponentsInBuildOrder pkg_descr lbi $ \component clbi -> do pre component let doExe com = case (compToExe com) of Just exe -> do withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $ \tmp -> do exeArgs <- fromExecutable verbosity tmp lbi exe clbi htmlTemplate version let exeArgs' = commonArgs `mappend` exeArgs runHaddock verbosity tmpFileOpts comp confHaddock exeArgs' Nothing -> do warn (fromFlag $ haddockVerbosity flags) "Unsupported component, skipping..." return () case component of CLib lib -> do withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $ \tmp -> do libArgs <- fromLibrary verbosity tmp lbi lib clbi htmlTemplate version let libArgs' = commonArgs `mappend` libArgs runHaddock verbosity tmpFileOpts comp confHaddock libArgs' CExe _ -> when (flag haddockExecutables) $ doExe component CTest _ -> when (flag haddockTestSuites) $ doExe component CBench _ -> when (flag haddockBenchmarks) $ doExe component forM_ (extraDocFiles pkg_descr) $ \ fpath -> do files <- matchFileGlob fpath forM_ files $ copyFileTo verbosity (unDir $ argOutputDir commonArgs) where verbosity = flag haddockVerbosity keepTempFiles = flag haddockKeepTempFiles comp = compiler lbi tmpFileOpts = defaultTempFileOptions { optKeepTempFiles = keepTempFiles } flag f = fromFlag $ f flags htmlTemplate = fmap toPathTemplate . flagToMaybe . haddockHtmlLocation $ flags -- ------------------------------------------------------------------------------ -- Contributions to HaddockArgs. fromFlags :: PathTemplateEnv -> HaddockFlags -> HaddockArgs fromFlags env flags = mempty { argHideModules = (maybe mempty (All . not) $ flagToMaybe (haddockInternal flags), mempty), argLinkSource = if fromFlag (haddockHscolour flags) then Flag ("src/%{MODULE/./-}.html" ,"src/%{MODULE/./-}.html#%{NAME}" ,"src/%{MODULE/./-}.html#line-%{LINE}") else NoFlag, argCssFile = haddockCss flags, argContents = fmap (fromPathTemplate . substPathTemplate env) (haddockContents flags), argVerbose = maybe mempty (Any . (>= deafening)) . flagToMaybe $ haddockVerbosity flags, argOutput = Flag $ case [ Html | Flag True <- [haddockHtml flags] ] ++ [ Hoogle | Flag True <- [haddockHoogle flags] ] of [] -> [ Html ] os -> os, argOutputDir = maybe mempty Dir . flagToMaybe $ haddockDistPref flags } fromPackageDescription :: PackageDescription -> HaddockArgs fromPackageDescription pkg_descr = mempty { argInterfaceFile = Flag $ haddockName pkg_descr, argPackageName = Flag $ packageId $ pkg_descr, argOutputDir = Dir $ "doc" </> "html" </> display (packageName pkg_descr), argPrologue = Flag $ if null desc then synopsis pkg_descr else desc, argTitle = Flag $ showPkg ++ subtitle } where desc = PD.description pkg_descr showPkg = display (packageId pkg_descr) subtitle | null (synopsis pkg_descr) = "" | otherwise = ": " ++ synopsis pkg_descr componentGhcOptions :: Verbosity -> LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> GhcOptions componentGhcOptions verbosity lbi bi clbi odir = let f = case compilerFlavor (compiler lbi) of GHC -> GHC.componentGhcOptions GHCJS -> GHCJS.componentGhcOptions _ -> error $ "Distribution.Simple.Haddock.componentGhcOptions:" ++ "haddock only supports GHC and GHCJS" in f verbosity lbi bi clbi odir fromLibrary :: Verbosity -> FilePath -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> Maybe PathTemplate -- ^ template for HTML location -> Version -> IO HaddockArgs fromLibrary verbosity tmp lbi lib clbi htmlTemplate haddockVersion = do inFiles <- map snd `fmap` getLibSourceFiles lbi lib ifaceArgs <- getInterfaces verbosity lbi clbi htmlTemplate let vanillaOpts = (componentGhcOptions normal lbi bi clbi (buildDir lbi)) { -- Noooooooooo!!!!!111 -- haddock stomps on our precious .hi -- and .o files. Workaround by telling -- haddock to write them elsewhere. ghcOptObjDir = toFlag tmp, ghcOptHiDir = toFlag tmp, ghcOptStubDir = toFlag tmp } `mappend` getGhcCppOpts haddockVersion bi sharedOpts = vanillaOpts { ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptFPic = toFlag True, ghcOptHiSuffix = toFlag "dyn_hi", ghcOptObjSuffix = toFlag "dyn_o", ghcOptExtra = toNubListR $ hcSharedOptions GHC bi } opts <- if withVanillaLib lbi then return vanillaOpts else if withSharedLib lbi then return sharedOpts else die $ "Must have vanilla or shared libraries " ++ "enabled in order to run haddock" ghcVersion <- maybe (die "Compiler has no GHC version") return (compilerCompatVersion GHC (compiler lbi)) return ifaceArgs { argHideModules = (mempty,otherModules $ bi), argGhcOptions = toFlag (opts, ghcVersion), argTargets = inFiles } where bi = libBuildInfo lib fromExecutable :: Verbosity -> FilePath -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> Maybe PathTemplate -- ^ template for HTML location -> Version -> IO HaddockArgs fromExecutable verbosity tmp lbi exe clbi htmlTemplate haddockVersion = do inFiles <- map snd `fmap` getExeSourceFiles lbi exe ifaceArgs <- getInterfaces verbosity lbi clbi htmlTemplate let vanillaOpts = (componentGhcOptions normal lbi bi clbi (buildDir lbi)) { -- Noooooooooo!!!!!111 -- haddock stomps on our precious .hi -- and .o files. Workaround by telling -- haddock to write them elsewhere. ghcOptObjDir = toFlag tmp, ghcOptHiDir = toFlag tmp, ghcOptStubDir = toFlag tmp } `mappend` getGhcCppOpts haddockVersion bi sharedOpts = vanillaOpts { ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptFPic = toFlag True, ghcOptHiSuffix = toFlag "dyn_hi", ghcOptObjSuffix = toFlag "dyn_o", ghcOptExtra = toNubListR $ hcSharedOptions GHC bi } opts <- if withVanillaLib lbi then return vanillaOpts else if withSharedLib lbi then return sharedOpts else die $ "Must have vanilla or shared libraries " ++ "enabled in order to run haddock" ghcVersion <- maybe (die "Compiler has no GHC version") return (compilerCompatVersion GHC (compiler lbi)) return ifaceArgs { argGhcOptions = toFlag (opts, ghcVersion), argOutputDir = Dir (exeName exe), argTitle = Flag (exeName exe), argTargets = inFiles } where bi = buildInfo exe compToExe :: Component -> Maybe Executable compToExe comp = case comp of CTest test@TestSuite { testInterface = TestSuiteExeV10 _ f } -> Just Executable { exeName = testName test, modulePath = f, buildInfo = testBuildInfo test } CBench bench@Benchmark { benchmarkInterface = BenchmarkExeV10 _ f } -> Just Executable { exeName = benchmarkName bench, modulePath = f, buildInfo = benchmarkBuildInfo bench } CExe exe -> Just exe _ -> Nothing getInterfaces :: Verbosity -> LocalBuildInfo -> ComponentLocalBuildInfo -> Maybe PathTemplate -- ^ template for HTML location -> IO HaddockArgs getInterfaces verbosity lbi clbi htmlTemplate = do (packageFlags, warnings) <- haddockPackageFlags lbi clbi htmlTemplate traverse_ (warn verbosity) warnings return $ mempty { argInterfaces = packageFlags } getGhcCppOpts :: Version -> BuildInfo -> GhcOptions getGhcCppOpts haddockVersion bi = mempty { ghcOptExtensions = toNubListR [EnableExtension CPP | needsCpp], ghcOptCppOptions = toNubListR defines } where needsCpp = EnableExtension CPP `elem` usedExtensions bi defines = [haddockVersionMacro] haddockVersionMacro = "-D__HADDOCK_VERSION__=" ++ show (v1 * 1000 + v2 * 10 + v3) where [v1, v2, v3] = take 3 $ versionBranch haddockVersion ++ [0,0] getGhcLibDir :: Verbosity -> LocalBuildInfo -> IO HaddockArgs getGhcLibDir verbosity lbi = do l <- case compilerFlavor (compiler lbi) of GHC -> GHC.getLibDir verbosity lbi GHCJS -> GHCJS.getLibDir verbosity lbi _ -> error "haddock only supports GHC and GHCJS" return $ mempty { argGhcLibDir = Flag l } -- ------------------------------------------------------------------------------ -- | Call haddock with the specified arguments. runHaddock :: Verbosity -> TempFileOptions -> Compiler -> ConfiguredProgram -> HaddockArgs -> IO () runHaddock verbosity tmpFileOpts comp confHaddock args = do let haddockVersion = fromMaybe (error "unable to determine haddock version") (programVersion confHaddock) renderArgs verbosity tmpFileOpts haddockVersion comp args $ \(flags,result)-> do rawSystemProgram verbosity confHaddock flags notice verbosity $ "Documentation created: " ++ result renderArgs :: Verbosity -> TempFileOptions -> Version -> Compiler -> HaddockArgs -> (([String], FilePath) -> IO a) -> IO a renderArgs verbosity tmpFileOpts version comp args k = do let haddockSupportsUTF8 = version >= Version [2,14,4] [] haddockSupportsResponseFiles = version > Version [2,16,1] [] createDirectoryIfMissingVerbose verbosity True outputDir withTempFileEx tmpFileOpts outputDir "haddock-prologue.txt" $ \prologueFileName h -> do do when haddockSupportsUTF8 (hSetEncoding h utf8) hPutStrLn h $ fromFlag $ argPrologue args hClose h let pflag = "--prologue=" ++ prologueFileName renderedArgs = pflag : renderPureArgs version comp args if haddockSupportsResponseFiles then withTempFileEx tmpFileOpts outputDir "haddock-response.txt" $ \responseFileName hf -> do when haddockSupportsUTF8 (hSetEncoding hf utf8) mapM_ (hPutStrLn hf) renderedArgs hClose hf let respFile = "@" ++ responseFileName k ([respFile], result) else k (renderedArgs, result) where outputDir = (unDir $ argOutputDir args) result = intercalate ", " . map (\o -> outputDir </> case o of Html -> "index.html" Hoogle -> pkgstr <.> "txt") $ arg argOutput where pkgstr = display $ packageName pkgid pkgid = arg argPackageName arg f = fromFlag $ f args renderPureArgs :: Version -> Compiler -> HaddockArgs -> [String] renderPureArgs version comp args = concat [ (:[]) . (\f -> "--dump-interface="++ unDir (argOutputDir args) </> f) . fromFlag . argInterfaceFile $ args , if isVersion 2 16 then (\pkg -> [ "--package-name=" ++ display (pkgName pkg) , "--package-version="++display (pkgVersion pkg) ]) . fromFlag . argPackageName $ args else [] , (\(All b,xs) -> bool (map (("--hide=" ++). display) xs) [] b) . argHideModules $ args , bool ["--ignore-all-exports"] [] . getAny . argIgnoreExports $ args , maybe [] (\(m,e,l) -> ["--source-module=" ++ m ,"--source-entity=" ++ e] ++ if isVersion 2 14 then ["--source-entity-line=" ++ l] else [] ) . flagToMaybe . argLinkSource $ args , maybe [] ((:[]) . ("--css="++)) . flagToMaybe . argCssFile $ args , maybe [] ((:[]) . ("--use-contents="++)) . flagToMaybe . argContents $ args , bool [] [verbosityFlag] . getAny . argVerbose $ args , map (\o -> case o of Hoogle -> "--hoogle"; Html -> "--html") . fromFlag . argOutput $ args , renderInterfaces . argInterfaces $ args , (:[]) . ("--odir="++) . unDir . argOutputDir $ args , (:[]) . ("--title="++) . (bool (++" (internal documentation)") id (getAny $ argIgnoreExports args)) . fromFlag . argTitle $ args , [ "--optghc=" ++ opt | (opts, _ghcVer) <- flagToList (argGhcOptions args) , opt <- renderGhcOptions comp opts ] , maybe [] (\l -> ["-B"++l]) $ flagToMaybe (argGhcLibDir args) -- error if Nothing? , argTargets $ args ] where renderInterfaces = map (\(i,mh) -> "--read-interface=" ++ maybe "" (++",") mh ++ i) bool a b c = if c then a else b isVersion major minor = version >= Version [major,minor] [] verbosityFlag | isVersion 2 5 = "--verbosity=1" | otherwise = "--verbose" --------------------------------------------------------------------------------- -- | Given a list of 'InstalledPackageInfo's, return a list of interfaces and -- HTML paths, and an optional warning for packages with missing documentation. haddockPackagePaths :: [InstalledPackageInfo] -> Maybe (InstalledPackageInfo -> FilePath) -> IO ([(FilePath, Maybe FilePath)], Maybe String) haddockPackagePaths ipkgs mkHtmlPath = do interfaces <- sequence [ case interfaceAndHtmlPath ipkg of Nothing -> return (Left (packageId ipkg)) Just (interface, html) -> do exists <- doesFileExist interface if exists then return (Right (interface, html)) else return (Left pkgid) | ipkg <- ipkgs, let pkgid = packageId ipkg , pkgName pkgid `notElem` noHaddockWhitelist ] let missing = [ pkgid | Left pkgid <- interfaces ] warning = "The documentation for the following packages are not " ++ "installed. No links will be generated to these packages: " ++ intercalate ", " (map display missing) flags = rights interfaces return (flags, if null missing then Nothing else Just warning) where -- Don't warn about missing documentation for these packages. See #1231. noHaddockWhitelist = map PackageName [ "rts" ] -- Actually extract interface and HTML paths from an 'InstalledPackageInfo'. interfaceAndHtmlPath :: InstalledPackageInfo -> Maybe (FilePath, Maybe FilePath) interfaceAndHtmlPath pkg = do interface <- listToMaybe (InstalledPackageInfo.haddockInterfaces pkg) html <- case mkHtmlPath of Nothing -> fmap fixFileUrl (listToMaybe (InstalledPackageInfo.haddockHTMLs pkg)) Just mkPath -> Just (mkPath pkg) return (interface, if null html then Nothing else Just html) where -- The 'haddock-html' field in the hc-pkg output is often set as a -- native path, but we need it as a URL. See #1064. fixFileUrl f | isAbsolute f = "file://" ++ f | otherwise = f haddockPackageFlags :: LocalBuildInfo -> ComponentLocalBuildInfo -> Maybe PathTemplate -> IO ([(FilePath, Maybe FilePath)], Maybe String) haddockPackageFlags lbi clbi htmlTemplate = do let allPkgs = installedPkgs lbi directDeps = map fst (componentPackageDeps clbi) transitiveDeps <- case dependencyClosure allPkgs directDeps of Left x -> return x Right inf -> die $ "internal error when calculating transitive " ++ "package dependencies.\nDebug info: " ++ show inf haddockPackagePaths (PackageIndex.allPackages transitiveDeps) mkHtmlPath where mkHtmlPath = fmap expandTemplateVars htmlTemplate expandTemplateVars tmpl pkg = fromPathTemplate . substPathTemplate (env pkg) $ tmpl env pkg = haddockTemplateEnv lbi (packageId pkg) haddockTemplateEnv :: LocalBuildInfo -> PackageIdentifier -> PathTemplateEnv haddockTemplateEnv lbi pkg_id = (PrefixVar, prefix (installDirTemplates lbi)) : initialPathTemplateEnv pkg_id (LibraryName (display pkg_id)) (compilerInfo (compiler lbi)) (hostPlatform lbi) -- ------------------------------------------------------------------------------ -- hscolour support. hscolour :: PackageDescription -> LocalBuildInfo -> [PPSuffixHandler] -> HscolourFlags -> IO () hscolour pkg_descr lbi suffixes flags = do -- we preprocess even if hscolour won't be found on the machine -- will this upset someone? initialBuildSteps distPref pkg_descr lbi verbosity hscolour' die pkg_descr lbi suffixes flags where verbosity = fromFlag (hscolourVerbosity flags) distPref = fromFlag $ hscolourDistPref flags hscolour' :: (String -> IO ()) -- ^ Called when the 'hscolour' exe is not found. -> PackageDescription -> LocalBuildInfo -> [PPSuffixHandler] -> HscolourFlags -> IO () hscolour' onNoHsColour pkg_descr lbi suffixes flags = either onNoHsColour (\(hscolourProg, _, _) -> go hscolourProg) =<< lookupProgramVersion verbosity hscolourProgram (orLaterVersion (Version [1,8] [])) (withPrograms lbi) where go :: ConfiguredProgram -> IO () go hscolourProg = do setupMessage verbosity "Running hscolour for" (packageId pkg_descr) createDirectoryIfMissingVerbose verbosity True $ hscolourPref distPref pkg_descr let pre c = preprocessComponent pkg_descr c lbi False verbosity suffixes withAllComponentsInBuildOrder pkg_descr lbi $ \comp _ -> do pre comp let doExe com = case (compToExe com) of Just exe -> do let outputDir = hscolourPref distPref pkg_descr </> exeName exe </> "src" runHsColour hscolourProg outputDir =<< getExeSourceFiles lbi exe Nothing -> do warn (fromFlag $ hscolourVerbosity flags) "Unsupported component, skipping..." return () case comp of CLib lib -> do let outputDir = hscolourPref distPref pkg_descr </> "src" runHsColour hscolourProg outputDir =<< getLibSourceFiles lbi lib CExe _ -> when (fromFlag (hscolourExecutables flags)) $ doExe comp CTest _ -> when (fromFlag (hscolourTestSuites flags)) $ doExe comp CBench _ -> when (fromFlag (hscolourBenchmarks flags)) $ doExe comp stylesheet = flagToMaybe (hscolourCSS flags) verbosity = fromFlag (hscolourVerbosity flags) distPref = fromFlag (hscolourDistPref flags) runHsColour prog outputDir moduleFiles = do createDirectoryIfMissingVerbose verbosity True outputDir case stylesheet of -- copy the CSS file Nothing | programVersion prog >= Just (Version [1,9] []) -> rawSystemProgram verbosity prog ["-print-css", "-o" ++ outputDir </> "hscolour.css"] | otherwise -> return () Just s -> copyFileVerbose verbosity s (outputDir </> "hscolour.css") forM_ moduleFiles $ \(m, inFile) -> rawSystemProgram verbosity prog ["-css", "-anchor", "-o" ++ outFile m, inFile] where outFile m = outputDir </> intercalate "-" (ModuleName.components m) <.> "html" haddockToHscolour :: HaddockFlags -> HscolourFlags haddockToHscolour flags = HscolourFlags { hscolourCSS = haddockHscolourCss flags, hscolourExecutables = haddockExecutables flags, hscolourTestSuites = haddockTestSuites flags, hscolourBenchmarks = haddockBenchmarks flags, hscolourVerbosity = haddockVerbosity flags, hscolourDistPref = haddockDistPref flags } --------------------------------------------------------------------------------- -- TODO these should be moved elsewhere. getLibSourceFiles :: LocalBuildInfo -> Library -> IO [(ModuleName.ModuleName, FilePath)] getLibSourceFiles lbi lib = getSourceFiles searchpaths modules where bi = libBuildInfo lib modules = PD.exposedModules lib ++ otherModules bi searchpaths = autogenModulesDir lbi : buildDir lbi : hsSourceDirs bi getExeSourceFiles :: LocalBuildInfo -> Executable -> IO [(ModuleName.ModuleName, FilePath)] getExeSourceFiles lbi exe = do moduleFiles <- getSourceFiles searchpaths modules srcMainPath <- findFile (hsSourceDirs bi) (modulePath exe) return ((ModuleName.main, srcMainPath) : moduleFiles) where bi = buildInfo exe modules = otherModules bi searchpaths = autogenModulesDir lbi : exeBuildDir lbi exe : hsSourceDirs bi getSourceFiles :: [FilePath] -> [ModuleName.ModuleName] -> IO [(ModuleName.ModuleName, FilePath)] getSourceFiles dirs modules = flip mapM modules $ \m -> fmap ((,) m) $ findFileWithExtension ["hs", "lhs"] dirs (ModuleName.toFilePath m) >>= maybe (notFound m) (return . normalise) where notFound module_ = die $ "can't find source for module " ++ display module_ -- | The directory where we put build results for an executable exeBuildDir :: LocalBuildInfo -> Executable -> FilePath exeBuildDir lbi exe = buildDir lbi </> exeName exe </> exeName exe ++ "-tmp" -- ------------------------------------------------------------------------------ -- Boilerplate Monoid instance. instance Monoid HaddockArgs where mempty = HaddockArgs { argInterfaceFile = mempty, argPackageName = mempty, argHideModules = mempty, argIgnoreExports = mempty, argLinkSource = mempty, argCssFile = mempty, argContents = mempty, argVerbose = mempty, argOutput = mempty, argInterfaces = mempty, argOutputDir = mempty, argTitle = mempty, argPrologue = mempty, argGhcOptions = mempty, argGhcLibDir = mempty, argTargets = mempty } mappend a b = HaddockArgs { argInterfaceFile = mult argInterfaceFile, argPackageName = mult argPackageName, argHideModules = mult argHideModules, argIgnoreExports = mult argIgnoreExports, argLinkSource = mult argLinkSource, argCssFile = mult argCssFile, argContents = mult argContents, argVerbose = mult argVerbose, argOutput = mult argOutput, argInterfaces = mult argInterfaces, argOutputDir = mult argOutputDir, argTitle = mult argTitle, argPrologue = mult argPrologue, argGhcOptions = mult argGhcOptions, argGhcLibDir = mult argGhcLibDir, argTargets = mult argTargets } where mult f = f a `mappend` f b instance Monoid Directory where mempty = Dir "." mappend (Dir m) (Dir n) = Dir $ m </> n
rimmington/cabal
Cabal/Distribution/Simple/Haddock.hs
bsd-3-clause
33,325
0
26
10,170
7,477
3,927
3,550
615
7
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ar-SA"> <title>Passive Scan Rules | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>بحث</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/pscanrules/src/main/javahelp/org/zaproxy/zap/extension/pscanrules/resources/help_ar_SA/helpset_ar_SA.hs
apache-2.0
979
80
65
160
413
209
204
-1
-1
module DoExp2 where f x = do t <- getLine putStrLn t g x = do x <- getLine putStrLn x
kmate/HaRe
old/testing/foldDef/DoExpr2.hs
bsd-3-clause
125
0
7
60
46
21
25
7
1
-- | A description of the platform we're compiling for. -- module Platform ( Platform(..), Arch(..), OS(..), ArmISA(..), ArmISAExt(..), ArmABI(..), target32Bit, isARM, osElfTarget, osMachOTarget, platformUsesFrameworks, platformBinariesAreStaticLibs, ) where -- | Contains enough information for the native code generator to emit -- code for this platform. data Platform = Platform { platformArch :: Arch, platformOS :: OS, -- Word size in bytes (i.e. normally 4 or 8, -- for 32bit and 64bit platforms respectively) platformWordSize :: {-# UNPACK #-} !Int, platformUnregisterised :: Bool, platformHasGnuNonexecStack :: Bool, platformHasIdentDirective :: Bool, platformHasSubsectionsViaSymbols :: Bool, platformIsCrossCompiling :: Bool } deriving (Read, Show, Eq) -- | Architectures that the native code generator knows about. -- TODO: It might be nice to extend these constructors with information -- about what instruction set extensions an architecture might support. -- data Arch = ArchUnknown | ArchX86 | ArchX86_64 | ArchPPC | ArchPPC_64 | ArchSPARC | ArchARM { armISA :: ArmISA , armISAExt :: [ArmISAExt] , armABI :: ArmABI } | ArchARM64 | ArchAlpha | ArchMipseb | ArchMipsel | ArchJavaScript deriving (Read, Show, Eq) isARM :: Arch -> Bool isARM (ArchARM {}) = True isARM ArchARM64 = True isARM _ = False -- | Operating systems that the native code generator knows about. -- Having OSUnknown should produce a sensible default, but no promises. data OS = OSUnknown | OSLinux | OSDarwin | OSiOS | OSSolaris2 | OSMinGW32 | OSFreeBSD | OSDragonFly | OSOpenBSD | OSNetBSD | OSKFreeBSD | OSHaiku | OSOsf3 | OSQNXNTO | OSAndroid deriving (Read, Show, Eq) -- | ARM Instruction Set Architecture, Extensions and ABI -- data ArmISA = ARMv5 | ARMv6 | ARMv7 deriving (Read, Show, Eq) data ArmISAExt = VFPv2 | VFPv3 | VFPv3D16 | NEON | IWMMX2 deriving (Read, Show, Eq) data ArmABI = SOFT | SOFTFP | HARD deriving (Read, Show, Eq) target32Bit :: Platform -> Bool target32Bit p = platformWordSize p == 4 -- | This predicates tells us whether the OS supports ELF-like shared libraries. osElfTarget :: OS -> Bool osElfTarget OSLinux = True osElfTarget OSFreeBSD = True osElfTarget OSDragonFly = True osElfTarget OSOpenBSD = True osElfTarget OSNetBSD = True osElfTarget OSSolaris2 = True osElfTarget OSDarwin = False osElfTarget OSiOS = False osElfTarget OSMinGW32 = False osElfTarget OSKFreeBSD = True osElfTarget OSHaiku = True osElfTarget OSOsf3 = False -- I don't know if this is right, but as -- per comment below it's safe osElfTarget OSQNXNTO = False osElfTarget OSAndroid = True osElfTarget OSUnknown = False -- Defaulting to False is safe; it means don't rely on any -- ELF-specific functionality. It is important to have a default for -- portability, otherwise we have to answer this question for every -- new platform we compile on (even unreg). -- | This predicate tells us whether the OS support Mach-O shared libraries. osMachOTarget :: OS -> Bool osMachOTarget OSDarwin = True osMachOTarget _ = False osUsesFrameworks :: OS -> Bool osUsesFrameworks OSDarwin = True osUsesFrameworks OSiOS = True osUsesFrameworks _ = False platformUsesFrameworks :: Platform -> Bool platformUsesFrameworks = osUsesFrameworks . platformOS osBinariesAreStaticLibs :: OS -> Bool osBinariesAreStaticLibs OSiOS = True osBinariesAreStaticLibs _ = False platformBinariesAreStaticLibs :: Platform -> Bool platformBinariesAreStaticLibs = osBinariesAreStaticLibs . platformOS
christiaanb/ghc
compiler/utils/Platform.hs
bsd-3-clause
4,269
0
9
1,342
707
417
290
111
1
module Propellor.Types.Empty where import qualified Data.Map as M import qualified Data.Set as S class Empty t where isEmpty :: t -> Bool instance Empty [a] where isEmpty = null instance Empty (M.Map k v) where isEmpty = M.null instance Empty (S.Set v) where isEmpty = S.null
np/propellor
src/Propellor/Types/Empty.hs
bsd-2-clause
285
0
8
55
105
60
45
11
0
----------------------------------------------------------------------------- -- | -- Module : XMonad.Prompt.Email -- Copyright : (c) 2007 Brent Yorgey -- License : BSD-style (see LICENSE) -- -- Maintainer : <byorgey@gmail.com> -- Stability : stable -- Portability : unportable -- -- A prompt for sending quick, one-line emails, via the standard GNU -- \'mail\' utility (which must be in your $PATH). This module is -- intended mostly as an example of using "XMonad.Prompt.Input" to -- build an action requiring user input. -- ----------------------------------------------------------------------------- module XMonad.Prompt.Email ( -- * Usage -- $usage emailPrompt ) where import XMonad.Core import XMonad.Util.Run import XMonad.Prompt import XMonad.Prompt.Input -- $usage -- -- You can use this module by importing it, along with -- "XMonad.Prompt", into your ~\/.xmonad\/xmonad.hs file: -- -- > import XMonad.Prompt -- > import XMonad.Prompt.Email -- -- and adding an appropriate keybinding, for example: -- -- > , ((modm .|. controlMask, xK_e), emailPrompt def addresses) -- -- where @addresses@ is a list of email addresses that should -- autocomplete, for example: -- -- > addresses = ["me@me.com", "mr@big.com", "tom.jones@foo.bar"] -- -- You can still send email to any address, but sending to these -- addresses will be faster since you only have to type a few -- characters and then hit \'tab\'. -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". -- | Prompt the user for a recipient, subject, and body, and send an -- email via the GNU \'mail\' utility. The second argument is a list -- of addresses for autocompletion. emailPrompt :: XPConfig -> [String] -> X () emailPrompt c addrs = inputPromptWithCompl c "To" (mkComplFunFromList addrs) ?+ \to -> inputPrompt c "Subject" ?+ \subj -> inputPrompt c "Body" ?+ \body -> runProcessWithInput "mail" ["-s", subj, to] (body ++ "\n") >> return ()
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Prompt/Email.hs
bsd-2-clause
2,135
0
14
458
191
124
67
13
1
module Tests.Unicode where import Data.Char {-# NOINLINE str #-} str :: String str = "痴漢は犯罪だ!" runTest :: IO [String] runTest = return [str, str', str'', str'''] where str' = filter (/= 'だ') str str'' = map toUpper str' str''' = map toLower $ str'' ++ " THIS IS ENGLISH"
jtojnar/haste-compiler
Tests/Unicode.hs
bsd-3-clause
307
0
9
69
95
54
41
11
1
{-# OPTIONS -fno-warn-orphans #-} {-# LANGUAGE TemplateHaskell #-} module Lamdu.Config (Layers(..), Config(..), delKeys) where import Data.Aeson (ToJSON(..), FromJSON(..)) import Data.Aeson.TH (deriveJSON, defaultOptions) import Data.Vector.Vector2 (Vector2(..)) import Foreign.C.Types (CDouble) import Graphics.DrawingCombinators.Utils () -- Read instance for Color import qualified Graphics.DrawingCombinators as Draw import qualified Graphics.UI.Bottle.EventMap as E data Layers = Layers { layerCursorBG , layerTypes , layerCollapsedCompactBG , layerCollapsedExpandedBG , layerChoiceBG , layerHoleBG , layerNameCollisionBG , layerLabeledApplyBG , layerParensHighlightBG , layerActivePane , layerMax :: Int } deriving Eq data Config = Config { layers :: Layers , baseColor :: Draw.Color , baseTextSize :: Int , helpTextColor :: Draw.Color , helpTextSize :: Int , helpInputDocColor :: Draw.Color , helpBGColor :: Draw.Color , invalidCursorBGColor :: Draw.Color , quitKeys :: [E.ModKey] , undoKeys :: [E.ModKey] , redoKeys :: [E.ModKey] , makeBranchKeys :: [E.ModKey] , jumpToBranchesKeys :: [E.ModKey] , overlayDocKeys :: [E.ModKey] , addNextParamKeys :: [E.ModKey] , delBranchKeys :: [E.ModKey] , closePaneKeys :: [E.ModKey] , movePaneDownKeys :: [E.ModKey] , movePaneUpKeys :: [E.ModKey] , replaceKeys :: [E.ModKey] , pickResultKeys :: [E.ModKey] , pickAndMoveToNextHoleKeys :: [E.ModKey] , jumpToNextHoleKeys :: [E.ModKey] , jumpToPrevHoleKeys :: [E.ModKey] , jumpToDefinitionKeys :: [E.ModKey] , delForwardKeys :: [E.ModKey] , delBackwardKeys :: [E.ModKey] , wrapKeys :: [E.ModKey] , debugModeKeys :: [E.ModKey] , newDefinitionKeys :: [E.ModKey] , definitionColor :: Draw.Color , atomColor :: Draw.Color , parameterColor :: Draw.Color , paramOriginColor :: Draw.Color , literalIntColor :: Draw.Color , previousCursorKeys :: [E.ModKey] , holeResultCount :: Int , holeResultScaleFactor :: Vector2 Double , holeResultPadding :: Vector2 Double , holeResultInjectedScaleExponent :: Double , holeSearchTermScaleFactor :: Vector2 Double , holeNumLabelScaleFactor :: Vector2 Double , holeNumLabelColor :: Draw.Color , holeInactiveExtraSymbolColor :: Draw.Color , typeErrorHoleWrapBackgroundColor :: Draw.Color , deletableHoleBackgroundColor :: Draw.Color , activeHoleBackgroundColor :: Draw.Color , inactiveHoleBackgroundColor :: Draw.Color , wrapperHolePadding :: Vector2 Double , tagScaleFactor :: Vector2 Double , fieldTagScaleFactor :: Vector2 Double , fieldTint :: Draw.Color , inferredValueScaleFactor :: Vector2 Double , inferredValueTint :: Draw.Color , parenHighlightColor :: Draw.Color , addWhereItemKeys :: [E.ModKey] , lambdaColor :: Draw.Color , lambdaTextSize :: Int , rightArrowColor :: Draw.Color , rightArrowTextSize :: Int , whereColor :: Draw.Color , whereScaleFactor :: Vector2 Double , whereLabelScaleFactor :: Vector2 Double , typeScaleFactor :: Vector2 Double , squareParensScaleFactor :: Vector2 Double , foreignModuleColor :: Draw.Color , foreignVarColor :: Draw.Color , cutKeys :: [E.ModKey] , pasteKeys :: [E.ModKey] , inactiveTintColor :: Draw.Color , activeDefBGColor :: Draw.Color , inferredTypeTint :: Draw.Color , inferredTypeErrorBGColor :: Draw.Color , inferredTypeBGColor :: Draw.Color -- For definitions , collapsedForegroundColor :: Draw.Color -- For parameters , collapsedCompactBGColor :: Draw.Color , collapsedExpandedBGColor :: Draw.Color , collapsedExpandKeys :: [E.ModKey] , collapsedCollapseKeys :: [E.ModKey] , monomorphicDefOriginForegroundColor :: Draw.Color , polymorphicDefOriginForegroundColor :: Draw.Color , builtinOriginNameColor :: Draw.Color , cursorBGColor :: Draw.Color , listBracketTextSize :: Int , listBracketColor :: Draw.Color , listCommaTextSize :: Int , listCommaColor :: Draw.Color , listAddItemKeys :: [E.ModKey] , selectedBranchColor :: Draw.Color , jumpLHStoRHSKeys :: [E.ModKey] , jumpRHStoLHSKeys :: [E.ModKey] , shrinkBaseFontKeys :: [E.ModKey] , enlargeBaseFontKeys :: [E.ModKey] , enlargeFactor :: Double , shrinkFactor :: Double , defTypeLabelTextSize :: Int , defTypeLabelColor :: Draw.Color , defTypeBoxScaleFactor :: Vector2 Double , acceptKeys :: [E.ModKey] , autoGeneratedNameTint :: Draw.Color , collisionSuffixTextColor :: Draw.Color , collisionSuffixBGColor :: Draw.Color , collisionSuffixScaleFactor :: Vector2 Double , paramDefSuffixScaleFactor :: Vector2 Double , enterSubexpressionKeys :: [E.ModKey] , leaveSubexpressionKeys :: [E.ModKey] , nextInfoModeKeys :: [E.ModKey] , recordTypeParensColor :: Draw.Color , recordValParensColor :: Draw.Color , recordAddFieldKeys :: [E.ModKey] , presentationChoiceScaleFactor :: Vector2 Double , presentationChoiceColor :: Draw.Color , labeledApplyBGColor :: Draw.Color , labeledApplyPadding :: Vector2 Double , spaceBetweenAnnotatedArgs :: Double } deriving Eq delKeys :: Config -> [E.ModKey] delKeys config = delForwardKeys config ++ delBackwardKeys config deriveJSON defaultOptions ''Vector2 deriveJSON defaultOptions ''Draw.Color deriveJSON defaultOptions ''E.ModState deriveJSON defaultOptions ''E.ModKey deriveJSON defaultOptions ''E.Key deriveJSON defaultOptions ''Layers deriveJSON defaultOptions ''Config instance FromJSON CDouble where parseJSON = fmap (realToFrac :: Double -> CDouble) . parseJSON instance ToJSON CDouble where toJSON = toJSON . (realToFrac :: CDouble -> Double)
schell/lamdu
Lamdu/Config.hs
gpl-3.0
5,632
0
10
948
1,360
837
523
153
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE BangPatterns, CPP, NoImplicitPrelude #-} module GHC.Event.Array ( Array , capacity , clear , concat , copy , duplicate , empty , ensureCapacity , findIndex , forM_ , length , loop , new , removeAt , snoc , unsafeLoad , unsafeRead , unsafeWrite , useAsPtr ) where import Data.Bits ((.|.), shiftR) import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef) import Data.Maybe import Foreign.C.Types (CSize(..)) import Foreign.ForeignPtr (ForeignPtr, withForeignPtr) import Foreign.Ptr (Ptr, nullPtr, plusPtr) import Foreign.Storable (Storable(..)) import GHC.Base hiding (empty) import GHC.ForeignPtr (mallocPlainForeignPtrBytes, newForeignPtr_) import GHC.Num (Num(..)) import GHC.Real (fromIntegral) import GHC.Show (show) #include "MachDeps.h" #define BOUNDS_CHECKING 1 #if defined(BOUNDS_CHECKING) -- This fugly hack is brought by GHC's apparent reluctance to deal -- with MagicHash and UnboxedTuples when inferring types. Eek! #define CHECK_BOUNDS(_func_,_len_,_k_) \ if (_k_) < 0 || (_k_) >= (_len_) then errorWithoutStackTrace ("GHC.Event.Array." ++ (_func_) ++ ": bounds error, index " ++ show (_k_) ++ ", capacity " ++ show (_len_)) else #else #define CHECK_BOUNDS(_func_,_len_,_k_) #endif -- Invariant: size <= capacity newtype Array a = Array (IORef (AC a)) -- The actual array content. data AC a = AC !(ForeignPtr a) -- Elements !Int -- Number of elements (length) !Int -- Maximum number of elements (capacity) empty :: IO (Array a) empty = do p <- newForeignPtr_ nullPtr Array `fmap` newIORef (AC p 0 0) allocArray :: Storable a => Int -> IO (ForeignPtr a) allocArray n = allocHack undefined where allocHack :: Storable a => a -> IO (ForeignPtr a) allocHack dummy = mallocPlainForeignPtrBytes (n * sizeOf dummy) reallocArray :: Storable a => ForeignPtr a -> Int -> Int -> IO (ForeignPtr a) reallocArray p newSize oldSize = reallocHack undefined p where reallocHack :: Storable a => a -> ForeignPtr a -> IO (ForeignPtr a) reallocHack dummy src = do let size = sizeOf dummy dst <- mallocPlainForeignPtrBytes (newSize * size) withForeignPtr src $ \s -> when (s /= nullPtr && oldSize > 0) . withForeignPtr dst $ \d -> do _ <- memcpy d s (fromIntegral (oldSize * size)) return () return dst new :: Storable a => Int -> IO (Array a) new c = do es <- allocArray cap fmap Array (newIORef (AC es 0 cap)) where cap = firstPowerOf2 c duplicate :: Storable a => Array a -> IO (Array a) duplicate a = dupHack undefined a where dupHack :: Storable b => b -> Array b -> IO (Array b) dupHack dummy (Array ref) = do AC es len cap <- readIORef ref ary <- allocArray cap withForeignPtr ary $ \dest -> withForeignPtr es $ \src -> do _ <- memcpy dest src (fromIntegral (len * sizeOf dummy)) return () Array `fmap` newIORef (AC ary len cap) length :: Array a -> IO Int length (Array ref) = do AC _ len _ <- readIORef ref return len capacity :: Array a -> IO Int capacity (Array ref) = do AC _ _ cap <- readIORef ref return cap unsafeRead :: Storable a => Array a -> Int -> IO a unsafeRead (Array ref) ix = do AC es _ cap <- readIORef ref CHECK_BOUNDS("unsafeRead",cap,ix) withForeignPtr es $ \p -> peekElemOff p ix unsafeWrite :: Storable a => Array a -> Int -> a -> IO () unsafeWrite (Array ref) ix a = do ac <- readIORef ref unsafeWrite' ac ix a unsafeWrite' :: Storable a => AC a -> Int -> a -> IO () unsafeWrite' (AC es _ cap) ix a = do CHECK_BOUNDS("unsafeWrite'",cap,ix) withForeignPtr es $ \p -> pokeElemOff p ix a unsafeLoad :: Array a -> (Ptr a -> Int -> IO Int) -> IO Int unsafeLoad (Array ref) load = do AC es _ cap <- readIORef ref len' <- withForeignPtr es $ \p -> load p cap writeIORef ref (AC es len' cap) return len' ensureCapacity :: Storable a => Array a -> Int -> IO () ensureCapacity (Array ref) c = do ac@(AC _ _ cap) <- readIORef ref ac'@(AC _ _ cap') <- ensureCapacity' ac c when (cap' /= cap) $ writeIORef ref ac' ensureCapacity' :: Storable a => AC a -> Int -> IO (AC a) ensureCapacity' ac@(AC es len cap) c = do if c > cap then do es' <- reallocArray es cap' cap return (AC es' len cap') else return ac where cap' = firstPowerOf2 c useAsPtr :: Array a -> (Ptr a -> Int -> IO b) -> IO b useAsPtr (Array ref) f = do AC es len _ <- readIORef ref withForeignPtr es $ \p -> f p len snoc :: Storable a => Array a -> a -> IO () snoc (Array ref) e = do ac@(AC _ len _) <- readIORef ref let len' = len + 1 ac'@(AC es _ cap) <- ensureCapacity' ac len' unsafeWrite' ac' len e writeIORef ref (AC es len' cap) clear :: Array a -> IO () clear (Array ref) = do atomicModifyIORef' ref $ \(AC es _ cap) -> (AC es 0 cap, ()) forM_ :: Storable a => Array a -> (a -> IO ()) -> IO () forM_ ary g = forHack ary g undefined where forHack :: Storable b => Array b -> (b -> IO ()) -> b -> IO () forHack (Array ref) f dummy = do AC es len _ <- readIORef ref let size = sizeOf dummy offset = len * size withForeignPtr es $ \p -> do let go n | n >= offset = return () | otherwise = do f =<< peek (p `plusPtr` n) go (n + size) go 0 loop :: Storable a => Array a -> b -> (b -> a -> IO (b,Bool)) -> IO () loop ary z g = loopHack ary z g undefined where loopHack :: Storable b => Array b -> c -> (c -> b -> IO (c,Bool)) -> b -> IO () loopHack (Array ref) y f dummy = do AC es len _ <- readIORef ref let size = sizeOf dummy offset = len * size withForeignPtr es $ \p -> do let go n k | n >= offset = return () | otherwise = do (k',cont) <- f k =<< peek (p `plusPtr` n) when cont $ go (n + size) k' go 0 y findIndex :: Storable a => (a -> Bool) -> Array a -> IO (Maybe (Int,a)) findIndex = findHack undefined where findHack :: Storable b => b -> (b -> Bool) -> Array b -> IO (Maybe (Int,b)) findHack dummy p (Array ref) = do AC es len _ <- readIORef ref let size = sizeOf dummy offset = len * size withForeignPtr es $ \ptr -> let go !n !i | n >= offset = return Nothing | otherwise = do val <- peek (ptr `plusPtr` n) if p val then return $ Just (i, val) else go (n + size) (i + 1) in go 0 0 concat :: Storable a => Array a -> Array a -> IO () concat (Array d) (Array s) = do da@(AC _ dlen _) <- readIORef d sa@(AC _ slen _) <- readIORef s writeIORef d =<< copy' da dlen sa 0 slen -- | Copy part of the source array into the destination array. The -- destination array is resized if not large enough. copy :: Storable a => Array a -> Int -> Array a -> Int -> Int -> IO () copy (Array d) dstart (Array s) sstart maxCount = do da <- readIORef d sa <- readIORef s writeIORef d =<< copy' da dstart sa sstart maxCount -- | Copy part of the source array into the destination array. The -- destination array is resized if not large enough. copy' :: Storable a => AC a -> Int -> AC a -> Int -> Int -> IO (AC a) copy' d dstart s sstart maxCount = copyHack d s undefined where copyHack :: Storable b => AC b -> AC b -> b -> IO (AC b) copyHack dac@(AC _ oldLen _) (AC src slen _) dummy = do when (maxCount < 0 || dstart < 0 || dstart > oldLen || sstart < 0 || sstart > slen) $ errorWithoutStackTrace "copy: bad offsets or lengths" let size = sizeOf dummy count = min maxCount (slen - sstart) if count == 0 then return dac else do AC dst dlen dcap <- ensureCapacity' dac (dstart + count) withForeignPtr dst $ \dptr -> withForeignPtr src $ \sptr -> do _ <- memcpy (dptr `plusPtr` (dstart * size)) (sptr `plusPtr` (sstart * size)) (fromIntegral (count * size)) return $ AC dst (max dlen (dstart + count)) dcap removeAt :: Storable a => Array a -> Int -> IO () removeAt a i = removeHack a undefined where removeHack :: Storable b => Array b -> b -> IO () removeHack (Array ary) dummy = do AC fp oldLen cap <- readIORef ary when (i < 0 || i >= oldLen) $ errorWithoutStackTrace "removeAt: invalid index" let size = sizeOf dummy newLen = oldLen - 1 when (newLen > 0 && i < newLen) . withForeignPtr fp $ \ptr -> do _ <- memmove (ptr `plusPtr` (size * i)) (ptr `plusPtr` (size * (i+1))) (fromIntegral (size * (newLen-i))) return () writeIORef ary (AC fp newLen cap) {-The firstPowerOf2 function works by setting all bits on the right-hand side of the most significant flagged bit to 1, and then incrementing the entire value at the end so it "rolls over" to the nearest power of two. -} -- | Computes the next-highest power of two for a particular integer, -- @n@. If @n@ is already a power of two, returns @n@. If @n@ is -- zero, returns zero, even though zero is not a power of two. firstPowerOf2 :: Int -> Int firstPowerOf2 !n = let !n1 = n - 1 !n2 = n1 .|. (n1 `shiftR` 1) !n3 = n2 .|. (n2 `shiftR` 2) !n4 = n3 .|. (n3 `shiftR` 4) !n5 = n4 .|. (n4 `shiftR` 8) !n6 = n5 .|. (n5 `shiftR` 16) #if WORD_SIZE_IN_BITS == 32 in n6 + 1 #elif WORD_SIZE_IN_BITS == 64 !n7 = n6 .|. (n6 `shiftR` 32) in n7 + 1 #else # error firstPowerOf2 not defined on this architecture #endif foreign import ccall unsafe "string.h memcpy" memcpy :: Ptr a -> Ptr a -> CSize -> IO (Ptr a) foreign import ccall unsafe "string.h memmove" memmove :: Ptr a -> Ptr a -> CSize -> IO (Ptr a)
tolysz/prepare-ghcjs
spec-lts8/base/GHC/Event/Array.hs
bsd-3-clause
10,044
0
23
2,912
3,886
1,905
1,981
-1
-1
module Main (main) where import GenUtils import DataTypes import Parser import Interp import PrintTEX import System.Environment -- 1.3 (partain) import Data.Char -- 1.3 --fakeArgs = "game001.txt" --fakeArgs = "pca2.pgn" --fakeArgs = "silly.pgn" --fakeArgs = "small.pgn" --fakeArgs = "sicil.pgn" --fakeArgs = "badgame.pgn" --fakeArgs = "mycgames.pgn" fakeArgs = "rab.pgn" version = "0.3" main = do [test_dir] <- getArgs let (style,fn,filename) = interpArgs (words "-d tex mygames.pgn") file <- readFile (test_dir ++ "/" ++filename) std_in <- getContents let games = pgnParser fn file -- parse relavent pgn games putStr (prog style std_in games) {- OLD 1.2: main = getArgs abort $ \ args -> --let args = (words "-d tex analgames.pgn") in let (style,fn,filename) = interpArgs args in readFile filename abort $ \ file -> readChan stdin abort $ \ std_in -> let games = pgnParser fn file -- parse relavent pgn games in appendChan stdout (prog style std_in games) abort done -} interpArgs :: [String] -> (OutputStyle,Int -> Bool,String) --interpArgs [] = (ViewGame,const True,fakeArgs) interpArgs [] = interpArgs (words "-d pgn analgames.pgn") interpArgs files = interpArgs' OutputPGN (const True) files interpArgs' style fn ("-d":"pgn":xs) = interpArgs' OutputPGN fn xs interpArgs' style fn ("-d":"rawpgn":xs) = interpArgs' OutputRawPGN fn xs interpArgs' style fn ("-d":"play":xs) = interpArgs' ViewGame fn xs interpArgs' style fn ("-d":"parser":xs) = interpArgs' OutputParser fn xs interpArgs' style fn ("-d":"tex":xs) = interpArgs' OutputTEX fn xs interpArgs' style fn ("-d":"head":xs) = interpArgs' OutputHeader fn xs interpArgs' style fn ("-g":range:xs) = interpArgs' style (changeFn (parse range)) xs where changeFn (Digit n:Line:Digit m:r) x = moreChangeFn r x || x >= n && x <= m changeFn (Line:Digit m:r) x = moreChangeFn r x || x <= m changeFn (Digit n:Line:r) x = moreChangeFn r x || x >= n changeFn (Digit n:r) x = moreChangeFn r x || x == n changeFn _ _ = rangeError moreChangeFn [] = const False moreChangeFn (Comma:r) = changeFn r moreChangeFn _ = rangeError parse xs@(n:_) | isDigit n = case span isDigit xs of (dig,rest) -> Digit (read dig) : parse rest parse ('-':r) = Line : parse r parse (',':r) = Comma : parse r parse [] = [] parse _ = rangeError rangeError = error ("incorrect -g option (" ++ range ++ ")\n") interpArgs' style fn [file] = (style,fn,file) interpArgs' style fn args = error ("bad args: " ++ unwords args) data Tok = Digit Int -- n | Line -- - | Comma -- , data OutputStyle = OutputPGN -- pgn | OutputRawPGN -- rawpgn | OutputHeader -- header | ViewGame -- play | ViewGameEmacs -- emacs | TwoColumn -- 2col | TestGames -- test | OutputTEX | OutputParser -- simply dump out the string read in. | CmpGen -- cmp 2nd and 3rd generations of output prog :: OutputStyle -- style of action -> String -- stdin (for interactive bits) -> [AbsGame] -- input games -> String -- result prog OutputPGN _ = pgnPrinter True -- print out game(s) . map runInterp -- interprete all games prog OutputRawPGN _ = pgnPrinter False -- print out game(s) . map runInterp -- interprete all games prog OutputHeader _ = pgnHeadPrinter -- print out game(s) headers . map runInterp -- interprete all games prog OutputTEX _ = texPrinter -- print out game(s) . map runInterp -- interprete all games prog ViewGame std_in = interactViewer std_in -- print out game(s) . runInterp -- interprete the game . head -- should check for only *one* object prog OutputParser _ = userFormat type PrintState = (Bool,MoveNumber) pgnPrinter :: Bool -> [RealGame] -> String pgnPrinter detail = unlines . concat . map printGame where printMoveNumber :: Bool -> MoveNumber -> String printMoveNumber False (MoveNumber _ Black) = "" printMoveNumber _ mvnum = userFormat mvnum ++ " " printQuantums :: PrintState -> [Quantum] -> [String] printQuantums ps = concat . fst . mapAccumL printQuantum ps printQuantum :: PrintState -> Quantum -> ([String],PrintState) printQuantum (pnt,mv) (QuantumMove move ch an brd) = ([printMoveNumber pnt mv ++ move ++ ch],(False,incMove mv)) printQuantum (pnt,mv) (QuantumNAG i) = if detail then (["$" ++ show i],(False,mv)) else ([],(False,mv)) printQuantum (pnt,mv) (QuantumComment comms) = if detail then ("{" : comms ++ ["}"],(True,mv)) else ([],(False,mv)) printQuantum (pnt,mv) (QuantumAnalysis anal) = if detail then ("(" : printQuantums (True,decMove mv) anal ++ [")"], (True,mv)) else ([],(False,mv)) printQuantum (pnt,mv) (QuantumResult str) = ([str],(True,mv)) printQuantum _ _ = error "PANIC: strange Quantum" printGame :: RealGame -> [String] printGame (Game tags qu) = [ userFormat tag | tag <- tags] ++ formatText 75 (printQuantums (False,initMoveNumber) qu) printHeadGame :: RealGame -> [String] printHeadGame (Game tags qu) = [ rjustify 4 gameno ++ " " ++ take 20 (rjustify 20 white) ++ " - " ++ take 20 (ljustify 20 black) ++ " " ++ take 26 (ljustify 28 site) ++ " " ++ result ] where (date,site,game_no,res,white,black,opening) = getHeaderInfo tags gameno = case game_no of Nothing -> "" Just n -> show n result = userFormat res pgnHeadPrinter :: [RealGame] -> String pgnHeadPrinter = unlines . concat . map printHeadGame interactViewer :: String -> RealGame -> String interactViewer stdin (Game tags qu) = replayQ qu (lines stdin) replayQ (QuantumMove _ _ _ brd:rest) std_in = "\027[H" ++ userFormat brd ++ waitQ rest std_in replayQ (_:rest) std_in = replayQ rest std_in replayQ [] _ = [] waitQ game std_in = ">>" ++ (case std_in of [] -> "" (q:qs) -> replayQ game qs)
wxwxwwxxx/ghc
testsuite/tests/programs/andy_cherry/Main.hs
bsd-3-clause
6,952
0
15
2,345
1,967
1,044
923
136
11
{-# LANGUAGE TypeFamilies #-} module DataFamDeriv where data family Foo a data Bar = Bar data instance Foo Bar = Bar1 | Bar2 | Bar3 | Bar4 | Bar5 | Bar6 | Bar7 | Bar8 | Bar9 deriving Eq
urbanslug/ghc
testsuite/tests/indexed-types/should_compile/DataFamDeriv.hs
bsd-3-clause
198
0
5
51
56
36
20
7
0
module B where import C import {-# SOURCE #-} A
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/programs/hs-boot/B.hs
bsd-3-clause
50
0
3
12
11
8
3
3
0
-- | Allow to filter a list of string with fileListenInfoInclude and exclude patterns module Shaker.Regex( processListWithRegexp ) where import Text.Regex.Posix import Data.List -- | Filter all elements matching fileListenInfoInclude patterns and -- remove all elements matching exclude patterns to the result. -- -- If no fileListenInfoInclude pattern is given, all elements are accepted minus those matching exclude patterns. -- -- If no exclude pattern is given, all elements matching fileListenInfoInclude patterns are taken. processListWithRegexp :: [String] -- ^ Initial list to filter -> [String] -- ^ exclude patterns (regex) -> [String] -- ^ fileListenInfoInclude patterns (regex) -> [String] -- ^ List with all elements matching fileListenInfoInclude patterns minus all elements matching exclude patterns processListWithRegexp list [] [] = list processListWithRegexp list fileListenInfoIgnore [] = nub $ list \\ getExcluded list fileListenInfoIgnore processListWithRegexp list [] fileListenInfoInclude = nub $ getIncluded list fileListenInfoInclude processListWithRegexp list fileListenInfoIgnore fileListenInfoInclude = nub $ getIncluded list fileListenInfoInclude \\ getExcluded list fileListenInfoIgnore getExcluded :: [String] -> [String] -> [String] getExcluded list patterns = filter funExclude list where funExclude el = any (\a -> el =~+ (a,compIgnoreCase, execBlank) ) patterns getIncluded :: [String] -> [String] -> [String] getIncluded list patterns = filter funInclude list where funInclude el = any (\a -> el =~+ (a,compIgnoreCase, execBlank) ) patterns (=~+) :: ( RegexMaker regex compOpt execOpt source, RegexContext regex source1 target ) => source1 -> (source, compOpt, execOpt) -> target source1 =~+ (source, compOpt, execOpt) = match (makeRegexOpts compOpt execOpt source) source1
bonnefoa/Shaker
src/Shaker/Regex.hs
isc
1,838
0
11
271
388
214
174
22
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} module Database.PostgreSQL.Simple.Classy.Exceptions.FormatError ( AsFormatError (..) , _FmtMessage , _FmtQuery , _FmtParams ) where import Data.String (String) import Data.ByteString (ByteString) import Data.Profunctor (Profunctor) import Data.Functor (Functor) import Control.Category (id) import Control.Lens (Getter,Optic',iso,to) import Database.PostgreSQL.Simple (Query,FormatError (..)) -- $setup -- >>> import Control.Lens ((^?),(^.)) -- >>> import Data.Maybe (Maybe(Just,Nothing)) -- >>> import Database.PostgreSQL.Simple (Query (..)) -- >>> let fakeQ = ("select foo from bar where buzz" :: Query) -- Query is an instance of `IsString` and is a `ByteString` internally. class AsFormatError p f s where _FormatError :: Optic' p f s FormatError instance AsFormatError p f FormatError where _FormatError = id -- | -- >>> (("fuzz"::String), fakeQ, ["foo"::ByteString,"bar"]) ^? _FormatError -- Just (FormatError {fmtMessage = "fuzz", fmtQuery = "select foo from bar where buzz", fmtParams = ["foo","bar"]}) instance (Profunctor p, Functor f) => AsFormatError p f (String, Query, [ByteString]) where _FormatError = iso (\(a,b,c) -> FormatError a b c) (\(FormatError { fmtMessage = a , fmtQuery = b , fmtParams = c} ) -> (a,b,c)) -- | -- >>> let a = FormatError ("Oh noes"::String) fakeQ ["Fuzz"::ByteString,"Bozz"] -- >>> a ^. _FmtMessage -- "Oh noes" -- >>> a ^. _FmtQuery -- "select foo from bar where buzz" -- >>> a ^. _FmtParams -- ["Fuzz","Bozz"] _FmtMessage :: Getter FormatError String _FmtMessage = to (\(FormatError { fmtMessage = a}) -> a) _FmtQuery :: Getter FormatError Query _FmtQuery = to (\(FormatError { fmtQuery = a}) -> a) _FmtParams :: Getter FormatError [ByteString] _FmtParams = to (\(FormatError { fmtParams = a}) -> a)
mankyKitty/classy-pgsql-errors
src/Database/PostgreSQL/Simple/Classy/Exceptions/FormatError.hs
mit
2,006
0
12
381
411
249
162
36
1
module Rebase.GHC.Real ( module GHC.Real ) where import GHC.Real
nikita-volkov/rebase
library/Rebase/GHC/Real.hs
mit
68
0
5
12
20
13
7
4
0
module Main where import BFIOlib import Control.Concurrent import Control.Monad.State import Control.Monad.Writer import BFLib.Brainfuch (Code, emptyStack, Stack) import BFLib.BrainfuchFollow main :: IO () main = do code <- readCode putStr "\nOutput of script:\n" stacks <- interpret code putStr "\n\nStack states during interpretation:\n" putStrLn $ showStacks stacks -- Code showStacks :: [StackCode] -> String showStacks stacks = foldl1 (\a e -> a ++ "\n" ++ e) stackstrings where stackstrings = map showStack stacks interpret :: Code -> IO [StackCode] interpret c = liftM (snd . fst) $ runStateT (runWriterT (bffTell (emptyStack,' ') >> bfInt c)) emptyStack
dermesser/Brainfuch
BFdbg.hs
mit
714
0
12
146
222
116
106
19
1
{-# LANGUAGE OverloadedStrings #-} module WS.Mail where import Control.Applicative (Applicative) import Data.Text (Text) import Data.Text.Lazy (fromStrict) import Network.Mail.SMTP as SMTP class (Functor m, Applicative m, Monad m) => MonadMail m where sendMail :: Text -> Text -> Text -> Text -> m () instance MonadMail IO where sendMail from to sub body = sendMail' "localhost" 1025 mail where mail = simpleMail from' [to'] [] [] sub [plainTextPart (fromStrict body)] from' = Address Nothing from to' = Address Nothing to
krdlab/haskell-webapp-testing-experimentation
src/WS/Mail.hs
mit
567
0
12
123
190
102
88
13
0
{-# OPTIONS_GHC -fno-warn-orphans #-} import qualified Interface.ReadCsv as Csv import Interface.Interaction import VirtualArrow.Input import VirtualArrow.Election import qualified Data.Map.Strict as Map main :: IO () main = do ds <- Csv.readCSV "example/constituencies.csv" :: IO [District] vs <- Csv.readVotersFromCsv "example/voters.csv" let input = Input{ districts=ds , voters=vs , nparties=5 , districtMap=Map.fromList (votersByDistrict vs)} printParliament (plurality input)
olya-d/virtual-arrow
src/Profiling.hs
mit
566
0
14
138
140
77
63
15
1
----------------------------------------------------------------------------- -- -- Module : NSGA2Mod -- Copyright : Armin Kazmi (2015) -- License : MIT -- -- Maintainer : Armin Kazmi -- Stability : experimental -- Portability : GHC only or compatible -- -- | This module just copies a lot of functions from the module -- 'Moo.GeneticAlgorithm.Multiobjective.NSGA2' and enhances -- it with parallel population evaluation and a more complex form of -- 'ObjectiveFunction'. ----------------------------------------------------------------------------- {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE IncoherentInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} module DAAK.Algorithms.NSGA2Mod where import Control.Arrow import Control.DeepSeq import Control.Monad import Control.Monad.ST (ST) import Control.Parallel.Strategies import Data.Array import Data.Array.ST (STArray, getBounds, getElems, newArray, readArray, runSTArray, writeArray) import Data.List import Data.STRef import Moo.GeneticAlgorithm.Continuous import Moo.GeneticAlgorithm.Multiobjective import Moo.GeneticAlgorithm.Random import Moo.GeneticAlgorithm.Types import Moo.GeneticAlgorithm.Multiobjective.NSGA2 hiding (nondominatedRanking, nondominatedSort, nondominatedSortFast, nsga2Ranking, rankAllSolutions, stepNSGA2'firstGeneration, stepNSGA2'nextGeneration, stepNSGA2'poolSelection) type TransferFunction a b = Genome a -> b singleton :: a -> [a] singleton a = [a] -- | Assign non-domination rank and crowding distances to all solutions. -- Return a list of non-domination fronts. rankAllSolutions :: DominationCmp a -> [MultiPhenotype a] -> [[RankedSolution a]] rankAllSolutions dominates genomes = let -- non-dominated fronts fronts = nondominatedSort dominates genomes -- for every non-dominated front frontsDists = fmap (crowdingDistances . map snd) fronts ranks = iterate (+1) 1 in map rankedSolutions1 (zip3 fronts ranks frontsDists) where rankedSolutions1 :: ([MultiPhenotype a], Int, [Double]) -> [RankedSolution a] rankedSolutions1 (front, rank, dists) = zipWith (\g d -> RankedSolution g rank d) front dists -- | Calculate multiple objective per every genome in the population. evalAllObjectives' :: forall fn gt a b. ( fn ~ (b -> a) , ObjectiveFunction fn b , GenomeState gt a , NFData b ) => TransferFunction a b -> MultiObjectiveProblem fn -- ^ a list of @problems@ -> [gt] -- ^ a population of @genomes@ -> [MultiPhenotype a] evalAllObjectives' transfer problems genomes = let rawgenomes = fmap takeGenome genomes transgenomes = parMap rdeepseq (singleton . transfer) rawgenomes -- transgenomes = fmap (singleton . transfer) rawgenomes -- pops_per_objective = fmap (\(_, f) -> evalObjective f transgenomes) problems pops_per_objective = parMap rdeepseq (\(_, f) -> evalObjective f transgenomes) problems ovs_per_objective = fmap (fmap takeObjectiveValue) pops_per_objective ovs_per_genome = transpose ovs_per_objective in zip rawgenomes ovs_per_genome -- | To every genome in the population, assign a single objective -- value according to its non-domination rank. This ranking is -- supposed to be used once in the beginning of the NSGA-II algorithm. -- -- Note: 'nondominatedRanking' reorders the genomes. nondominatedRanking :: forall fn a b . ( NFData a , fn ~ (b -> a) , ObjectiveFunction fn b , NFData b ) => TransferFunction a b -> DominationCmp a -> MultiObjectiveProblem fn -- ^ list of @problems@ -> [Genome a] -- ^ a population of raw @genomes@ -> [(Genome a, Objective)] nondominatedRanking transfer dominates problems genomes = let egs = evalAllObjectives' transfer problems genomes fronts = nondominatedSort dominates egs ranks = concatMap assignRanks (zip fronts (iterate (+1) 1)) in ranks where assignRanks :: ([MultiPhenotype a], Int) -> [(Genome a, Objective)] assignRanks (gs, r) = map (fst *** fromIntegral) $ zip gs (repeat r) -- | A single step of the NSGA-II algorithm (Non-Dominated Sorting -- Genetic Algorithm for Multi-Objective Optimization). -- -- The next population is selected from a common pool of parents and -- their children minimizing the non-domination rank and maximizing -- the crowding distance within the same rank. -- The first generation of children is produced without taking -- crowding into account. -- Every solution is assigned a single objective value which is its -- sequence number after sorting with the crowded comparison operator. -- The smaller value corresponds to solutions which are not worse -- the one with the bigger value. Use 'evalAllObjectives' to restore -- individual objective values. -- -- Reference: -- Deb, K., Pratap, A., Agarwal, S., & Meyarivan, T. A. M. T. (2002). A -- fast and elitist multiobjective genetic algorithm: -- NSGA-II. Evolutionary Computation, IEEE Transactions on, 6(2), -- 182-197. -- -- Deb et al. used a binary tournament selection, base on crowded -- comparison operator. To achieve the same effect, use -- 'stepNSGA2bt' (or 'stepNSGA2' with 'tournamentSelect' -- @Minimizing 2 n@, where @n@ is the size of the population). -- stepNSGA2 :: forall fn a b . ( NFData a , fn ~ (b -> a) , ObjectiveFunction fn b , NFData b ) => TransferFunction a b -> MultiObjectiveProblem fn -- ^ a list of @objective@ functions -> SelectionOp a -> CrossoverOp a -> MutationOp a -> StepGA Rand a stepNSGA2 transfer problems select crossover mutate stop input = do let dominates = domination (map fst problems) case input of (Left _) -> -- raw genomes => it's the first generation stepNSGA2'firstGeneration transfer dominates problems select crossover mutate stop input (Right _) -> -- ranked genomes => it's the second or later generation stepNSGA2'nextGeneration transfer dominates problems select crossover mutate stop input stepNSGA2'firstGeneration :: forall fn a b . ( NFData a , fn ~ (b -> a) , ObjectiveFunction fn b , NFData b ) => TransferFunction a b -> DominationCmp a -> MultiObjectiveProblem fn -- ^ a list of @objective@ functions -> SelectionOp a -> CrossoverOp a -> MutationOp a -> StepGA Rand a stepNSGA2'firstGeneration transfer dominates problems select crossover mutate = do let objective = nondominatedRanking transfer dominates problems makeStoppable objective $ \phenotypes -> do let popsize = length phenotypes let genomes = map takeGenome phenotypes selected <- liftM (map takeGenome) $ (shuffle <=< select) phenotypes newgenomes <- mapM mutate <=< flip doCrossovers crossover $ selected let pool = newgenomes ++ genomes return $ stepNSGA2'poolSelection transfer dominates problems popsize pool -- | Use normal selection, crossover, mutation to produce new -- children. Select from a common pool of parents and children the -- best according to the least non-domination rank and crowding. stepNSGA2'nextGeneration :: forall fn a b . ( NFData a , fn ~ (b -> a) , ObjectiveFunction fn b , NFData b ) => TransferFunction a b -> DominationCmp a -> MultiObjectiveProblem fn -- ^ a list of objective functions -> SelectionOp a -> CrossoverOp a -> MutationOp a -> StepGA Rand a stepNSGA2'nextGeneration transfer dominates problems select crossover mutate = do -- nextGeneration is never called with raw genomes, -- => dummyObjective is never evaluated; -- nondominatedRanking is required to type-check let dummyObjective = nondominatedRanking transfer dominates problems makeStoppable dummyObjective $ \rankedgenomes -> do let popsize = length rankedgenomes selected <- liftM (map takeGenome) $ select rankedgenomes newgenomes <- mapM mutate <=< flip doCrossovers crossover <=< shuffle $ selected let pool = map takeGenome rankedgenomes ++ newgenomes return $ stepNSGA2'poolSelection transfer dominates problems popsize pool -- | Take a pool of phenotypes of size 2N, ordered by the crowded -- comparison operator, and select N best. stepNSGA2'poolSelection :: forall fn a b . ( NFData a , fn ~ (b -> a) , ObjectiveFunction fn b , NFData b ) => TransferFunction a b -> DominationCmp a -> MultiObjectiveProblem fn -- ^ a list of @objective@ functions -> Int -- ^ @n@, the number of solutions to select -> [Genome a] -- ^ @pool@ of genomes to select from -> [Phenotype a] -- ^ @n@ best phenotypes stepNSGA2'poolSelection transfer dominates problems n pool = -- nsga2Ranking returns genomes properly sorted already let rankedgenomes = let grs = nsga2Ranking transfer dominates problems n pool in map (first takeGenome) grs selected = take n rankedgenomes -- :: [Phenotype a] in selected -- | To every genome in the population, assign a single objective value -- equal to its non-domination rank, and sort genomes by the decreasing -- local crowding distance within every rank -- (i.e. sort the population with NSGA-II crowded comparision -- operator) nsga2Ranking :: forall fn a b . ( NFData a , fn ~ (b -> a) , ObjectiveFunction fn b , NFData b ) => TransferFunction a b -> DominationCmp a -> MultiObjectiveProblem fn -- ^ a list of @objective@ functions -> Int -- ^ @n@, number of top-ranked genomes to select -> [Genome a] -- ^ a population of raw @genomes@ -> [(MultiPhenotype a, Double)] -- ^ selected genomes with their non-domination ranks nsga2Ranking transfer dominates problems n genomes = let evaledGenomes = evalAllObjectives' transfer problems genomes fronts = rankAllSolutions dominates evaledGenomes frontSizes = map length fronts nFullFronts = length . takeWhile (< n) $ scanl1 (+) frontSizes partialSize = n - sum (take nFullFronts frontSizes) (frontsFull, frontsPartial) = splitAt nFullFronts fronts fromFullFronts = concatMap (map assignRank) frontsFull fromPartialFront = concatMap ( map assignRank . take partialSize . sortBy crowdedCompare ) $ take 1 frontsPartial in fromFullFronts ++ fromPartialFront where assignRank eg = let r = fromIntegral $ rs'nondominationRank eg phenotype = rs'phenotype eg in (phenotype, r) -- | Fast non-dominated sort from (Deb et al. 2002). -- It is should be O(m N^2), with storage requirements of O(N^2). nondominatedSort :: DominationCmp a -> [MultiPhenotype a] -> [[MultiPhenotype a]] nondominatedSort = nondominatedSortFast -- | This is a direct translation of the pseudocode from (Deb et al. 2002). nondominatedSortFast :: DominationCmp a -> [MultiPhenotype a] -> [[MultiPhenotype a]] nondominatedSortFast dominates gs = let n = length gs -- number of genomes garray = listArray (0, n-1) gs fronts = runSTArray $ do -- structure of sp array: -- sp [pi][0] -- n_p, number of genomes dominating pi-th genome -- sp [pi][1] -- size of S_p, how many genomes pi-th genome dominates -- sp [pi][2..] -- indices of the genomes dominated by pi-th genome -- -- where pi in [0..n-1] -- -- structure of the fronts array: -- fronts [0][i] -- size of the i-th front -- fronts [1][start..start+fsizes[i]-1] -- indices of the elements of the i-th front -- -- where start = sum (take (i-1) fsizes) -- -- domination table sp <- newArray ((0,0), (n-1, (n+2)-1)) 0 :: ST s (STArray s (Int,Int) Int) -- at most n fronts with 1 element each frontsi <- newArray ((0,0), (1,n-1)) 0 :: ST s (STArray s (Int,Int) Int) forM_ (zip gs [0..]) $ \(p, pi) -> do -- for each p in P forM_ (zip gs [0..]) $ \(q, qi) -> do -- for each q in P when ( p `dominates` q ) $ -- if p dominates q, include q in S_p includeInSp sp pi qi when ( q `dominates` p) $ -- if q dominates p, increment n_p incrementNp sp pi np <- readArray sp (pi, 0) when (np == 0) $ addToFront 0 frontsi pi buildFronts sp frontsi 0 frontSizes = takeWhile (>0) . take n $ elems fronts frontElems = map (\i -> garray ! i) . drop n $ elems fronts in splitAll frontSizes frontElems where includeInSp sp pi qi = do oldspsize <- readArray sp (pi, 1) writeArray sp (pi, 2 + oldspsize) qi writeArray sp (pi, 1) (oldspsize + 1) incrementNp sp pi = do oldnp <- readArray sp (pi, 0) writeArray sp (pi, 0) (oldnp + 1) -- size of the i-th front frontSize fronts i = readArray fronts (0, i) frontStartIndex fronts frontno = do -- start = sum (take (frontno-1) fsizes) startref <- newSTRef 0 forM_ [0..(frontno-1)] $ \i -> do oldstart <- readSTRef startref l <- frontSize fronts i writeSTRef startref (oldstart + l) readSTRef startref -- adjust fronts array by updating frontno-th front size and appending -- pi to its elements; frontno should be the last front! addToFront frontno fronts pi = do -- update i-th front size and write an index in the correct position start <- frontStartIndex fronts frontno sz <- frontSize fronts frontno writeArray fronts (1, start + sz) pi writeArray fronts (0, frontno) (sz + 1) -- elements of the i-th front frontElems fronts i = do start <- frontStartIndex fronts i sz <- frontSize fronts i felems <- newArray (0, sz-1) (-1) :: ST s (STArray s Int Int) forM_ [0..sz-1] $ \elix -> readArray fronts (1, start+elix) >>= writeArray felems elix getElems felems -- elements which are dominated by the element pi dominatedSet sp pi = do sz <- readArray sp (pi, 1) delems <- newArray (0, sz-1) (-1) :: ST s (STArray s Int Int) forM_ [0..sz-1] $ \elix -> readArray sp (pi, 2+elix) >>= writeArray delems elix getElems delems buildFronts sp fronts i = do maxI <- (snd . snd) `liftM` getBounds fronts if i >= maxI || i < 0 -- all fronts are singletons and the last is already built then return fronts else do fsz <- frontSize fronts i if fsz <= 0 then return fronts else do felems <- frontElems fronts i forM_ felems $ \pi -> do -- for each member p in F_i dominated <- dominatedSet sp pi forM_ dominated $ \qi -> do -- modify each member from the set S_p nq <- liftM (+ (-1:: Int)) $ readArray sp (qi, 0) -- decrement n_q by one writeArray sp (qi, 0) nq when (nq <= 0) $ -- if n_q is zero, q is a member of the next front addToFront (i+1) fronts qi buildFronts sp fronts (i+1) splitAll [] _ = [] splitAll _ [] = [] splitAll (sz:szs) els = let (front, rest) = splitAt sz els in front : splitAll szs rest
apriori/daak
lib/DAAK/Algorithms/NSGA2Mod.hs
mit
17,202
0
28
5,660
3,470
1,814
1,656
256
5
{-# LANGUAGE DeriveDataTypeable #-} import Data.Typeable data Animal = Cat | Dog deriving Typeable data Zoo a = Zoo [a] deriving Typeable equal :: (Typeable a, Typeable b) => a -> b -> Bool equal a b = typeOf a == typeOf b example1 :: TypeRep example1 = typeOf Cat -- Animal example2 :: TypeRep example2 = typeOf (Zoo [Cat, Dog]) -- Zoo Animal example3 :: TypeRep example3 = typeOf ((1, 6.636e-34, "foo") :: (Int, Double, String)) -- (Int,Double,[Char]) example4 :: Bool example4 = equal False () -- False
riwsky/wiwinwlh
src/typeable.hs
mit
513
0
8
96
180
103
77
14
1
import Data.List import Data.List.Extra import Data.Maybe import qualified Data.Map as Map parseLine :: String -> [Int] parseLine s = let [name, _, _, speed, "km/s", _, endurance, "seconds,", _, _, _, _, _, rest, "seconds."] = words s in concat $ repeat $ replicate (read endurance) (read speed) ++ replicate (read rest) 0 allDistances :: [String] -> [[Int]] allDistances = map parseLine totalDistance :: Int -> [Int] -> Int totalDistance time thingus = sum $ take time thingus time = 2503 furthest :: [[Int]] -> Int furthest dists = maximum $ map (totalDistance time) dists solve :: String -> Int solve = furthest . allDistances . lines answer f = interact $ (++"\n") . show . f main = answer solve
msullivan/advent-of-code
2015/A14a.hs
mit
724
0
11
145
303
167
136
20
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.AudioTrackList (item, item_, getTrackById, getTrackById_, getLength, change, addTrack, removeTrack, AudioTrackList(..), gTypeAudioTrackList) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList.item Mozilla AudioTrackList.item documentation> item :: (MonadDOM m) => AudioTrackList -> Word -> m AudioTrack item self index = liftDOM ((self ^. jsf "item" [toJSVal index]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList.item Mozilla AudioTrackList.item documentation> item_ :: (MonadDOM m) => AudioTrackList -> Word -> m () item_ self index = liftDOM (void (self ^. jsf "item" [toJSVal index])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList.getTrackById Mozilla AudioTrackList.getTrackById documentation> getTrackById :: (MonadDOM m, ToJSString id) => AudioTrackList -> id -> m AudioTrack getTrackById self id = liftDOM ((self ^. jsf "getTrackById" [toJSVal id]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList.getTrackById Mozilla AudioTrackList.getTrackById documentation> getTrackById_ :: (MonadDOM m, ToJSString id) => AudioTrackList -> id -> m () getTrackById_ self id = liftDOM (void (self ^. jsf "getTrackById" [toJSVal id])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList.length Mozilla AudioTrackList.length documentation> getLength :: (MonadDOM m) => AudioTrackList -> m Word getLength self = liftDOM (round <$> ((self ^. js "length") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList.onchange Mozilla AudioTrackList.onchange documentation> change :: EventName AudioTrackList Event change = unsafeEventName (toJSString "change") -- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList.onaddtrack Mozilla AudioTrackList.onaddtrack documentation> addTrack :: EventName AudioTrackList Event addTrack = unsafeEventName (toJSString "addtrack") -- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList.onremovetrack Mozilla AudioTrackList.onremovetrack documentation> removeTrack :: EventName AudioTrackList Event removeTrack = unsafeEventName (toJSString "removetrack")
ghcjs/jsaddle-dom
src/JSDOM/Generated/AudioTrackList.hs
mit
3,223
0
12
393
718
419
299
44
1
{-# htermination intersectFM :: FiniteMap Ordering b -> FiniteMap Ordering b -> FiniteMap Ordering b #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_intersectFM_11.hs
mit
122
0
3
18
5
3
2
1
0
module Sproxy.Server ( server ) where import Control.Concurrent (forkIO) import Control.Exception (bracketOnError) import Control.Monad (void, when) import Data.ByteString.Char8 (pack) import qualified Data.HashMap.Strict as HM import Data.Maybe (fromMaybe) import Data.Text (Text) import Data.Yaml.Include (decodeFileEither) import Network.HTTP.Client ( Manager , ManagerSettings(..) , defaultManagerSettings , newManager , responseTimeoutMicro , socketConnection ) import Network.HTTP.Client.Internal (Connection) import Network.Socket ( AddrInfoFlag(AI_NUMERICSERV) , Family(AF_INET, AF_UNIX) , SockAddr(SockAddrInet, SockAddrUnix) , Socket , SocketOption(ReuseAddr) , SocketType(Stream) , addrAddress , addrFamily , addrFlags , addrProtocol , addrSocketType , bind , close , connect , defaultHints , getAddrInfo , listen , maxListenQueue , setSocketOption , socket ) import Network.Wai (Application) import Network.Wai.Handler.Warp ( Settings , defaultSettings , runSettingsSocket , setHTTP2Disabled , setOnException ) import Network.Wai.Handler.WarpTLS (runTLSSocket, tlsSettingsChain) import System.Entropy (getEntropy) import System.Environment (setEnv) import System.Exit (exitFailure) import System.FilePath.Glob (compile) import System.IO (hPutStrLn, stderr) import System.Posix.User ( GroupEntry(..) , UserEntry(..) , getAllGroupEntries , getRealUserID , getUserEntryForName , setGroupID , setGroups , setUserID ) import Sproxy.Application (redirect, sproxy) import qualified Sproxy.Application.OAuth2 as OAuth2 import Sproxy.Application.OAuth2.Common (OAuth2Client) import Sproxy.Config (BackendConf(..), ConfigFile(..), OAuth2Conf(..)) import qualified Sproxy.Logging as Log import qualified Sproxy.Server.DB as DB {- TODO: - Log.error && exitFailure should be replaced - by Log.fatal && wait for logger thread to print && exitFailure -} server :: FilePath -> IO () server configFile = do cf <- readConfigFile configFile Log.start $ cfLogLevel cf sock <- socket AF_INET Stream 0 setSocketOption sock ReuseAddr 1 bind sock $ SockAddrInet (fromIntegral $ cfListen cf) 0 maybe80 <- if fromMaybe (443 == cfListen cf) (cfListen80 cf) then do sock80 <- socket AF_INET Stream 0 setSocketOption sock80 ReuseAddr 1 bind sock80 $ SockAddrInet 80 0 return (Just sock80) else return Nothing uid <- getRealUserID when (0 == uid) $ do let user = cfUser cf Log.info $ "switching to user " ++ show user u <- getUserEntryForName user groupIDs <- map groupID . filter (elem user . groupMembers) <$> getAllGroupEntries setGroups groupIDs setGroupID $ userGroupID u setUserID $ userID u ds <- newDataSource cf db <- DB.start (cfHome cf) ds key <- maybe (Log.info "using new random key" >> getEntropy 64) (return . pack) (cfKey cf) let settings = (if cfHTTP2 cf then id else setHTTP2Disabled) $ setOnException (\_ _ -> return ()) defaultSettings oauth2clients <- HM.fromList <$> mapM newOAuth2Client (HM.toList (cfOAuth2 cf)) backends <- mapM (\be -> do m <- newBackendManager be return (compile $ beName be, be, m)) $ cfBackends cf warpServer <- newServer cf case maybe80 of Nothing -> return () Just sock80 -> do let httpsPort = fromMaybe (cfListen cf) (cfHttpsPort cf) Log.info "listening on port 80 (HTTP redirect)" listen sock80 maxListenQueue void . forkIO $ runSettingsSocket settings sock80 (redirect httpsPort) -- XXX 2048 is from bindPortTCP from streaming-commons used internally by runTLS. -- XXX Since we don't call runTLS, we listen socket here with the same options. Log.info $ "proxy listening on port " ++ show (cfListen cf) listen sock (max 2048 maxListenQueue) warpServer settings sock (sproxy key db oauth2clients backends) newDataSource :: ConfigFile -> IO (Maybe DB.DataSource) newDataSource cf = case (cfDataFile cf, cfDatabase cf) of (Nothing, Just str) -> do case cfPgPassFile cf of Nothing -> return () Just f -> do Log.info $ "pgpassfile: " ++ show f setEnv "PGPASSFILE" f return . Just $ DB.PostgreSQL str (Just f, Nothing) -> return . Just $ DB.File f (Nothing, Nothing) -> return Nothing _ -> do Log.error "only one data source can be used" exitFailure newOAuth2Client :: (Text, OAuth2Conf) -> IO (Text, OAuth2Client) newOAuth2Client (name, cfg) = case HM.lookup name OAuth2.providers of Nothing -> do Log.error $ "OAuth2 provider " ++ show name ++ " is not supported" exitFailure Just provider -> do Log.info $ "oauth2: adding " ++ show name return (name, provider (client_id, client_secret)) where client_id = pack $ oa2ClientId cfg client_secret = pack $ oa2ClientSecret cfg newBackendManager :: BackendConf -> IO Manager newBackendManager be = do openConn <- case (beSocket be, bePort be) of (Just f, Nothing) -> do Log.info $ "backend `" ++ beName be ++ "' on UNIX socket " ++ f return $ openUnixSocketConnection f (Nothing, Just n) -> do let svc = show n Log.info $ "backend `" ++ beName be ++ "' on " ++ beAddress be ++ ":" ++ svc return $ openTCPConnection (beAddress be) svc _ -> do Log.error "either backend port number or UNIX socket path is required." exitFailure newManager defaultManagerSettings { managerRawConnection = return $ \_ _ _ -> openConn , managerConnCount = beConnCount be , managerResponseTimeout = responseTimeoutMicro (1000000 * beTimeout be) } newServer :: ConfigFile -> IO (Settings -> Socket -> Application -> IO ()) newServer cf | cfSsl cf = case (cfSslKey cf, cfSslCert cf) of (Just k, Just c) -> return $ runTLSSocket (tlsSettingsChain c (cfSslCertChain cf) k) _ -> do Log.error "missings SSL certificate" exitFailure | otherwise = do Log.warn "not using SSL!" return runSettingsSocket openUnixSocketConnection :: FilePath -> IO Connection openUnixSocketConnection f = bracketOnError (socket AF_UNIX Stream 0) close (\s -> do connect s (SockAddrUnix f) socketConnection s 8192) openTCPConnection :: String -> String -> IO Connection openTCPConnection host svc = do addr:_ <- getAddrInfo (Just hints) (Just host) (Just svc) bracketOnError (socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) close (\s -> do connect s (addrAddress addr) socketConnection s 8192) where hints = defaultHints {addrFlags = [AI_NUMERICSERV], addrSocketType = Stream} readConfigFile :: FilePath -> IO ConfigFile readConfigFile f = do r <- decodeFileEither f case r of Left e -> do hPutStrLn stderr $ "FATAL: " ++ f ++ ": " ++ show e exitFailure Right cf -> return cf
ip1981/sproxy2
src/Sproxy/Server.hs
mit
7,052
0
19
1,651
2,164
1,100
1,064
207
5
module Parser.Evaluator where import Parser.Types.LispVal eval :: LispVal -> LispVal eval (List [Atom "quote", val]) = val eval (List [Atom f, val]) = maybe (Bool False) ($ val) $ lookup f symbols eval (List (Atom f : args)) = apply f $ map eval args eval val = val apply :: String -> [LispVal] -> LispVal apply f args = maybe (Bool False) ($ args) $ lookup f primitives primitives :: [(String, [LispVal] -> LispVal)] primitives = [("+", numericBinop (+)), ("-", numericBinop (-)), ("*", numericBinop (*)), ("/", numericBinop div), ("mod", numericBinop mod), ("quotient", numericBinop quot), ("remainder", numericBinop rem), ("symbol?", isSymbol), ("string?", isString), ("number?", isNumber)] symbols :: [(String, LispVal -> LispVal)] symbols = [("symbol->string", symbolToString), ("string->symbol", stringToSymbol)] -- -- Symbolic Functions -- isSymbol :: [LispVal] -> LispVal isSymbol = Bool . all isAtom' where isAtom' :: LispVal -> Bool isAtom' (Atom _) = True isAtom' _ = False symbolToString :: LispVal -> LispVal symbolToString (Atom a) = String a symbolToString _ = String "" stringToSymbol :: LispVal -> LispVal stringToSymbol (String s) = Atom s stringToSymbol _ = Atom "" -- -- String Functions -- isString :: [LispVal] -> LispVal isString = Bool . all isString' where isString' :: LispVal -> Bool isString' (String _) = True isString' _ = False -- -- Numeric Functions -- isNumber :: [LispVal] -> LispVal isNumber = Bool . all isNumber' where isNumber' :: LispVal -> Bool isNumber' (Number _) = True isNumber' _ = False numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> LispVal numericBinop op params = Number $ foldl1 op $ map unpackNum params where unpackNum :: LispVal -> Integer unpackNum (Number n) = n unpackNum _ = 0
slogsdon/haskell-exercises
write-a-scheme/evaluation-part1/src/Parser/Evaluator.hs
mit
2,042
0
10
569
709
390
319
49
2
module ParserSpec (spec) where import Test.Hspec import Language.SimplyTyped.Syntax import Language.SimplyTyped.Parser import Text.Parsec import Text.Parsec.Error type PTerm = Term String String parseTerm :: String -> Either ParseError PTerm parseTerm = parse term "" -- equality instance needed for equality checking on right argument instance Eq ParseError where x == y = errorMessages x == errorMessages y isLeft :: Either a b -> Bool isLeft (Left _) = True isLeft (Right _) = False spec :: Spec spec = do describe "atoms" $ do it "should parse true" $ do parseTerm "true" `shouldBe` Right TmTrue it "should parse false" $ do parseTerm "false" `shouldBe` Right TmFalse it "should parse variables with underscored" $ do parseTerm "some_variable3" `shouldBe` Right (TmVar "some_variable3") it "should not parse variables with operator characters" $ do parseTerm "$" `shouldSatisfy` isLeft it "should not parse identifiers that start with numbers" $ do parseTerm "3some" `shouldSatisfy` isLeft it "should parse identifiers that start with reserved words" $ do parseTerm "truely" `shouldBe` Right (TmVar "truely") parseTerm "if_statement" `shouldBe` Right (TmVar "if_statement") describe "if statements" $ do it "should parse basic if" $ do parseTerm "if true then true else false" `shouldBe` Right (TmIf TmTrue TmTrue TmFalse) it "should parse nested ifs" $ do parseTerm "if if if false then true else false then true else false then true else false" `shouldBe` Right (TmIf (TmIf (TmIf TmFalse TmTrue TmFalse) TmTrue TmFalse) TmTrue TmFalse) it "should fail with incomplete if statement" $ do parseTerm "if true then false" `shouldSatisfy` isLeft it "should handle abstractions in branches" $ do parseTerm "if (\\x : Bool. y) then x else y" `shouldBe` Right (TmIf (TmAbs "x" TyBool (TmVar "y")) (TmVar "x") (TmVar "y")) parseTerm "if true then \\x : Bool. if x then true else false else \\y:Bool. y" `shouldBe` Right (TmIf TmTrue (TmAbs "x" TyBool (TmIf (TmVar "x") TmTrue TmFalse)) (TmAbs "y" TyBool (TmVar "y"))) it "should extend as far to the right as possible" $ do parseTerm "if true then true else f x" `shouldBe` Right (TmIf TmTrue TmTrue (TmApp (TmVar "f") (TmVar "x"))) it "should handle applications in branches" $ do parseTerm "if x y then f g else f x" `shouldBe` Right (TmIf (TmApp (TmVar "x") (TmVar "y")) (TmApp (TmVar "f") (TmVar "g")) (TmApp (TmVar "f") (TmVar "x"))) describe "abstractions" $ do it "should parse abstraction" $ do parseTerm "\\x : Bool. x" `shouldBe` Right (TmAbs "x" TyBool (TmVar "x")) it "should ignore whitespace" $ do parseTerm "\\x: Bool. x" `shouldBe` Right (TmAbs "x" TyBool (TmVar "x")) parseTerm "\\x :Bool. x" `shouldBe` Right (TmAbs "x" TyBool (TmVar "x")) parseTerm "\\x : Bool . x" `shouldBe` Right (TmAbs "x" TyBool (TmVar "x")) parseTerm "\\x : Bool .x" `shouldBe` Right (TmAbs "x" TyBool (TmVar "x")) it "should extend as far to the right as possible" $ do parseTerm "\\x : (Bool -> (Bool -> Bool)). (x true) true" `shouldBe` Right (TmAbs "x" (TyArr TyBool (TyArr TyBool TyBool)) (TmApp (TmApp (TmVar "x") TmTrue) TmTrue)) parseTerm "\\x: Bool. x true" `shouldBe` Right (TmAbs "x" TyBool (TmApp (TmVar "x") TmTrue)) it "should handle nested abstractions" $ do parseTerm "\\x: Bool -> Bool. \\y:Bool. x y" `shouldBe` Right (TmAbs "x" (TyArr TyBool TyBool) (TmAbs "y" TyBool (TmApp (TmVar "x") (TmVar "y")))) it "should parse an expression with undefined variables" $ do parseTerm "\\z: Bool. x" `shouldBe` Right (TmAbs "z" TyBool (TmVar "x")) it "should error if abstraction has no type" $ do parseTerm "\\x. x" `shouldSatisfy` isLeft describe "let" $ do it "should parse let expression" $ do parseTerm "let x = true in x" `shouldBe` Right (TmLet "x" TmTrue (TmVar "x")) it "should parse as far to the right as possible" $ do parseTerm "let x = true in x y" `shouldBe` Right (TmLet "x" TmTrue (TmApp (TmVar "x") (TmVar "y"))) it "should handle nested lets" $ do parseTerm "let x = let y = true in y z in x" `shouldBe` Right (TmLet "x" (TmLet "y" TmTrue (TmApp (TmVar "y") (TmVar "z"))) (TmVar "x")) describe "type declarations" $ do it "should parse type declarations right associatively" $ do parseTerm "\\x : (Bool -> Bool -> Bool). x" `shouldBe` Right (TmAbs "x" (TyArr TyBool (TyArr TyBool TyBool)) (TmVar "x")) it "should handle parens in types" $ do parseTerm "\\x : (Bool -> Bool) -> Bool. x" `shouldBe` Right (TmAbs "x" (TyArr (TyArr TyBool TyBool) TyBool) (TmVar "x")) it "should not require parens" $ do parseTerm "\\z : Bool -> Bool.z" `shouldBe` Right (TmAbs "z" (TyArr TyBool TyBool) (TmVar "z")) it "should error on incomplete declarations" $ do parseTerm "\\x: Bool -> . z" `shouldSatisfy` isLeft describe "applications" $ do it "should parse applications" $ do parseTerm "(\\x: Bool. true) false" `shouldBe` Right (TmApp (TmAbs "x" TyBool TmTrue) TmFalse) it "should parse incorrect applications" $ do parseTerm "true false" `shouldBe` Right (TmApp TmTrue TmFalse) it "should parse an application with a top level paresn" $ do parseTerm "(f x)" `shouldBe` Right (TmApp (TmVar "f") (TmVar "x")) it "should associate to the left" $ do parseTerm "(\\x: Bool. true) true (\\y: Bool. false)" `shouldBe` Right (TmApp (TmApp (TmAbs "x" TyBool TmTrue) TmTrue) (TmAbs "y" TyBool TmFalse)) it "should allow parens to associate to the right" $ do parseTerm "true (true (true false))" `shouldBe` Right (TmApp TmTrue (TmApp TmTrue (TmApp TmTrue TmFalse))) it "should parse applications of if statements" $ do parseTerm "(if x then y else z) (if a then b else c)" `shouldBe` Right (TmApp (TmIf (TmVar "x") (TmVar "y") (TmVar "z")) (TmIf (TmVar "a") (TmVar "b") (TmVar "c"))) it "should parse applications of if statements" $ do parseTerm "if x then y else z (if a then b else c)" `shouldBe` Right (TmIf (TmVar "x") (TmVar "y") (TmApp (TmVar "z") (TmIf (TmVar "a") (TmVar "b") (TmVar "c")))) it "should error if applied to invalid argument" $ do parseTerm "x if a then b else c" `shouldSatisfy` isLeft parseTerm "x \\x : Bool. x" `shouldSatisfy` isLeft
robertclancy/tapl
simply-typed/tests/ParserSpec.hs
gpl-2.0
7,106
0
22
2,078
2,001
951
1,050
95
1
f4 :: Int -> Int f4 x | x < 0 = 0 | x > 0 = 1 | otherwise = 2
rdnetto/H2V
docs/Design Presentation/src/patguard.hs
gpl-2.0
82
0
8
43
50
23
27
5
1
{-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving , OverloadedStrings #-} -- | Defines a set of various functions used in API requests/responses. module Util.API ( APIError (..), ToAPIError (..) , sendObjectCreated, sendNoContent, sendErrorResponse, sendPermissionDenied , tooManyRequests429 , withFormSuccess, withUploadOwner ) where import Import import Data.String (IsString) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Network.HTTP.Types.Status ( Status, mkStatus, badRequest400, created201, noContent204, forbidden403 ) import Text.Blaze (Markup) import Text.Blaze.Renderer.Text (renderMarkup) import Util.Hmac (Hmac) newtype APIError = APIError Text deriving (Show, IsString, ToJSON) class ToAPIError a where toAPIError :: a -> APIError instance ToAPIError APIError where toAPIError = id instance ToAPIError Text where toAPIError = APIError instance ToAPIError [Char] where toAPIError = APIError . T.pack instance ToAPIError Markup where toAPIError = APIError . TL.toStrict . renderMarkup -- | Responds to the client with a 201 Created and a JSON object containing the -- HMAC of the object and the URI to the object. sendObjectCreated :: MonadHandler m => Hmac -> Route (HandlerSite m) -> m a sendObjectCreated hmac route = do url <- getUrlRender <*> pure route addHeader "Location" url sendResponseStatus created201 $ object [ "id" .= hmac, "uri" .= url ] -- | Responds to the client with a 204 created indicating a successful -- operation. sendNoContent :: MonadHandler m => m a sendNoContent = sendResponseStatus noContent204 () -- | Responds to the client with a status code and a set of errors in an JSON -- array. sendErrorResponse :: (MonadHandler m, ToAPIError a) => Status -> [a] -> m b sendErrorResponse status errs = sendResponseStatus status (array $ map toAPIError errs) -- | Responds to the client with a 403 status code and a JSON array containing -- the error saying that he has no ownership on the object. sendPermissionDenied :: MonadHandler m => m a sendPermissionDenied = let msg = "You are not the owner of this resource." :: Text in sendErrorResponse forbidden403 [msg] tooManyRequests429 :: Status tooManyRequests429 = mkStatus 429 "Too Many Requests" -- | Executes the inner action if the form has been correctly encoded, responds -- with a 400 Bad request with a JSON array of errors otherwise. withFormSuccess :: MonadHandler m => FormResult a -> (a -> m b) -> m b withFormSuccess (FormSuccess a) f = f a withFormSuccess (FormFailure errs) _ = sendErrorResponse badRequest400 errs withFormSuccess FormMissing _ = sendErrorResponse badRequest400 ["Missing Form." :: Text] -- | Executes the inner database transaction and then the action if the current -- user is an admin of the upload. Returns a 403 status code if the user is not -- the owner of the upload and a 404 status code if the upload doesn't exists. withUploadOwner :: Hmac -> Handler b -> (Entity Upload -> YesodDB App a) -> Handler b withUploadOwner hmac onSuccess transac = do mAdminKey <- getAdminKey case mAdminKey of Just _ -> do success <- runDB $ do entity@(Entity _ upload) <- getBy404 $ UniqueUploadHmac hmac if isAdmin upload mAdminKey then transac entity >> return True else return False if success then onSuccess else sendPermissionDenied Nothing -> sendPermissionDenied
RaphaelJ/getwebb.org
Util/API.hs
gpl-3.0
3,647
0
19
835
747
398
349
64
4
{-# LANGUAGE BangPatterns #-} -- | module PhonebookSpec where import Control.Concurrent import Phonebook import Prelude hiding (lookup) import Test.Hspec mkNumber :: Integer -> String mkNumber = concat . map ( : "-") . show spec :: Spec spec = do describe "Phonebook" $ do it "should be able to find what we inserted" $ do pbook <- new insert pbook "Jane" "99" mNumber <- lookup pbook "Jane" mNumber `shouldBe` Just "99" -- This test case is useful to compare a lazy version of the `insert` -- function against a strict implementation. In the cabal file the maximum -- ammount of memory is limited (using the `with-rtsopts` flag) in such a -- way that this test case will fail on an lazy implmentation of insert. it "should not stack overflow" $ do pbook <- new let insertions = [insert pbook ("name" ++ show n) (mkNumber n) | n <- [1..5200]] sequence_ insertions mNumber <- lookup pbook "name99" mNumber `shouldBe` Just (mkNumber 99) mNumber <- lookup pbook "unkown" mNumber `shouldBe` Nothing
capitanbatata/marlows-parconc-exercises
parconc-ch07/test/PhonebookSpec.hs
gpl-3.0
1,165
0
20
339
254
128
126
26
1
module PulseLambda.Debuggable ( Debuggable , debug , ansiColorRedBright , ansiColorGreenBright , ansiColorYellowBright , ansiColorBlueBright , ansiColorMagentaBright , ansiColorCyanBright , ansiColorRed , ansiColorGreen , ansiColorYellow , ansiColorBlue , ansiColorMagenta , ansiColorCyan , ansiColorReset ) where class Debuggable a where debug :: a -> String ansiColorRedBright :: String ansiColorRedBright = "\x1b[31;1m" ansiColorGreenBright :: String ansiColorGreenBright = "\x1b[32;1m" ansiColorYellowBright :: String ansiColorYellowBright = "\x1b[33;1m" ansiColorBlueBright :: String ansiColorBlueBright = "\x1b[34;1m" ansiColorMagentaBright :: String ansiColorMagentaBright = "\x1b[35;1m" ansiColorCyanBright :: String ansiColorCyanBright = "\x1b[36;1m" ansiColorRed :: String ansiColorRed = "\x1b[31m" ansiColorGreen :: String ansiColorGreen = "\x1b[32m" ansiColorYellow :: String ansiColorYellow = "\x1b[33m" ansiColorBlue :: String ansiColorBlue = "\x1b[34m" ansiColorMagenta :: String ansiColorMagenta = "\x1b[35m" ansiColorCyan :: String ansiColorCyan = "\x1b[36m" ansiColorReset :: String ansiColorReset = "\x1b[0m"
brunoczim/PulseLambda
PulseLambda/Debuggable.hs
gpl-3.0
1,146
0
7
139
201
122
79
44
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.YouTube.VideoAbuseReportReasons.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns a list of abuse reasons that can be used for reporting abusive -- videos. -- -- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.videoAbuseReportReasons.list@. module Network.Google.Resource.YouTube.VideoAbuseReportReasons.List ( -- * REST Resource VideoAbuseReportReasonsListResource -- * Creating a Request , videoAbuseReportReasonsList , VideoAbuseReportReasonsList -- * Request Lenses , varrlPart , varrlHl ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.videoAbuseReportReasons.list@ method which the -- 'VideoAbuseReportReasonsList' request conforms to. type VideoAbuseReportReasonsListResource = "youtube" :> "v3" :> "videoAbuseReportReasons" :> QueryParam "part" Text :> QueryParam "hl" Text :> QueryParam "alt" AltJSON :> Get '[JSON] VideoAbuseReportReasonListResponse -- | Returns a list of abuse reasons that can be used for reporting abusive -- videos. -- -- /See:/ 'videoAbuseReportReasonsList' smart constructor. data VideoAbuseReportReasonsList = VideoAbuseReportReasonsList' { _varrlPart :: !Text , _varrlHl :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'VideoAbuseReportReasonsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'varrlPart' -- -- * 'varrlHl' videoAbuseReportReasonsList :: Text -- ^ 'varrlPart' -> VideoAbuseReportReasonsList videoAbuseReportReasonsList pVarrlPart_ = VideoAbuseReportReasonsList' { _varrlPart = pVarrlPart_ , _varrlHl = "en_US" } -- | The part parameter specifies the videoCategory resource parts that the -- API response will include. Supported values are id and snippet. varrlPart :: Lens' VideoAbuseReportReasonsList Text varrlPart = lens _varrlPart (\ s a -> s{_varrlPart = a}) -- | The hl parameter specifies the language that should be used for text -- values in the API response. varrlHl :: Lens' VideoAbuseReportReasonsList Text varrlHl = lens _varrlHl (\ s a -> s{_varrlHl = a}) instance GoogleRequest VideoAbuseReportReasonsList where type Rs VideoAbuseReportReasonsList = VideoAbuseReportReasonListResponse type Scopes VideoAbuseReportReasonsList = '["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtube.readonly"] requestClient VideoAbuseReportReasonsList'{..} = go (Just _varrlPart) (Just _varrlHl) (Just AltJSON) youTubeService where go = buildClient (Proxy :: Proxy VideoAbuseReportReasonsListResource) mempty
rueshyna/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/VideoAbuseReportReasons/List.hs
mpl-2.0
3,745
0
13
818
392
237
155
63
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.RegionHealthChecks.Patch -- 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) -- -- Updates a HealthCheck resource in the specified project using the data -- included in the request. This method supports PATCH semantics and uses -- the JSON merge patch format and processing rules. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionHealthChecks.patch@. module Network.Google.Resource.Compute.RegionHealthChecks.Patch ( -- * REST Resource RegionHealthChecksPatchResource -- * Creating a Request , regionHealthChecksPatch , RegionHealthChecksPatch -- * Request Lenses , rhcpRequestId , rhcpHealthCheck , rhcpProject , rhcpPayload , rhcpRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionHealthChecks.patch@ method which the -- 'RegionHealthChecksPatch' request conforms to. type RegionHealthChecksPatchResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "healthChecks" :> Capture "healthCheck" Text :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] HealthCheck :> Patch '[JSON] Operation -- | Updates a HealthCheck resource in the specified project using the data -- included in the request. This method supports PATCH semantics and uses -- the JSON merge patch format and processing rules. -- -- /See:/ 'regionHealthChecksPatch' smart constructor. data RegionHealthChecksPatch = RegionHealthChecksPatch' { _rhcpRequestId :: !(Maybe Text) , _rhcpHealthCheck :: !Text , _rhcpProject :: !Text , _rhcpPayload :: !HealthCheck , _rhcpRegion :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegionHealthChecksPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rhcpRequestId' -- -- * 'rhcpHealthCheck' -- -- * 'rhcpProject' -- -- * 'rhcpPayload' -- -- * 'rhcpRegion' regionHealthChecksPatch :: Text -- ^ 'rhcpHealthCheck' -> Text -- ^ 'rhcpProject' -> HealthCheck -- ^ 'rhcpPayload' -> Text -- ^ 'rhcpRegion' -> RegionHealthChecksPatch regionHealthChecksPatch pRhcpHealthCheck_ pRhcpProject_ pRhcpPayload_ pRhcpRegion_ = RegionHealthChecksPatch' { _rhcpRequestId = Nothing , _rhcpHealthCheck = pRhcpHealthCheck_ , _rhcpProject = pRhcpProject_ , _rhcpPayload = pRhcpPayload_ , _rhcpRegion = pRhcpRegion_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). rhcpRequestId :: Lens' RegionHealthChecksPatch (Maybe Text) rhcpRequestId = lens _rhcpRequestId (\ s a -> s{_rhcpRequestId = a}) -- | Name of the HealthCheck resource to patch. rhcpHealthCheck :: Lens' RegionHealthChecksPatch Text rhcpHealthCheck = lens _rhcpHealthCheck (\ s a -> s{_rhcpHealthCheck = a}) -- | Project ID for this request. rhcpProject :: Lens' RegionHealthChecksPatch Text rhcpProject = lens _rhcpProject (\ s a -> s{_rhcpProject = a}) -- | Multipart request metadata. rhcpPayload :: Lens' RegionHealthChecksPatch HealthCheck rhcpPayload = lens _rhcpPayload (\ s a -> s{_rhcpPayload = a}) -- | Name of the region scoping this request. rhcpRegion :: Lens' RegionHealthChecksPatch Text rhcpRegion = lens _rhcpRegion (\ s a -> s{_rhcpRegion = a}) instance GoogleRequest RegionHealthChecksPatch where type Rs RegionHealthChecksPatch = Operation type Scopes RegionHealthChecksPatch = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient RegionHealthChecksPatch'{..} = go _rhcpProject _rhcpRegion _rhcpHealthCheck _rhcpRequestId (Just AltJSON) _rhcpPayload computeService where go = buildClient (Proxy :: Proxy RegionHealthChecksPatchResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionHealthChecks/Patch.hs
mpl-2.0
5,607
0
18
1,262
636
380
256
100
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.TargetHTTPProxies.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) -- -- Creates a TargetHttpProxy resource in the specified project using the -- data included in the request. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetHttpProxies.insert@. module Network.Google.Resource.Compute.TargetHTTPProxies.Insert ( -- * REST Resource TargetHTTPProxiesInsertResource -- * Creating a Request , targetHTTPProxiesInsert , TargetHTTPProxiesInsert -- * Request Lenses , thttppiProject , thttppiPayload ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetHttpProxies.insert@ method which the -- 'TargetHTTPProxiesInsert' request conforms to. type TargetHTTPProxiesInsertResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "targetHttpProxies" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TargetHTTPProxy :> Post '[JSON] Operation -- | Creates a TargetHttpProxy resource in the specified project using the -- data included in the request. -- -- /See:/ 'targetHTTPProxiesInsert' smart constructor. data TargetHTTPProxiesInsert = TargetHTTPProxiesInsert' { _thttppiProject :: !Text , _thttppiPayload :: !TargetHTTPProxy } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TargetHTTPProxiesInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'thttppiProject' -- -- * 'thttppiPayload' targetHTTPProxiesInsert :: Text -- ^ 'thttppiProject' -> TargetHTTPProxy -- ^ 'thttppiPayload' -> TargetHTTPProxiesInsert targetHTTPProxiesInsert pThttppiProject_ pThttppiPayload_ = TargetHTTPProxiesInsert' { _thttppiProject = pThttppiProject_ , _thttppiPayload = pThttppiPayload_ } -- | Project ID for this request. thttppiProject :: Lens' TargetHTTPProxiesInsert Text thttppiProject = lens _thttppiProject (\ s a -> s{_thttppiProject = a}) -- | Multipart request metadata. thttppiPayload :: Lens' TargetHTTPProxiesInsert TargetHTTPProxy thttppiPayload = lens _thttppiPayload (\ s a -> s{_thttppiPayload = a}) instance GoogleRequest TargetHTTPProxiesInsert where type Rs TargetHTTPProxiesInsert = Operation type Scopes TargetHTTPProxiesInsert = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient TargetHTTPProxiesInsert'{..} = go _thttppiProject (Just AltJSON) _thttppiPayload computeService where go = buildClient (Proxy :: Proxy TargetHTTPProxiesInsertResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetHTTPProxies/Insert.hs
mpl-2.0
3,676
0
15
815
395
238
157
67
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.Classroom.Courses.Teachers.Delete -- 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) -- -- Deletes a teacher of a course. This method returns the following error -- codes: * \`PERMISSION_DENIED\` if the requesting user is not permitted -- to delete teachers of this course or for access errors. * \`NOT_FOUND\` -- if no teacher of this course has the requested ID or if the course does -- not exist. * \`FAILED_PRECONDITION\` if the requested ID belongs to the -- primary teacher of this course. -- -- /See:/ <https://developers.google.com/classroom/ Google Classroom API Reference> for @classroom.courses.teachers.delete@. module Network.Google.Resource.Classroom.Courses.Teachers.Delete ( -- * REST Resource CoursesTeachersDeleteResource -- * Creating a Request , coursesTeachersDelete , CoursesTeachersDelete -- * Request Lenses , ctdXgafv , ctdUploadProtocol , ctdPp , ctdCourseId , ctdAccessToken , ctdUploadType , ctdUserId , ctdBearerToken , ctdCallback ) where import Network.Google.Classroom.Types import Network.Google.Prelude -- | A resource alias for @classroom.courses.teachers.delete@ method which the -- 'CoursesTeachersDelete' request conforms to. type CoursesTeachersDeleteResource = "v1" :> "courses" :> Capture "courseId" Text :> "teachers" :> Capture "userId" Text :> QueryParam "$.xgafv" Text :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Empty -- | Deletes a teacher of a course. This method returns the following error -- codes: * \`PERMISSION_DENIED\` if the requesting user is not permitted -- to delete teachers of this course or for access errors. * \`NOT_FOUND\` -- if no teacher of this course has the requested ID or if the course does -- not exist. * \`FAILED_PRECONDITION\` if the requested ID belongs to the -- primary teacher of this course. -- -- /See:/ 'coursesTeachersDelete' smart constructor. data CoursesTeachersDelete = CoursesTeachersDelete' { _ctdXgafv :: !(Maybe Text) , _ctdUploadProtocol :: !(Maybe Text) , _ctdPp :: !Bool , _ctdCourseId :: !Text , _ctdAccessToken :: !(Maybe Text) , _ctdUploadType :: !(Maybe Text) , _ctdUserId :: !Text , _ctdBearerToken :: !(Maybe Text) , _ctdCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CoursesTeachersDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ctdXgafv' -- -- * 'ctdUploadProtocol' -- -- * 'ctdPp' -- -- * 'ctdCourseId' -- -- * 'ctdAccessToken' -- -- * 'ctdUploadType' -- -- * 'ctdUserId' -- -- * 'ctdBearerToken' -- -- * 'ctdCallback' coursesTeachersDelete :: Text -- ^ 'ctdCourseId' -> Text -- ^ 'ctdUserId' -> CoursesTeachersDelete coursesTeachersDelete pCtdCourseId_ pCtdUserId_ = CoursesTeachersDelete' { _ctdXgafv = Nothing , _ctdUploadProtocol = Nothing , _ctdPp = True , _ctdCourseId = pCtdCourseId_ , _ctdAccessToken = Nothing , _ctdUploadType = Nothing , _ctdUserId = pCtdUserId_ , _ctdBearerToken = Nothing , _ctdCallback = Nothing } -- | V1 error format. ctdXgafv :: Lens' CoursesTeachersDelete (Maybe Text) ctdXgafv = lens _ctdXgafv (\ s a -> s{_ctdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ctdUploadProtocol :: Lens' CoursesTeachersDelete (Maybe Text) ctdUploadProtocol = lens _ctdUploadProtocol (\ s a -> s{_ctdUploadProtocol = a}) -- | Pretty-print response. ctdPp :: Lens' CoursesTeachersDelete Bool ctdPp = lens _ctdPp (\ s a -> s{_ctdPp = a}) -- | Identifier of the course. This identifier can be either the -- Classroom-assigned identifier or an alias. ctdCourseId :: Lens' CoursesTeachersDelete Text ctdCourseId = lens _ctdCourseId (\ s a -> s{_ctdCourseId = a}) -- | OAuth access token. ctdAccessToken :: Lens' CoursesTeachersDelete (Maybe Text) ctdAccessToken = lens _ctdAccessToken (\ s a -> s{_ctdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ctdUploadType :: Lens' CoursesTeachersDelete (Maybe Text) ctdUploadType = lens _ctdUploadType (\ s a -> s{_ctdUploadType = a}) -- | Identifier of the teacher to delete. The identifier can be one of the -- following: * the numeric identifier for the user * the email address of -- the user * the string literal \`\"me\"\`, indicating the requesting user ctdUserId :: Lens' CoursesTeachersDelete Text ctdUserId = lens _ctdUserId (\ s a -> s{_ctdUserId = a}) -- | OAuth bearer token. ctdBearerToken :: Lens' CoursesTeachersDelete (Maybe Text) ctdBearerToken = lens _ctdBearerToken (\ s a -> s{_ctdBearerToken = a}) -- | JSONP ctdCallback :: Lens' CoursesTeachersDelete (Maybe Text) ctdCallback = lens _ctdCallback (\ s a -> s{_ctdCallback = a}) instance GoogleRequest CoursesTeachersDelete where type Rs CoursesTeachersDelete = Empty type Scopes CoursesTeachersDelete = '["https://www.googleapis.com/auth/classroom.rosters"] requestClient CoursesTeachersDelete'{..} = go _ctdCourseId _ctdUserId _ctdXgafv _ctdUploadProtocol (Just _ctdPp) _ctdAccessToken _ctdUploadType _ctdBearerToken _ctdCallback (Just AltJSON) classroomService where go = buildClient (Proxy :: Proxy CoursesTeachersDeleteResource) mempty
rueshyna/gogol
gogol-classroom/gen/Network/Google/Resource/Classroom/Courses/Teachers/Delete.hs
mpl-2.0
6,704
0
20
1,615
945
553
392
133
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.Games.Snapshots.Get -- 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) -- -- Retrieves the metadata for a given snapshot ID. -- -- /See:/ <https://developers.google.com/games/ Google Play Game Services Reference> for @games.snapshots.get@. module Network.Google.Resource.Games.Snapshots.Get ( -- * REST Resource SnapshotsGetResource -- * Creating a Request , snapshotsGet , SnapshotsGet -- * Request Lenses , snaXgafv , snaUploadProtocol , snaAccessToken , snaUploadType , snaLanguage , snaCallback , snaSnapshotId ) where import Network.Google.Games.Types import Network.Google.Prelude -- | A resource alias for @games.snapshots.get@ method which the -- 'SnapshotsGet' request conforms to. type SnapshotsGetResource = "games" :> "v1" :> "snapshots" :> Capture "snapshotId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "language" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Snapshot -- | Retrieves the metadata for a given snapshot ID. -- -- /See:/ 'snapshotsGet' smart constructor. data SnapshotsGet = SnapshotsGet' { _snaXgafv :: !(Maybe Xgafv) , _snaUploadProtocol :: !(Maybe Text) , _snaAccessToken :: !(Maybe Text) , _snaUploadType :: !(Maybe Text) , _snaLanguage :: !(Maybe Text) , _snaCallback :: !(Maybe Text) , _snaSnapshotId :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SnapshotsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'snaXgafv' -- -- * 'snaUploadProtocol' -- -- * 'snaAccessToken' -- -- * 'snaUploadType' -- -- * 'snaLanguage' -- -- * 'snaCallback' -- -- * 'snaSnapshotId' snapshotsGet :: Text -- ^ 'snaSnapshotId' -> SnapshotsGet snapshotsGet pSnaSnapshotId_ = SnapshotsGet' { _snaXgafv = Nothing , _snaUploadProtocol = Nothing , _snaAccessToken = Nothing , _snaUploadType = Nothing , _snaLanguage = Nothing , _snaCallback = Nothing , _snaSnapshotId = pSnaSnapshotId_ } -- | V1 error format. snaXgafv :: Lens' SnapshotsGet (Maybe Xgafv) snaXgafv = lens _snaXgafv (\ s a -> s{_snaXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). snaUploadProtocol :: Lens' SnapshotsGet (Maybe Text) snaUploadProtocol = lens _snaUploadProtocol (\ s a -> s{_snaUploadProtocol = a}) -- | OAuth access token. snaAccessToken :: Lens' SnapshotsGet (Maybe Text) snaAccessToken = lens _snaAccessToken (\ s a -> s{_snaAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). snaUploadType :: Lens' SnapshotsGet (Maybe Text) snaUploadType = lens _snaUploadType (\ s a -> s{_snaUploadType = a}) -- | The preferred language to use for strings returned by this method. snaLanguage :: Lens' SnapshotsGet (Maybe Text) snaLanguage = lens _snaLanguage (\ s a -> s{_snaLanguage = a}) -- | JSONP snaCallback :: Lens' SnapshotsGet (Maybe Text) snaCallback = lens _snaCallback (\ s a -> s{_snaCallback = a}) -- | The ID of the snapshot. snaSnapshotId :: Lens' SnapshotsGet Text snaSnapshotId = lens _snaSnapshotId (\ s a -> s{_snaSnapshotId = a}) instance GoogleRequest SnapshotsGet where type Rs SnapshotsGet = Snapshot type Scopes SnapshotsGet = '["https://www.googleapis.com/auth/drive.appdata", "https://www.googleapis.com/auth/games"] requestClient SnapshotsGet'{..} = go _snaSnapshotId _snaXgafv _snaUploadProtocol _snaAccessToken _snaUploadType _snaLanguage _snaCallback (Just AltJSON) gamesService where go = buildClient (Proxy :: Proxy SnapshotsGetResource) mempty
brendanhay/gogol
gogol-games/gen/Network/Google/Resource/Games/Snapshots/Get.hs
mpl-2.0
4,824
0
18
1,182
785
456
329
114
1
{-# LANGUAGE OverloadedStrings #-} {- | Module : $Header$ Description : HTTP request verification tests for authochan. Copyright : (c) plaimi 2015 License : AGPL-3 Maintainer : tempuhs@plaimi.net -} module Authochan.Tests.HTTP (requestTests) where import Control.Monad ( forM, guard, msum, ) import Crypto.Hash ( hashlazy, ) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy as LB import Data.Char ( isHexDigit, ) import Data.Functor ( (<$>), ) import Data.Int ( Int64, ) import Data.List ( nub, ) import Data.Maybe ( isJust, ) import Network.HTTP.Types ( Header, ) import Network.Wai ( rawPathInfo, rawQueryString, requestHeaders, requestMethod, ) import Network.Wai.Test ( SRequest (SRequest), ) import Test.Framework ( Test, testGroup, ) import Test.Framework.Providers.QuickCheck2 ( testProperty, ) import Test.QuickCheck ( Gen, Property, (===), counterexample, elements, listOf, listOf1, ) import Authochan.HTTP ( filterHeaders, parseAuthHeader, requestToMessage, ) import Authochan.Tests.Gen.HTTP ( genHeader, genHeaderName, genSignedSRequest, mutateSRequest, ) requestTests :: [Test] requestTests = [testGroup "HTTP request verification" [testProperty "headers are filtered and sorted correctly" propFilterHeaders ,testProperty "well-formed signed requests are accepted" propRequestWellFormed ,testProperty "signature protects specific parts of request" propStripRequest]] stripRequest :: SRequest -> Maybe ([B.ByteString], Int64, [Header]) stripRequest (SRequest r b) = do p <- parseAuthHeader =<< lookup "Authorization" rh [k, s, n, sx] <- forM ["key", "sid", "nonce", "signature"] (flip lookup p) n' <- msum [Just x | (x, "") <- reads $ B8.unpack n] guard $ B.length sx == 64 && B8.all isHexDigit sx return $ ([k, s, sx, LB.toStrict b, requestMethod r, rawPathInfo r ,rawQueryString r], n', filterHeaders ["Content-Type", "Host"] rh) where rh = requestHeaders r propFilterHeaders :: Gen Property propFilterHeaders = do f <- nub <$> listOf1 genHeaderName nx <- listOf1 genHeaderName hs <- listOf $ elements [f, nx] >>= genHeader let r = filterHeaders f hs return $ r === concatMap (\x -> filter ((== x) . fst) r) f propRequestWellFormed :: Gen Property propRequestWellFormed = do SRequest r b <- genSignedSRequest return $ counterexample (show r) $ isJust $ requestToMessage r (hashlazy b) propStripRequest :: Gen Property propStripRequest = do r <- genSignedSRequest r' <- mutateSRequest r return $ counterexample (s r ++ "\n" ++ s r') $ (stripRequest r == stripRequest r') === (m r == m r') where m (SRequest r b) = requestToMessage r (hashlazy b) s sr@(SRequest r b) = show (r, b, stripRequest sr)
plaimi/authochan
test/Authochan/Tests/HTTP.hs
agpl-3.0
3,054
0
14
752
887
491
396
105
1
triangle :: Integer -> Integer triangle 0 = 0 triangle n = n + triangle (n - 1) count :: Eq a => a -> [a] -> Integer count k [] = 0 count k (x:xs) = if k == x then 1 + count k xs else count k xs euclid :: (Integer, Integer) -> Integer euclid (a, b) | a == b = a | a > b = euclid (a - b, b) | otherwise = euclid (b - a, a) funkyMap :: (a -> b) -> (a -> b) -> [a] -> [b] -- split list into two : (odds, evens) split :: [a] -> ([a], [a]) split [] = ([], []) split [x] = ([x], []) split (x: y: xs) = (x : xp, y : yp) where (xp, yp) = split xs -- f applied to even positions, g applied to odd positions funkyMap f g [] = [] funkyMap f g [x] = [(f x)] funkyMap f g (x:y:xs) = (f x) : (g y) : (funkyMap f g xs)
dongarerahul/edx-haskell
chapter-8-lab.hs
apache-2.0
749
0
8
222
453
242
211
18
2
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QStyleOptionToolBoxV2.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:16 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QStyleOptionToolBoxV2 ( QqStyleOptionToolBoxV2(..) ,QqStyleOptionToolBoxV2_nf(..) ,qStyleOptionToolBoxV2_delete ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QStyleOptionToolBoxV2 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 class QqStyleOptionToolBoxV2 x1 where qStyleOptionToolBoxV2 :: x1 -> IO (QStyleOptionToolBoxV2 ()) instance QqStyleOptionToolBoxV2 (()) where qStyleOptionToolBoxV2 () = withQStyleOptionToolBoxV2Result $ qtc_QStyleOptionToolBoxV2 foreign import ccall "qtc_QStyleOptionToolBoxV2" qtc_QStyleOptionToolBoxV2 :: IO (Ptr (TQStyleOptionToolBoxV2 ())) instance QqStyleOptionToolBoxV2 ((QStyleOptionToolBoxV2 t1)) where qStyleOptionToolBoxV2 (x1) = withQStyleOptionToolBoxV2Result $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionToolBoxV21 cobj_x1 foreign import ccall "qtc_QStyleOptionToolBoxV21" qtc_QStyleOptionToolBoxV21 :: Ptr (TQStyleOptionToolBoxV2 t1) -> IO (Ptr (TQStyleOptionToolBoxV2 ())) instance QqStyleOptionToolBoxV2 ((QStyleOptionToolBox t1)) where qStyleOptionToolBoxV2 (x1) = withQStyleOptionToolBoxV2Result $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionToolBoxV22 cobj_x1 foreign import ccall "qtc_QStyleOptionToolBoxV22" qtc_QStyleOptionToolBoxV22 :: Ptr (TQStyleOptionToolBox t1) -> IO (Ptr (TQStyleOptionToolBoxV2 ())) class QqStyleOptionToolBoxV2_nf x1 where qStyleOptionToolBoxV2_nf :: x1 -> IO (QStyleOptionToolBoxV2 ()) instance QqStyleOptionToolBoxV2_nf (()) where qStyleOptionToolBoxV2_nf () = withObjectRefResult $ qtc_QStyleOptionToolBoxV2 instance QqStyleOptionToolBoxV2_nf ((QStyleOptionToolBoxV2 t1)) where qStyleOptionToolBoxV2_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionToolBoxV21 cobj_x1 instance QqStyleOptionToolBoxV2_nf ((QStyleOptionToolBox t1)) where qStyleOptionToolBoxV2_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionToolBoxV22 cobj_x1 instance Qposition (QStyleOptionToolBoxV2 a) (()) (IO (Int)) where position x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionToolBoxV2_position cobj_x0 foreign import ccall "qtc_QStyleOptionToolBoxV2_position" qtc_QStyleOptionToolBoxV2_position :: Ptr (TQStyleOptionToolBoxV2 a) -> IO CInt instance QselectedPosition (QStyleOptionToolBoxV2 a) (()) where selectedPosition x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionToolBoxV2_selectedPosition cobj_x0 foreign import ccall "qtc_QStyleOptionToolBoxV2_selectedPosition" qtc_QStyleOptionToolBoxV2_selectedPosition :: Ptr (TQStyleOptionToolBoxV2 a) -> IO CInt instance QsetPosition (QStyleOptionToolBoxV2 a) ((QStyleOptionToolBoxV2TabPosition)) where setPosition x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionToolBoxV2_setPosition cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QStyleOptionToolBoxV2_setPosition" qtc_QStyleOptionToolBoxV2_setPosition :: Ptr (TQStyleOptionToolBoxV2 a) -> CLong -> IO () instance QsetSelectedPosition (QStyleOptionToolBoxV2 a) ((QStyleOptionToolBoxV2SelectedPosition)) where setSelectedPosition x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionToolBoxV2_setSelectedPosition cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QStyleOptionToolBoxV2_setSelectedPosition" qtc_QStyleOptionToolBoxV2_setSelectedPosition :: Ptr (TQStyleOptionToolBoxV2 a) -> CLong -> IO () qStyleOptionToolBoxV2_delete :: QStyleOptionToolBoxV2 a -> IO () qStyleOptionToolBoxV2_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionToolBoxV2_delete cobj_x0 foreign import ccall "qtc_QStyleOptionToolBoxV2_delete" qtc_QStyleOptionToolBoxV2_delete :: Ptr (TQStyleOptionToolBoxV2 a) -> IO ()
uduki/hsQt
Qtc/Gui/QStyleOptionToolBoxV2.hs
bsd-2-clause
4,344
0
12
551
937
490
447
-1
-1
{-# LANGUAGE BangPatterns, FlexibleContexts #-} -- | -- Module : Statistics.Math -- Copyright : (c) 2009, 2011 Bryan O'Sullivan -- License : BSD3 -- -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : portable -- -- Mathematical functions for statistics. -- -- DEPRECATED. Use package math-functions instead. This module is just -- reexports functions from 'Numeric.SpecFunctions', -- 'Numeric.SpecFunctions.Extra' and 'Numeric.Polynomial.Chebyshev'. module Statistics.Math {-# DEPRECATED "Use package math-function" #-} ( module Numeric.Polynomial.Chebyshev , module Numeric.SpecFunctions , module Numeric.SpecFunctions.Extra ) where import Numeric.Polynomial.Chebyshev import Numeric.SpecFunctions import Numeric.SpecFunctions.Extra
00tau/statistics
Statistics/Math.hs
bsd-2-clause
791
0
5
115
61
46
15
9
0
module Penny.Account where import Data.Text (Text) import Data.Sequence (Seq) type SubAccount = Text -- | An account contains a set of related postings. It is a sequence -- of 'SubAccount', with each successive 'SubAccount' being a subset -- of the last, such as -- -- @["Assets", "Current", "Checking"]@ type Account = Seq SubAccount
massysett/penny
penny/lib/Penny/Account.hs
bsd-3-clause
339
0
5
57
46
30
16
5
0
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor, PatternGuards #-} module Idris.ElabDecls where import Idris.AbsSyntax import Idris.ASTUtils import Idris.DSL import Idris.Error import Idris.Delaborate import Idris.Directives import Idris.Imports import Idris.Elab.Term import Idris.Coverage import Idris.DataOpts import Idris.Providers import Idris.Primitives import Idris.Inliner import Idris.PartialEval import Idris.DeepSeq import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting) import IRTS.Lang import Idris.Elab.Utils import Idris.Elab.Type import Idris.Elab.Clause import Idris.Elab.Data import Idris.Elab.Record import Idris.Elab.Class import Idris.Elab.Instance import Idris.Elab.Provider import Idris.Elab.Transform import Idris.Elab.Value import Idris.Core.TT import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.Typecheck import Idris.Core.CaseTree import Idris.Docstrings hiding (Unchecked) import Prelude hiding (id, (.)) import Control.Category import Control.Applicative hiding (Const) import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import Data.List import Data.Maybe import Debug.Trace import qualified Data.Map as Map import qualified Data.Set as S import qualified Data.Text as T import Data.Char(isLetter, toLower) import Data.List.Split (splitOn) import Util.Pretty(pretty, text) -- Top level elaborator info, supporting recursive elaboration recinfo :: ElabInfo recinfo = EInfo [] emptyContext id Nothing Nothing elabDecl' -- | Return the elaborated term which calls 'main' elabMain :: Idris Term elabMain = do (m, _) <- elabVal recinfo ERHS (PApp fc (PRef fc (sUN "run__IO")) [pexp $ PRef fc (sNS (sUN "main") ["Main"])]) return m where fc = fileFC "toplevel" -- | Elaborate primitives elabPrims :: Idris () elabPrims = do mapM_ (elabDecl' EAll recinfo) (map (\(opt, decl, docs, argdocs) -> PData docs argdocs defaultSyntax (fileFC "builtin") opt decl) (zip4 [inferOpts, eqOpts] [inferDecl, eqDecl] [emptyDocstring, eqDoc] [[], eqParamDoc])) addNameHint eqTy (sUN "prf") mapM_ elabPrim primitives -- Special case prim__believe_me because it doesn't work on just constants elabBelieveMe -- Finally, syntactic equality elabSynEq where elabPrim :: Prim -> Idris () elabPrim (Prim n ty i def sc tot) = do updateContext (addOperator n ty i (valuePrim def)) setTotality n tot i <- getIState putIState i { idris_scprims = (n, sc) : idris_scprims i } valuePrim :: ([Const] -> Maybe Const) -> [Value] -> Maybe Value valuePrim prim vals = fmap VConstant (mapM getConst vals >>= prim) getConst (VConstant c) = Just c getConst _ = Nothing p_believeMe [_,_,x] = Just x p_believeMe _ = Nothing believeTy = Bind (sUN "a") (Pi Nothing (TType (UVar (-2))) (TType (UVar (-1)))) (Bind (sUN "b") (Pi Nothing (TType (UVar (-2))) (TType (UVar (-1)))) (Bind (sUN "x") (Pi Nothing (V 1) (TType (UVar (-1)))) (V 1))) elabBelieveMe = do let prim__believe_me = sUN "prim__believe_me" updateContext (addOperator prim__believe_me believeTy 3 p_believeMe) setTotality prim__believe_me (Partial NotCovering) i <- getIState putIState i { idris_scprims = (prim__believe_me, (3, LNoOp)) : idris_scprims i } p_synEq [t,_,x,y] | x == y = Just (VApp (VApp vnJust VErased) (VApp (VApp vnRefl t) x)) | otherwise = Just (VApp vnNothing VErased) p_synEq args = Nothing nMaybe = P (TCon 0 2) (sNS (sUN "Maybe") ["Maybe", "Prelude"]) Erased vnJust = VP (DCon 1 2 False) (sNS (sUN "Just") ["Maybe", "Prelude"]) VErased vnNothing = VP (DCon 0 1 False) (sNS (sUN "Nothing") ["Maybe", "Prelude"]) VErased vnRefl = VP (DCon 0 2 False) eqCon VErased synEqTy = Bind (sUN "a") (Pi Nothing (TType (UVar (-3))) (TType (UVar (-2)))) (Bind (sUN "b") (Pi Nothing (TType (UVar (-3))) (TType (UVar (-2)))) (Bind (sUN "x") (Pi Nothing (V 1) (TType (UVar (-2)))) (Bind (sUN "y") (Pi Nothing (V 1) (TType (UVar (-2)))) (mkApp nMaybe [mkApp (P (TCon 0 4) eqTy Erased) [V 3, V 2, V 1, V 0]])))) elabSynEq = do let synEq = sUN "prim__syntactic_eq" updateContext (addOperator synEq synEqTy 4 p_synEq) setTotality synEq (Total []) i <- getIState putIState i { idris_scprims = (synEq, (4, LNoOp)) : idris_scprims i } elabDecls :: ElabInfo -> [PDecl] -> Idris () elabDecls info ds = do mapM_ (elabDecl EAll info) ds elabDecl :: ElabWhat -> ElabInfo -> PDecl -> Idris () elabDecl what info d = let info' = info { rec_elabDecl = elabDecl' } in idrisCatch (withErrorReflection $ elabDecl' what info' d) (setAndReport) elabDecl' _ info (PFix _ _ _) = return () -- nothing to elaborate elabDecl' _ info (PSyntax _ p) = return () -- nothing to elaborate elabDecl' what info (PTy doc argdocs s f o n nfc ty) | what /= EDefns = do iLOG $ "Elaborating type decl " ++ show n ++ show o elabType info s doc argdocs f o n nfc ty return () elabDecl' what info (PPostulate b doc s f o n ty) | what /= EDefns = do iLOG $ "Elaborating postulate " ++ show n ++ show o if b then elabExtern info s doc f o n ty else elabPostulate info s doc f o n ty elabDecl' what info (PData doc argDocs s f co d) | what /= ETypes = do iLOG $ "Elaborating " ++ show (d_name d) elabData info s doc argDocs f co d | otherwise = do iLOG $ "Elaborating [type of] " ++ show (d_name d) elabData info s doc argDocs f co (PLaterdecl (d_name d) (d_name_fc d) (d_tcon d)) elabDecl' what info d@(PClauses f o n ps) | what /= ETypes = do iLOG $ "Elaborating clause " ++ show n i <- getIState -- get the type options too let o' = case lookupCtxt n (idris_flags i) of [fs] -> fs [] -> [] elabClauses info f (o ++ o') n ps elabDecl' what info (PMutual f ps) = do case ps of [p] -> elabDecl what info p _ -> do mapM_ (elabDecl ETypes info) ps mapM_ (elabDecl EDefns info) ps -- record mutually defined data definitions let datans = concatMap declared (filter isDataDecl ps) mapM_ (setMutData datans) datans iLOG $ "Rechecking for positivity " ++ show datans mapM_ (\x -> do setTotality x Unchecked) datans -- Do totality checking after entire mutual block i <- get mapM_ (\n -> do logLvl 5 $ "Simplifying " ++ show n updateContext (simplifyCasedef n $ getErasureInfo i)) (map snd (idris_totcheck i)) mapM_ buildSCG (idris_totcheck i) mapM_ checkDeclTotality (idris_totcheck i) clear_totcheck where isDataDecl (PData _ _ _ _ _ _) = True isDataDecl _ = False setMutData ns n = do i <- getIState case lookupCtxt n (idris_datatypes i) of [x] -> do let x' = x { mutual_types = ns } putIState $ i { idris_datatypes = addDef n x' (idris_datatypes i) } _ -> return () elabDecl' what info (PParams f ns ps) = do i <- getIState iLOG $ "Expanding params block with " ++ show ns ++ " decls " ++ show (concatMap tldeclared ps) let nblock = pblock i mapM_ (elabDecl' what info) nblock where pinfo = let ds = concatMap tldeclared ps newps = params info ++ ns dsParams = map (\n -> (n, map fst newps)) ds newb = addAlist dsParams (inblock info) in info { params = newps, inblock = newb } pblock i = map (expandParamsD False i id ns (concatMap tldeclared ps)) ps elabDecl' what info (PNamespace n nfc ps) = do mapM_ (elabDecl' what ninfo) ps let ns = reverse (map T.pack newNS) sendHighlighting [(nfc, AnnNamespace ns Nothing)] where newNS = maybe [n] (n:) (namespace info) ninfo = info { namespace = Just newNS } elabDecl' what info (PClass doc s f cs n nfc ps pdocs fds ds cn cd) | what /= EDefns = do iLOG $ "Elaborating class " ++ show n elabClass info (s { syn_params = [] }) doc f cs n nfc ps pdocs fds ds cn cd elabDecl' what info (PInstance doc argDocs s f cs n nfc ps t expn ds) = do iLOG $ "Elaborating instance " ++ show n elabInstance info s doc argDocs what f cs n nfc ps t expn ds elabDecl' what info (PRecord doc rsyn fc opts name nfc ps pdocs fs cname cdoc csyn) | what /= ETypes = do iLOG $ "Elaborating record " ++ show name elabRecord info doc rsyn fc opts name nfc ps pdocs fs cname cdoc csyn {- | otherwise = do iLOG $ "Elaborating [type of] " ++ show tyn elabData info s doc [] f [] (PLaterdecl tyn ty) -} elabDecl' _ info (PDSL n dsl) = do i <- getIState putIState (i { idris_dsls = addDef n dsl (idris_dsls i) }) addIBC (IBCDSL n) elabDecl' what info (PDirective i) | what /= EDefns = directiveAction i elabDecl' what info (PProvider doc syn fc provWhat n) | what /= EDefns = do iLOG $ "Elaborating type provider " ++ show n elabProvider doc info syn fc provWhat n elabDecl' what info (PTransform fc safety old new) = do elabTransform info fc safety old new return () elabDecl' _ _ _ = return () -- skipped this time
BartAdv/Idris-dev
src/Idris/ElabDecls.hs
bsd-3-clause
10,439
0
21
3,394
3,613
1,826
1,787
222
6