code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE BangPatterns #-} -- -- The Computer Language Benchmarks Game -- http://benchmarksgame.alioth.debian.org/ -- -- Contributed by Don Stewart -- Parallelized by Louis Wasserman import System.Environment import Control.Monad import System.Mem import Data.Bits import Text.Printf import GHC.Conc -- -- an artificially strict tree. -- -- normally you would ensure the branches are lazy, but this benchmark -- requires strict allocation. -- data Tree = Nil | Node !Int !Tree !Tree minN = 4 io s n t = printf "%s of depth %d\t check: %d\n" s n t main = do n <- getArgs >>= readIO . head let maxN = max (minN + 2) n stretchN = maxN + 1 -- stretch memory tree let c = {-# SCC "stretch" #-} check (make 0 stretchN) io "stretch tree" stretchN c -- allocate a long lived tree let !long = make 0 maxN -- allocate, walk, and deallocate many bottom-up binary trees let vs = depth minN maxN mapM_ (\((m,d,i)) -> io (show m ++ "\t trees") d i) vs -- confirm the the long-lived binary tree still exists io "long lived tree" maxN (check long) -- generate many trees depth :: Int -> Int -> [(Int,Int,Int)] depth d m | d <= m = let s = sumT d n 0 rest = depth (d+2) m in s `par` ((2*n,d,s) : rest) | otherwise = [] where n = bit (m - d + minN) -- allocate and check lots of trees sumT :: Int -> Int -> Int -> Int sumT d 0 t = t sumT d i t = a `par` b `par` sumT d (i-1) ans where a = check (make i d) b = check (make (-i) d) ans = a + b + t check = check' True 0 -- traverse the tree, counting up the nodes check' :: Bool -> Int -> Tree -> Int check' !b !z Nil = z check' b z (Node i l r) = check' (not b) (check' b (if b then z+i else z-i) l) r -- build a tree make :: Int -> Int -> Tree make i 0 = Node i Nil Nil make i d = Node i (make (i2-1) d2) (make i2 d2) where i2 = 2*i; d2 = d-1
beni55/ghcjs
test/nofib/shootout/binary-trees/Main.hs
mit
1,919
6
13
518
730
381
349
48
2
-- Test purpose: -- -- Ensure the plural "s" in warnings is only shown if there are more than -- one entries {-# OPTIONS_GHC -Wredundant-constraints #-} {-# OPTIONS_GHC -Wtype-defaults #-} module PluralS () where -- Defaulting type classes defaultingNum = 123 `seq` () defaultingNumAndShow = show 123 -- Redundant constraints redundantNum :: (Num a, Num a) => a redundantNum = 123 redundantMultiple :: (Num a, Show a, Num a, Eq a, Eq a) => a redundantMultiple = 123
ezyang/ghc
testsuite/tests/warnings/should_compile/PluralS.hs
bsd-3-clause
478
0
6
90
104
62
42
9
1
-- Test for #1617 module T1617 where import Prelude () import Control.Monad (mplus) import qualified Control.Monad (mplus)
urbanslug/ghc
testsuite/tests/ghci/scripts/ghci027_1.hs
bsd-3-clause
123
0
5
17
32
21
11
4
0
-- !!! tests calls of `error' (that make calls of `error'...) -- main = error ("1st call to error\n"++( error ("2nd call to error\n"++( error ("3rd call to error\n"++( error ("4th call to error\n"++( error ("5th call to error\n"++( error ("6th call to error" )))))))))))
sdiehl/ghc
testsuite/tests/codeGen/should_run/cgrun016.hs
bsd-3-clause
313
0
26
87
79
43
36
6
1
-- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. {-| Copyright : (c) Microsoft License : MIT Maintainer : [email protected] Stability : alpha Portability : portable The module exports the built-in code generation templates. -} module Language.Bond.Codegen.Templates ( -- * Templates -- | All codegen templates take at least the following arguments: -- -- * 'MappingContext' which determines mapping of Bond types to types in -- the target language -- -- * base file name, typically the name of the schema definition file -- without the extension -- -- * list of 'Import's from the parsed schema definition -- -- * list of 'Declaration's from the parsed schema definition -- -- Some templates are parameterized with additional options for -- customizing the generated code. -- -- The templates return the name suffix for the target file and lazy -- 'Text' with the generated code. -- ** Protocol data type Protocol(..) -- ** C++ , types_h , types_cpp , reflection_h , enum_h , apply_h , apply_cpp -- ** C# , FieldMapping(..) , StructMapping(..) , types_cs ) where import Language.Bond.Codegen.Cpp.Apply_cpp import Language.Bond.Codegen.Cpp.Apply_h import Language.Bond.Codegen.Cpp.ApplyOverloads import Language.Bond.Codegen.Cpp.Enum_h import Language.Bond.Codegen.Cpp.Reflection_h import Language.Bond.Codegen.Cpp.Types_cpp import Language.Bond.Codegen.Cpp.Types_h import Language.Bond.Codegen.Cs.Types_cs
upsoft/bond
compiler/src/Language/Bond/Codegen/Templates.hs
mit
1,705
0
5
400
140
108
32
20
0
module Hircules.Directories ( -- dirname, basename, makeDirectory) where import Control.Monad (unless) import System.Directory (createDirectory, doesDirectoryExist) --import System.FilePath -- dirname :: FilePath -> FilePath -- dirname = joinSegments . init . pathSegments -- basename :: FilePath -> FilePath -- basename = last . pathSegments -- pathSegments :: FilePath -> [String] -- pathSegments fs | last fs == '/' = pathSegments $ init fs -- pathSegments fs = -- let (l, s') = break (== '/') fs in -- (l) : case s' of -- [] -> [] -- (_:s'') -> pathSegments s'' -- joinSegments :: [String] -> FilePath -- joinSegments = concatMap (++ "/") makeDirectory :: FilePath -> IO () makeDirectory dir = do exists <- doesDirectoryExist dir unless exists $ putStrLn ("creating " ++ dir) >> createDirectory dir
juhp/hircules
src/Hircules/Directories.hs
mit
909
0
11
234
108
63
45
9
1
module Data.PackedSet where import qualified Data.Set as ST import qualified Data.Map as MP data PackedSet a = PackedSet -- Total number of elements, including interval elements. { psSize :: Int -- Primary interval ends. , psPrimaryIv :: (a,a) -- Lower end of all the secondary intervals; for speedy lookups. , psSecondaryIvsLE :: ST.Set a -- Secondary intervals; we assume at some point the main interval -- will swallow up all these secondary intervals. , psSecondaryIvs :: MP.Map a (a,a) -- Outliers are not part of either the main interval or the secondary -- intervals, so we keep these elements in a separate set. Eventually, -- these will merge in one of the intervals. , psOutliers :: ST.Set a } deriving (Show) -- | How often should we pack-up a set packingThrottle :: Int packingThrottle = 100 -- Main differences between Data.PackedSet and Data.Set: -- -- Type constraints on set members: Ord, Num. -- Lack of a 'delete' operation. {-------------------------------------------------------------------- Construction --------------------------------------------------------------------} -- | /O(1)/. The empty packet set. empty :: PackedSet Int empty = PackedSet { psSize = 0 , psPrimaryIv = (0,0) , psSecondaryIvsLE = ST.empty , psSecondaryIvs = MP.empty , psOutliers = ST.empty } -- | /O(1)/. Create a singleton packet set. singleton :: (Ord a, Num a) => a -> PackedSet a singleton x = PackedSet { psSize = 1 , psPrimaryIv = (x,x) , psSecondaryIvsLE = ST.empty , psSecondaryIvs = MP.empty , psOutliers = ST.empty } {-------------------------------------------------------------------- Query --------------------------------------------------------------------} -- | /O(1)/. Is this packed set empty? null :: PackedSet a -> Bool null PackedSet { psSize = s } = s == 0 -- | /O(1)/. Returns the number of elements in the packed set. size :: PackedSet a -> Int size PackedSet {psSize = s} = s -- | /O(log n)/. Lookup a member in the packed set. -- TODO! member :: (Ord a, Num a) => a -> PackedSet a -> Bool member m p = if (psSize p == 0) then False else if (_belongsTo m mi) || (ST.member m ol) then True else _intervalsLookup m p where ol = psOutliers p mi = psPrimaryIv p -- | /O(log n)/. Is the element not in the packed set? notMember :: (Ord a, Num a) => a -> PackedSet a -> Bool notMember m p = not $ member m p {-------------------------------------------------------------------- Insertion --------------------------------------------------------------------} -- | /O(log n)/. Insert an element in a packed set if it's not a member already. insert :: (Ord a, Num a) => a -> PackedSet a -> PackedSet a insert m p = if (psSize p) == 0 -- If the set is empty, create a singleton. then singleton m else if (_belongsTo m $ psPrimaryIv p) -- If the element is already in the main interval, nothing to do. then p -- Check if this element can expand the main interval. else if expandedMainIv == True -- Pack-up the set before returning it then postMainExpandPack p newSize newMainIv else p -- if (expandedSecondaryIv == True) -- then -- else where (psll, psul) = psPrimaryIv p (expandedMainIv, newMainIv) = _maybeExpand m $ psPrimaryIv p newSize = (psSize p) + 1 -- (expandedSecondaryIv) = _maybeExpandSecondaryIv -- packs the set after the main interval was expanded postMainExpandPack p size mainIv = p { psSize = size, psPrimaryIv = mainIv} {-------------------------------------------------------------------- Private functions --------------------------------------------------------------------} -- Looks-up an element in all the outlying intervals of a packed set. _intervalsLookup :: (Ord a, Num a) => a -> PackedSet a -> Bool _intervalsLookup m p = maybe False (\se -> maybe False validateInterval $ mInterval se) mIntervalSE where -- find the interval lower end, if any mIntervalSE = ST.lookupLE m (psSecondaryIvsLE p) mInterval k = MP.lookup k (psSecondaryIvs p) validateInterval (_, iGE) = iGE > m -- Returns true if an element is inside an interval. _belongsTo :: (Ord a, Num a) => a -> (a,a) -> Bool _belongsTo m (lowerLim, upperLim) = m >= lowerLim && m <= upperLim -- Tries to expand a given interval with an element, either to the left or to -- the right, wherever is possible. _maybeExpand :: (Ord a, Num a) => a -> (a,a) -> (Bool, (a,a)) _maybeExpand m (lowerLim, upperLim) = if (m == lowerLim - 1) then (True, (m,upperLim)) else if (m == upperLim + 1) then (True, (lowerLim, m)) else (False, (lowerLim, upperLim))
adizere/nifty-sets
src/Data/PackedSet.hs
mit
5,293
0
10
1,573
1,017
579
438
75
4
module JSError ( JSError (..) , ThrowsError , IOThrowsError , liftThrows , throwError , liftIO , runExceptT ) where import Control.Monad.Except import JSEntity (JSExpression, JSStatement, JSVal) import Text.Megaparsec.Error (ParseError) data JSError = NumArgs Integer [JSVal] | TypeMismatch String JSVal | ParserError ParseError | BadSpecialForm String JSExpression | NotFunction JSVal | UnboundVar String String | NameConflict String | InvalidStatement (Maybe JSStatement) | Default String unwordsList :: Show s => [s] -> String unwordsList = unwords . fmap show instance Show JSError where show err = case err of NumArgs expected actualVals -> "Expected " `mappend` show expected `mappend` " args: found values " `mappend` unwordsList [actualVals] TypeMismatch expected actualVal -> "Invalid type: expected " `mappend` expected `mappend` ", found " `mappend` show actualVal ParserError e -> "Parse error at " `mappend` show e BadSpecialForm msg expr -> msg `mappend` ": " `mappend` show expr NotFunction func -> "Try to call a non-function value: " `mappend` show func UnboundVar msg varName -> msg `mappend` ": " `mappend` varName NameConflict varName -> "Name conflict: " `mappend` varName `mappend` " has already been defined" InvalidStatement maybeStmt -> "Invalid statement: " `mappend` case maybeStmt of Nothing -> "unknown" Just stmt -> show stmt Default s -> s type ThrowsError = Either JSError type IOThrowsError = ExceptT JSError IO liftThrows :: ThrowsError a -> IOThrowsError a liftThrows (Left err) = throwError err liftThrows (Right val) = return val
li-zhirui/JSAnalyzer
JSError.hs
mit
1,950
0
13
615
470
257
213
56
1
module Simulation.Node ( Node (endpoints, counter) , Hostname , Port , Simulation.Node.create , createEndpoint , removeEndpoint , activateHttpServices , as ) where import Control.Applicative ((<$>), (<*>)) import Control.Concurrent.Async (Async, async) import Control.Concurrent.STM ( STM , TVar , TMVar , atomically , modifyTVar' , newTVarIO , newEmptyTMVarIO , readTVar , writeTVar , putTMVar ) import Control.Monad (when) import Data.List (delete) import Simulation.Node.SystemCounter import qualified Simulation.Node.SystemCounter as SC import Simulation.Node.Endpoint hiding (counter) import Simulation.Node.Endpoint.AppCounter (AppCounter) import qualified Simulation.Node.Endpoint as Endpoint import Simulation.Node.Endpoint.Behavior (Hostname, Port) import Simulation.Node.Service.Http (Service, as, activate) -- | A node instance descriptor. data Node c = Node { webGateway :: !Hostname , webPort :: !Port , endpoints :: TVar [Endpoint c] , counter :: TVar SystemCounter , httpServices :: TMVar (Async ())} deriving Eq -- | Create a node instance. create :: AppCounter c => Hostname -> Port -> IO (Node c) create gateway port = Node gateway port <$> newTVarIO [] <*> newTVarIO SC.create <*> newEmptyTMVarIO -- | Create an endpoint instance. createEndpoint :: AppCounter c => IpAddress -> Node c -> IO (Endpoint c) createEndpoint ip node = do endpoint <- Endpoint.create ip (webGateway node) (webPort node) (counter node) atomically $ modifyTVar' (endpoints node) (endpoint:) return endpoint -- | Remove an endpoint from the node. removeEndpoint :: (Eq c, AppCounter c) => Endpoint c -> Node c -> IO () removeEndpoint endpoint node = do isDeleted <- atomically $ maybeDelete endpoint (endpoints node) when isDeleted $ reset endpoint maybeDelete :: (Eq c, AppCounter c) => Endpoint c -> TVar [Endpoint c] -> STM Bool maybeDelete endpoint endpoints' = do xs <- readTVar endpoints' if endpoint `elem` xs then do writeTVar endpoints' (endpoint `delete` xs) return True else return False -- | Activate http services in a separate thread. activateHttpServices :: Node c -> Int -> [Service ()] -> IO () activateHttpServices node port services = do thread <- async $ activate port services atomically $ putTMVar (httpServices node) thread
kosmoskatten/programmable-endpoint
src/Simulation/Node.hs
mit
2,503
0
12
586
725
394
331
69
2
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UndecidableInstances #-} module Betfair.APING.Types.TimeRange ( TimeRange(..) ) where import Data.Aeson.TH (Options (omitNothingFields), defaultOptions, deriveJSON) import Protolude import Text.PrettyPrint.GenericPretty type DateString = Text data TimeRange = TimeRange { from :: Maybe DateString , to :: Maybe DateString } deriving (Eq, Show, Generic, Pretty) -- instance Default TimeRange where def = TimeRange "" "" $(deriveJSON defaultOptions {omitNothingFields = True} ''TimeRange)
joe9/betfair-api
src/Betfair/APING/Types/TimeRange.hs
mit
801
0
9
185
129
80
49
19
0
module Main where import Solidran.Lexf.Detail main :: IO () main = do alphabet <- (getLine >>= (return . filter (/= ' '))) n <- (getLine >>= (return . read)) mapM_ (putStrLn) $ getAlphabetStrings n alphabet
Jefffrey/Solidran
src/Solidran/Lexf/Main.hs
mit
234
0
13
62
92
49
43
7
1
module HttpStuff where import Data.ByteString.Lazy hiding (map) import Network.Wreq urls :: [String] urls = [ "http://httpbin.com/ip" , "http://httpbin.com/bytes/g" ] mappingGet :: [IO (Response ByteString)] mappingGet = map get urls -- better than the above traversedUrls :: IO [Response ByteString] traversedUrls = traverse get urls
NickAger/LearningHaskell
HaskellProgrammingFromFirstPrinciples/Chapter21.hsproj/HttpStuff.hs
mit
365
0
8
74
92
53
39
10
1
{-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Main where import Control.Applicative ((<$>), (<*>)) import Control.Monad import Control.Monad.Reader import DBus.Signature import Data.Binary.Get import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Lazy.Builder as BS import Data.Char import Data.Either import Data.Int import Data.List (intercalate) import Data.Singletons import Data.Singletons.Prelude.List import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Word import DBus.Types import DBus.Wire -- import DBus.Introspect import Test.QuickCheck import Test.QuickCheck.Arbitrary import Test.QuickCheck.Gen import Test.Tasty import Test.Tasty.QuickCheck import Test.Tasty.TH import Numeric import Debug.Trace instance Arbitrary DBusSimpleType where arbitrary = oneof [ return TypeByte , return TypeBoolean , return TypeInt16 , return TypeUInt16 , return TypeInt32 , return TypeUInt32 , return TypeInt64 , return TypeUInt64 , return TypeDouble , return TypeUnixFD , return TypeString , return TypeObjectPath , return TypeSignature ] shrink _ = [TypeByte] resized :: Gen a -> Gen a resized g = sized (\i -> resize (i `div` 2) g) maxsized :: Int -> Gen a -> Gen a maxsized s g = sized (\i -> resize (min s i) g) instance Arbitrary DBusType where arbitrary = oneof [ DBusSimpleType <$> resized arbitrary , TypeArray <$> resized arbitrary , TypeStruct <$> resized (listOf1 arbitrary) , TypeDict <$> resized arbitrary <*> resized arbitrary , return TypeVariant ] shrink (TypeStruct ts) = TypeStruct <$> (filter (not.null) $ shrink ts) shrink (TypeDict kt vt) = (TypeDict kt <$> (shrink vt)) ++ (TypeDict <$> (shrink kt) <*> [vt]) shrink (TypeDictEntry kt vt) = (TypeDictEntry kt <$> (shrink vt)) ++ (TypeDictEntry <$> (shrink kt) <*> [vt]) shrink (TypeArray t) = TypeArray <$> shrink t shrink t = [] prop_signatureInverse = \s -> eitherParseSig (toSignature s) == Right s nodeXml = Text.encodeUtf8 $ Text.concat [ "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection \ \1.0//EN\"" , " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">" , " <node name=\"/com/example/sample_object\">" , " <interface name=\"com.example.SampleInterface\">" , " <method name=\"Frobate\">" , " <arg name=\"foo\" type=\"i\" direction=\"in\"/>" , " <arg name=\"bar\" type=\"s\" direction=\"out\"/>" , " <arg name=\"baz\" type=\"a{us}\" direction=\"out\"/>" , " <annotation name=\"org.freedesktop.DBus.Deprecated\" value=\"true\"/>" , " </method>" , " <method name=\"Bazify\">" , " <arg name=\"bar\" type=\"(iiu)\" direction=\"in\"/>" , " <arg name=\"bar\" type=\"v\" direction=\"out\"/>" , " </method>" , " <method name=\"Mogrify\">" , " <arg name=\"bar\" type=\"(iiav)\" direction=\"in\"/>" , " </method>" , " <signal name=\"Changed\">" , " <arg name=\"new_value\" type=\"b\"/>" , " </signal>" , " <property name=\"Bar\" type=\"y\" access=\"readwrite\"/>" , " </interface>" , " <node name=\"child_of_sample_object\"/>" , " <node name=\"another_child_of_sample_object\"/>" , "</node>" ] isRight :: Either a b -> Bool isRight (Right _) = True isRight (Left _) = False -- testing_pickler1 = isRight $ xmlToNode nodeXml -- testing_pickler2 = let Right node = xmlToNode nodeXml -- reXml = nodeToXml node -- Right reNode = xmlToNode reXml -- in node == reNode genText = Text.pack <$> arbitrary genOP = objectPath . Text.pack <$> arbitrary shrinkTypes [x] = (:[]) <$> shrinkType x shrinkTypes xs = if BS.length (toSignatures xs) > 255 then shrinkTypes (tail xs) else return xs genDBV :: Sing t -> Gen (DBusValue t) genDBV (SDBusSimpleType STypeByte) = DBVByte <$> arbitrary genDBV (SDBusSimpleType STypeBoolean) = DBVBool <$> arbitrary genDBV (SDBusSimpleType STypeInt16) = DBVInt16 <$> arbitrary genDBV (SDBusSimpleType STypeUInt16) = DBVUInt16 <$> arbitrary genDBV (SDBusSimpleType STypeInt32) = DBVInt32 <$> arbitrary genDBV (SDBusSimpleType STypeUInt32) = DBVUInt32 <$> arbitrary genDBV (SDBusSimpleType STypeInt64) = DBVInt64 <$> arbitrary genDBV (SDBusSimpleType STypeUInt64) = DBVUInt64 <$> arbitrary genDBV (SDBusSimpleType STypeDouble) = DBVDouble <$> arbitrary genDBV (SDBusSimpleType STypeUnixFD) = DBVUnixFD <$> arbitrary genDBV (SDBusSimpleType STypeString) = DBVString <$> genText genDBV (SDBusSimpleType STypeObjectPath) = DBVObjectPath <$> genOP genDBV (SDBusSimpleType STypeSignature) = maxsized 10 $ DBVSignature <$> (shrinkTypes =<< arbitrary) genDBV STypeVariant = resized $ do t <- maxsized 10 $ shrinkType =<< arbitrary :: Gen DBusType case toSing t of SomeSing (st :: Sing t) -> withSingI st $ DBVVariant <$> genDBV st genDBV (STypeArray t) = resized $ DBVArray <$> listOf (genDBV t) genDBV (STypeStruct ts) = resized $ DBVStruct <$> genStruct ts genDBV (STypeDict kt vt) = resized $ DBVDict <$> listOf ((,) <$> genDBV (SDBusSimpleType kt) <*> genDBV vt) genStruct :: Sing ts -> Gen (DBusStruct ts) genStruct (SCons t SNil) = StructSingleton <$> genDBV t genStruct (SCons t ts) = StructCons <$> genDBV t <*> genStruct ts for = flip map shrinkType t = if BS.length (toSignature t) > 255 then shrinkType =<< elements (shrink t) else return t instance Arbitrary SomeDBusValue where arbitrary = do t <- shrinkType =<< arbitrary :: Gen DBusType case toSing t of SomeSing st -> withSingI st $ DBV <$> genDBV st shrink (DBV x) = case x of DBVVariant y -> (DBV y) : ((\(DBV x) -> DBV (DBVVariant x)) <$> shrink (DBV y)) (DBVArray (a:as) :: DBusValue t) -> case (sing :: Sing t) of STypeArray ts -> withSingI ts $ ( case shrink (fromSing (sing :: Sing t)) of tss -> for tss $ \tshrink -> case toSing tshrink of (SomeSing (ss :: Sing (tt :: DBusType))) -> withSingI ss $ DBV (DBVArray ([] :: [DBusValue tt])) ) ++ [ DBV ( DBVArray [] :: DBusValue t) , DBV ( DBVArray as :: DBusValue t) , DBV ( DBVArray (init (a:as)) :: DBusValue t) , case (sing :: Sing t) of STypeArray st -> withSingI st $ DBV a ] ++ map (\(DBV b) -> DBV (DBVArray [b])) (shrink (DBV a)) (DBVDict ((k,v):as) :: DBusValue t) -> [ DBV ( DBVDict [] :: DBusValue t) , DBV ( DBVDict as :: DBusValue t) , case (sing :: Sing t) of STypeDict kt vt -> withSingI kt $ DBV k , case (sing :: Sing t) of STypeDict kt vt -> withSingI vt $ DBV v ] (DBVStruct fs :: DBusValue t) -> case (sing :: Sing t) of STypeStruct ts -> shrinkStruct ts fs _ -> [] shrinkStruct :: Sing ts -> DBusStruct ts -> [SomeDBusValue] shrinkStruct (SCons t SNil) (StructSingleton x) = withSingI t [DBV x] shrinkStruct (SCons t ts) (StructCons x xs) = withSingI t $ withSingI ts $ (DBV $ DBVStruct xs) : (DBV x) : (shrinkStruct ts xs) hexifyChar c = case showHex c "" of [x] -> ['0',x] x -> x hexifyBS bs = intercalate " " $ hexifyChar <$> BSL.unpack bs showifyChar c = if ord 'a' <= c && c <= ord 'z' then chr c : " " else " " showifyBS bs = intercalate " " $ showifyChar . fromIntegral <$> BSL.unpack bs -- sho bs = "============\n" ++ show bs ++ "\n -------------- \n" ++ hexifyBS bs sho bs = show bs to :: SingI t => DBusValue t -> BSL.ByteString to x = (BS.toLazyByteString $ runDBusPut Big (putDBV x)) wire_inverse (x :: DBusValue t) = let from = runGet (runReaderT getDBV Big) (to x) in (DBV from, x == from) prop_wire_inverse (DBV x) = snd $ wire_inverse x main = $defaultMainGenerator ppv (x :: DBusValue t) = do print x let bs = to x return $! bs forM_ [1..32] $ \i -> (putStr $ hexifyChar i) >> putStr " " putStrLn "" putStrLn (hexifyBS bs) putStrLn (showifyBS bs) putStrLn (" ## " ++ show (BSL.length bs)) let from = runGet (runReaderT getDBV Big) bs print from print x print $ x == from foo = sample' arbitrary >>= (mapM_ $ \(DBV x) -> ppv x) test1 = DBVVariant (DBVArray [DBVUInt16 2]) test2 = DBVArray [DBVByte 0 , DBVByte 3, DBVByte 0] test3 = DBVVariant (DBVVariant (DBVStruct (StructSingleton (DBVStruct (StructSingleton (DBVUInt16 9)))))) test4 = DBVArray [DBVVariant $ DBVUInt32 7 ] test5 = DBVArray [DBVVariant $ DBVUInt64 7 ] test6 = DBVArray [DBVStruct (StructSingleton (DBVVariant (DBVUInt32 0)))] test7 = DBVArray [DBVStruct (StructSingleton (DBVUInt64 (maxBound :: Word64)))] test8o = DBVVariant (DBVVariant (DBVArray [DBVVariant (DBVVariant (DBVInt16 (-1)))])) test8 = DBVVariant (DBVVariant (DBVArray [DBVVariant (DBVVariant (DBVInt16 (-1)))]))
Philonous/d-bus
tests/Main.hs
mit
10,373
0
30
3,296
3,043
1,552
1,491
214
2
import System.IO import System.Process main = do (_, Just hout, Just herr, jHandle) <- -- Replace with some other command on Windows createProcess (proc "/bin/date" args) { cwd = Just "." , std_out = CreatePipe , std_err = CreatePipe } where args = []
tjakway/blackjack-simulator
main/ErrorFilter.hs
mit
329
0
11
121
85
47
38
-1
-1
module Utils.List ( takeWhileInclusive, listToInt ) where -- Same as take while, but includes the element that we terminate on. -- E.g. takeWhileInclusive (/=3) [1,2,3,4] -> [1,2,3] takeWhileInclusive :: (a -> Bool) -> [a] -> [a] takeWhileInclusive _ [] = [] takeWhileInclusive p (x:xs) = x : if p x then takeWhileInclusive p xs else [] -- Converts a list of integrals to a single integral -- E.g. [1,2,3,4] -> 1234 listToInt :: (Integral a) => [a] -> a listToInt i = foldl ((+).(*10)) 0 i
daniel-beard/projecteulerhaskell
Problems/Utils/list.hs
mit
581
1
8
177
146
83
63
9
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} -- | Common handler functions. module Handler.Common where import Data.FileEmbed (embedFile) import Data.List (nub) import Data.Range import Data.SemVer (Version, fromText, toText) import Data.Time.Clock import Database.Esqueleto import Import.App hiding (Value, on) import Web.Cookie -- These handlers embed files in the executable at compile time to avoid a -- runtime dependency, and for efficiency. getFaviconR :: Handler TypedContent getFaviconR = do cacheSeconds $ 60 * 60 * 24 -- cache for a day return $ TypedContent "image/x-icon" $ toContent $(embedFile "config/favicon.ico") handle404 :: MonadHandler m => m [a] -> m a handle404 = (=<<) $ \b -> case b of initial:_ -> pure initial [] -> notFound toParams :: Maybe Version -> [(Text, Text)] toParams Nothing = [("ev", "all")] toParams (Just v) = [("ev", toText v)] cookieLife :: DiffTime cookieLife = 60 * 60 * 24 * 365 setElmVersionCookie :: MonadHandler m => Text -> m () setElmVersionCookie ev = setCookie $ def { setCookieName = "ev" , setCookieValue = encodeUtf8 ev , setCookiePath = Just "/" , setCookieMaxAge = Just cookieLife } {- | Looks up the "ev" param in the URL. If it is set, we also set a cookie. We only use the cookie if you don't supply the param. So, basically, we use the cookie to redirect if you don't supply the param. -} lookupRequestedElmVersion :: Handler (Maybe Version) lookupRequestedElmVersion = do evParam <- lookupGetParam "ev" currentRoute <- fromMaybe HomeR <$> getCurrentRoute if evParam == Just "all" then do setElmVersionCookie "all" pure Nothing else case fromText <$> evParam of Just (Left err) -> invalidArgs ["The 'ev' param could not be interpreted.", pack err] Just (Right v) -> do setElmVersionCookie (toText v) pure (Just v) Nothing -> do evCookie <- fmap fromText <$> lookupCookie "ev" case evCookie of Just (Right v) -> redirect (currentRoute, [("ev", toText v)]) _ -> pure () pure Nothing elmVersionWidget :: Widget elmVersionWidget = do requestedElmVersion <- handlerToWidget lookupRequestedElmVersion currentRoute <- fromMaybe HomeR <$> getCurrentRoute renderUrl <- getUrlRenderParams standardVersions <- handlerToWidget $ runDB $ select $ from (\v -> pure $ v ^. ElmVersionVersion) let versions = nub $ sort $ Value requestedElmVersion : standardVersions wrapper <- newIdent labelButton <- newIdent let buttonColorForVersion v = if v == requestedElmVersion then "btn-primary" :: Text else "btn-default" let hrefForVersion v = if v == requestedElmVersion then "" else renderUrl currentRoute $ toParams v [whamlet| <div class="btn-group" role="group" aria-label="Choose Elm Version" .#{wrapper}> <button type="button" .btn.btn-xs.btn-success .#{labelButton}> Elm Version $forall Value v <- versions <button type="button" data-href="#{hrefForVersion v}" .btn.btn-xs .#{buttonColorForVersion v}> $case v $of Just vers #{toText vers} $of Nothing All |] toWidget [julius| (function (wrapper) { $("." + wrapper + " button[data-href]").click(function () { var href = $(this).attr('data-href'); if (href) window.location = href; }); })(#{toJSON wrapper}); |] toWidget [cassius| .#{wrapper} button min-width: 3.5em .#{labelButton} pointer-events: none |] maxRepoVersion :: Maybe Version -> SqlExpr (Entity Repo) -> SqlExpr (Value (Maybe Version)) maxRepoVersion elmVersion r = case elmVersion of Nothing -> sub_select $ from $ \rv2 -> do where_ $ rv2 ^. RepoVersionRepo ==. r ^. RepoId pure $ max_ $ rv2 ^. RepoVersionVersion Just _ -> sub_select $ from $ \(rv2 `InnerJoin` p2) -> do on $ p2 ^. PackageRepoVersion ==. rv2 ^. RepoVersionId where_ $ (rv2 ^. RepoVersionRepo ==. r ^. RepoId) &&. justValueInRange elmVersion (p2 ^. PackageElmVersion) pure $ max_ $ rv2 ^. RepoVersionVersion
rgrempel/frelm.org
src/Handler/Common.hs
mit
5,102
0
20
1,750
1,006
514
492
104
5
module Geometry.Polygon where import Algebra.Matrix as M import Algebra.Vector as V import Control.Exception.Base import qualified Data.Graph.Extensions as Graph import Data.List as List import Data.List.Extensions as ListExt import Data.Map as Map import Data.Maybe as Maybe import Data.Ratio as Ratio import Data.Set as Set import Data.Set.Extensions as SetExt import Data.Tuple.Extensions as TupleExt import Geometry.AABB as AABB import Geometry.LineSegment as LS import Geometry.Matrix2d as M2d import Geometry.Vector2d as V2d import Prelude.Extensions as PreludeExt type Polygon = [V.Vector] fromPoints = id points = id pointsToEdges = \points -> (ListExt.map2 LS.fromEndpoints points (rotateLeft points)) edges = ((.) pointsToEdges points) directedGraph = \polygon -> (Map.fromList (List.map (\e -> (endpoint0 e, [endpoint1 e])) (edges polygon))) translate = \polygon translation -> (List.map (V.add translation) polygon) rotate = \polygon angle -> (List.map (M.transform (M2d.rotation angle)) polygon) transform = \polygon center angle translation -> let centered = (Geometry.Polygon.translate polygon (V.negate center)) rotated = (Geometry.Polygon.rotate centered angle) translated = (Geometry.Polygon.translate rotated (V.add center translation)) in translated pointIntersection = \polygon point -> let walkBoundary = \(winding_number, on_boundary) edge -> let toQuadrant = ((.) V2d.quadrant (flip V.subtract point)) [start, stop] = (List.map toQuadrant [endpoint0 edge, endpoint1 edge]) quadrant = ((-) stop start) turn = (V2d.crossProduct (LS.direction edge) (V.subtract point (LS.endpoint0 edge))) turn_cases = [((>) turn 0, ((ifElse ((<) quadrant 0) ((+) quadrant 4) quadrant), False)), ((<) turn 0, ((ifElse ((>) quadrant 0) ((-) quadrant 4) quadrant), False))] (winding_change, boundary_change) = (cases turn_cases (0, LS.pointIntersection edge point)) in ((+) winding_number winding_change, (||) on_boundary boundary_change) (winding_number, on_boundary) = (List.foldl walkBoundary (0, False) (edges polygon)) in ((||) ((==) winding_number 4) on_boundary) intersectionSubdivision :: Polygon -> (Map Int [Vector]) -> Polygon intersectionSubdivision = \polygon intersection_lookup -> let edgeSubdivision = \(id, edge) -> let intersections = ((!) intersection_lookup id) scalar_points = (Map.fromList (List.map (\x -> (LS.projectionScalar edge x, x)) intersections)) in (Map.elems (Map.delete 1 (Map.insert 0 (endpoint0 edge) scalar_points))) in (fromPoints (concat (List.map edgeSubdivision (zipIndices0 (edges polygon))))) intersectionGraph :: Polygon -> Polygon -> (Graph.Graph Vector, Set Vector) intersectionGraph = \polygon0 polygon1 -> let edge_pairs = (ListExt.crossProduct (zipIndices0 (edges polygon0)) (zipIndices0 (edges polygon1))) intersections = (List.map (\((id0, f0), (id1, f1)) -> (id0, id1, LS.intersection f0 f1)) edge_pairs) (take02, take12) = (\(a,b,c) -> (a,c), \(a,b,c) -> (b,c)) subdivision0 = (intersectionSubdivision polygon0 (Map.fromListWith (++) (List.map take02 intersections))) subdivision1 = (intersectionSubdivision polygon1 (Map.fromListWith (++) (List.map take12 intersections))) intersection_set = (Set.fromList (concat (List.map third3 intersections))) inside0 = (List.filter (Geometry.Polygon.pointIntersection polygon1) (points polygon0)) inside1 = (List.filter (Geometry.Polygon.pointIntersection polygon0) (points polygon1)) inside_set = (Set.fromList (concat [inside0, inside1, concat (List.map third3 intersections)])) in (Graph.union (directedGraph subdivision0) (directedGraph subdivision1), inside_set) filterIntersectionGraph = \graph inside_set polygon0 polygon1 -> let inside_neighbors = (Map.map (List.filter (flip Set.member inside_set)) graph) inside_vertices = (Map.intersection inside_neighbors (SetExt.toMap (const []) inside_set)) insideGraph = \(a,b) -> let midpoint = (LS.midpoint (LS.fromEndpoints a b)) pointIntersection = (flip Geometry.Polygon.pointIntersection midpoint) in ((&&) (pointIntersection polygon0) (pointIntersection polygon1)) in (Graph.fromEdges (List.filter insideGraph (Graph.edges inside_vertices))) extractPolygonCycle :: (Graph.Graph Vector) -> [Vector] -> [Vector] -> (Bool, [Vector]) extractPolygonCycle = \graph start path -> let (current, previous, neighbors) = (head path, head (tail path), (!) graph current) outwardsAngle = \x -> (V2d.positiveAngle (V.subtract previous current) (V.subtract x current)) (angle, next) = (List.minimum (List.map (\x -> (outwardsAngle x, x)) neighbors)) recurse = (extractPolygonCycle graph start ((:) next path)) (prefix, suffix) = (List.splitAt 2 path) is_complete = ((&&) ((==) prefix start) (ListExt.notNull suffix)) in (ifElse is_complete (True,List.reverse suffix) (ifElse (List.null neighbors) (False,path) recurse)) extractPolygonCycles :: (Graph.Graph Vector) -> [Polygon] extractPolygonCycles = \graph -> let extractPolygonCycles = \graph -> let (start, neighbors) = (Map.findMax graph) outwardsAngle = \x -> (V2d.positiveAngle (V.fromList [1, 0]) (V.subtract x start)) (angle, next) = (List.minimum (List.map (\x -> (outwardsAngle x, x)) neighbors)) extracted_result = (extractPolygonCycle graph [next, start] [next, start]) (is_cycle, path) = (ifElse (List.null neighbors) (True,[start]) extracted_result) notUsed = (flip Set.notMember (Set.fromList path)) remaining_graph = (Map.filterWithKey (\k a -> notUsed k) (Map.map (List.filter notUsed) graph)) recurse = (extractPolygonCycles remaining_graph) result = (ifElse is_cycle ((:) (fromPoints path) recurse) recurse) in (ifElse (Map.null graph) [] result) in (extractPolygonCycles graph) intersection :: Polygon -> Polygon -> [Polygon] intersection = \polygon0 polygon1 -> let (graph, inside_set) = (intersectionGraph polygon0 polygon1) inside_graph = (filterIntersectionGraph graph inside_set polygon0 polygon1) in (extractPolygonCycles inside_graph) isLeftTurn = \p0 p1 p2 -> ((>) (V2d.crossProduct (V.subtract p1 p0) (V.subtract p2 p0)) 0) convexHull = \points -> let sorted_points = (List.sort (List.map V.toList points)) buildHull = \stack point -> let lessThanTwo = \stack -> ((||) (List.null stack) (List.null (tail stack))) turnsLeft = \stack -> (isLeftTurn ((!!) stack 1) ((!!) stack 0) point) convex_stack = (until (\x -> ((||) (lessThanTwo x) (turnsLeft x))) tail stack) in ((:) point convex_stack) bottom = (List.foldl buildHull [] sorted_points) top = (List.foldr (flip buildHull) [] sorted_points) in ((++) (List.reverse (tail bottom)) (List.reverse (tail top))) edgeNormal = ((.) V.negate ((.) V2d.perpendicular LS.direction)) edgeNormalQuadrantRatio = ((.) V2d.quadrantRatio edgeNormal) -- assumes every edge has a unique normal angle; i.e. no quadrant-ratio keys will duplicated in the normal map gaussianMap = \edges -> let normal_map = (Map.fromList (List.map (\edge -> (edgeNormalQuadrantRatio edge, edge)) edges)) (((q0, r0), min), ((q1, r1), max)) = (Map.findMin normal_map, Map.findMax normal_map) wrapped_min = (Map.insert ((+) q0 4, r0) min normal_map) wrapped_max = (Map.insert ((-) q1 4, r1) max wrapped_min) in wrapped_max compatibleVertices = \gaussian_map quadrant -> let (less, equal, greater) = (Map.splitLookup quadrant gaussian_map) parallel = [LS.endpoint0 (fromJust equal), LS.endpoint1 (fromJust equal)] result = [LS.endpoint1 (snd (Map.findMax less))] in (ifElse (isJust equal) parallel result) -- assumes no sequential edges are parallel convexMinkowskiSumEdges = \a_edges b_edges -> let a_map = (gaussianMap a_edges) b_map = (gaussianMap b_edges) edgeVertexEdges = \gaussian_map edge -> let vertices = (compatibleVertices gaussian_map (edgeNormalQuadrantRatio edge)) in (List.map (LS.translate edge) vertices) in ((++) (concat (List.map (edgeVertexEdges b_map) a_edges)) (concat (List.map (edgeVertexEdges a_map) b_edges))) -- assumes no sequential edges are parallel; this requirement can be ensured by first calling the convexHull function on each polygon convexPenetrationDepth = \a_points b_points -> let a_edges = (pointsToEdges a_points) b_negated_edges = (pointsToEdges (List.map V.negate b_points)) minkowski_sum = (convexMinkowskiSumEdges a_edges b_negated_edges) origin = (V.zero 2) distances_to_origin = (List.map (flip LS.distanceSquaredToPoint origin) minkowski_sum) closest = (snd (List.minimum (zip distances_to_origin minkowski_sum))) to_origin = (V.subtract origin (LS.closestPoint closest origin)) is_inside = ((<) (dotProduct to_origin (edgeNormal closest)) 0) in (is_inside, to_origin) convexPenetrationPoint = \a_points b_points -> let (is_overlap, penetration) = (convexPenetrationDepth a_points b_points) a_map = (gaussianMap (pointsToEdges a_points)) b_map = (gaussianMap (pointsToEdges b_points)) a_contacts = (compatibleVertices a_map (V2d.quadrantRatio (V.negate penetration))) b_contacts = (compatibleVertices b_map (V2d.quadrantRatio penetration)) contact = (ifElse ((==) (List.length a_contacts) 1) (head a_contacts) (head b_contacts)) in (is_overlap, contact, penetration) setPrecision = \precision -> (List.map (V.setPrecision precision)) setPrecision10 = (Geometry.Polygon.setPrecision ((%) 1 10000000000))
stevedonnelly/haskell
code/Geometry/Polygon.hs
mit
9,621
0
23
1,614
3,592
1,975
1,617
149
1
{-# LANGUAGE GADTs #-} {-# OPTIONS_GHC -fno-do-lambda-eta-expansion #-} module Text.Regex.Applicative.Compile (compile) where import Control.Monad.Trans.State import Text.Regex.Applicative.Types import Control.Applicative import Data.Maybe import qualified Data.IntMap as IntMap compile :: RE s a -> (a -> [Thread s r]) -> [Thread s r] compile e k = compile2 e (SingleCont k) data Cont a = SingleCont !a | EmptyNonEmpty !a !a instance Functor Cont where fmap f k = case k of SingleCont a -> SingleCont (f a) EmptyNonEmpty a b -> EmptyNonEmpty (f a) (f b) emptyCont :: Cont a -> a emptyCont k = case k of SingleCont a -> a EmptyNonEmpty a _ -> a nonEmptyCont :: Cont a -> a nonEmptyCont k = case k of SingleCont a -> a EmptyNonEmpty _ a -> a -- The whole point of this module is this function, compile2, which needs to be -- compiled with -fno-do-lambda-eta-expansion for efficiency. -- -- Since this option would make other code perform worse, we place this -- function in a separate module and make sure it's not inlined. -- -- The point of "-fno-do-lambda-eta-expansion" is to make sure the tree is -- "compiled" only once. -- -- compile2 function takes two continuations: one when the match is empty and -- one when the match is non-empty. See the "Rep" case for the reason. compile2 :: RE s a -> Cont (a -> [Thread s r]) -> [Thread s r] compile2 e = case e of Eps -> \k -> emptyCont k () Symbol i p -> \k -> [t $ nonEmptyCont k] where -- t :: (a -> [Thread s r]) -> Thread s r t k = Thread i $ \s -> if p s then k s else [] App n1 n2 -> let a1 = compile2 n1 a2 = compile2 n2 in \k -> case k of SingleCont k -> a1 $ SingleCont $ \a1_value -> a2 $ SingleCont $ k . a1_value EmptyNonEmpty ke kn -> a1 $ EmptyNonEmpty -- empty (\a1_value -> a2 $ EmptyNonEmpty (ke . a1_value) (kn . a1_value)) -- non-empty (\a1_value -> a2 $ EmptyNonEmpty (kn . a1_value) (kn . a1_value)) Alt n1 n2 -> let a1 = compile2 n1 a2 = compile2 n2 in \k -> a1 k ++ a2 k Fail -> const [] Fmap f n -> let a = compile2 n in \k -> a $ fmap (. f) k -- This is actually the point where we use the difference between -- continuations. For the inner RE the empty continuation is a -- "failing" one in order to avoid non-termination. Rep g f b n -> let a = compile2 n threads b k = combine g (a $ EmptyNonEmpty (\_ -> []) (\v -> let b' = f b v in threads b' (SingleCont $ nonEmptyCont k))) (emptyCont k b) in threads b Void n -> let a = compile2_ n in \k -> a $ fmap ($ ()) k data FSMState = SAccept | STransition ThreadId type FSMMap s = IntMap.IntMap (s -> Bool, [FSMState]) mkNFA :: RE s a -> ([FSMState], (FSMMap s)) mkNFA e = flip runState IntMap.empty $ go e [SAccept] where go :: RE s a -> [FSMState] -> State (FSMMap s) [FSMState] go e k = case e of Eps -> return k Symbol i@(ThreadId n) p -> do modify $ IntMap.insert n $ (p, k) return [STransition i] App n1 n2 -> go n1 =<< go n2 k Alt n1 n2 -> (++) <$> go n1 k <*> go n2 k Fail -> return [] Fmap _ n -> go n k Rep g _ _ n -> let entries = findEntries n cont = combine g entries k in -- return value of 'go' is ignored -- it should be a subset of -- 'cont' go n cont >> return cont Void n -> go n k findEntries :: RE s a -> [FSMState] findEntries e = -- A simple (although a bit inefficient) way to find all entry points is -- just to use 'go' evalState (go e []) IntMap.empty compile2_ :: RE s a -> Cont [Thread s r] -> [Thread s r] compile2_ e = let (entries, fsmap) = mkNFA e mkThread _ k1 (STransition i@(ThreadId n)) = let (p, cont) = fromMaybe (error "Unknown id") $ IntMap.lookup n fsmap in [Thread i $ \s -> if p s then concatMap (mkThread k1 k1) cont else []] mkThread k0 _ SAccept = k0 in \k -> concatMap (mkThread (emptyCont k) (nonEmptyCont k)) entries combine g continue stop = case g of Greedy -> continue ++ stop NonGreedy -> stop ++ continue
mitchellwrosen/regex-applicative
Text/Regex/Applicative/Compile.hs
mit
4,683
0
23
1,670
1,512
763
749
105
10
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} module Problem08 (partA, partB) where import Data.List import Control.Lens import Text.Megaparsec hiding (State) import Text.Megaparsec.String import qualified Text.Megaparsec.Lexer as L inputLocation = "input/input8.txt" transposeIso :: Iso' [[a]] [[a]] transposeIso = iso transpose transpose data ScreenAction = TurnOn Int Int | RotateRow Int | RotateColumn Int deriving (Eq,Show) newtype Screen = Screen {getScreen :: [[Bool]]} deriving (Eq) lightsOn (Screen s) = sum $ map (length . filter id) s emptyScreen :: Int -> Int -> Screen emptyScreen w h = Screen $ replicate h $ replicate w False instance Show Screen where show (Screen a) = unlines $ map (map (\x -> if x then '#' else '.')) a instance Wrapped Screen where type Unwrapped Screen = [[Bool]] _Wrapped' = iso getScreen Screen instance (t ~ Screen) => Rewrapped Screen t applyAction :: Screen -> ScreenAction -> Screen applyAction scr (TurnOn x y) = scr & _Wrapped . ix y . ix x .~ True applyAction scr (RotateRow y) = scr & _Wrapped . ix y %~ helper where helper xs = last xs : init xs applyAction scr (RotateColumn y) = scr & _Wrapped . transposeIso . ix y %~ helper where helper xs = last xs : init xs applyManyAction :: Screen -> [ScreenAction] -> Screen applyManyAction = foldl' applyAction rect :: Int -> Int -> [ScreenAction] rect w h = TurnOn <$> [0..w-1] <*> [0..h-1] rotateColumnBy :: Int -> Int -> [ScreenAction] rotateColumnBy x n = replicate n $ RotateColumn x rotateRowBy :: Int -> Int -> [ScreenAction] rotateRowBy y n = replicate n $ RotateRow y parseInt :: Parser Int parseInt = fromIntegral <$> L.integer parseActions :: Parser [ScreenAction] parseActions = (rect <$> (string "rect " *> parseInt) <*> (char 'x' *> parseInt)) <|> (rotateColumnBy <$> (string "rotate column x=" *> parseInt) <*> (string " by " *> parseInt)) <|> (rotateRowBy <$> (string "rotate row y=" *> parseInt) <*> (string " by " *> parseInt)) partA :: IO () partA = do lines <- lines <$> readFile inputLocation let instructions = concat $ either (error . show) id $ mapM (parse parseActions "") lines let screenOutput = applyManyAction (emptyScreen 50 6) instructions print $ lightsOn screenOutput partB :: IO () partB = do lines <- lines <$> readFile inputLocation let instructions = concat $ either (error . show) id $ mapM (parse parseActions "") lines print $ applyManyAction (emptyScreen 50 6) instructions
edwardwas/adventOfCodeTwo
src/Problem08.hs
mit
2,697
0
14
573
963
499
464
-1
-1
module Play where import Types import Wave import Control.Exception import qualified Data.Vector.Unboxed as V import Prelude hiding (catch) import Sound.Sox.Play as Play import Sound.Sox.Signal.List as SignalList import Sound.Sox.Option.Format as Option import System.Exit play :: FrameStream -> IO () play audio = do Play.simple SignalList.put Option.none samplingRate (simpleData audio) `catch` \err -> do print (err :: IOException); exitFailure return () where simpleData stream = V.toList (discreteSamples stream)
garncarz/synth-haskell
Play.hs
gpl-2.0
527
2
12
75
168
97
71
16
1
module SMCDEL.Examples.Prisoners where import Data.HasCacBDD hiding (Top,Bot) import SMCDEL.Explicit.S5 import SMCDEL.Internal.TexDisplay import SMCDEL.Language import SMCDEL.Symbolic.S5 n :: Int n = 3 light :: Form light = PrpF (P 0) -- P 0 -- light is on -- P i -- agent i has been in the room (and switched on the light) -- agents: 1 is the counter, 2 and 3 are the others prisonExpStart :: KripkeModelS5 prisonExpStart = KrMS5 [1] [ ("1",[[1]]) ] [ (1, [(P k,False) | k <- [0..n] ] ) ] prisonGoal :: Form prisonGoal = K "1" $ Conj [ PrpF $ P k | k <- [1..n] ] prisonAction :: ActionModelS5 prisonAction = ActMS5 actions actRels where p = PrpF . P actions = [ (0, (p 0 , [(P 0, Bot), (P 1, Top)]) ) -- interview 1 with light on , (1, (Neg (p 0), [ (P 1, Top)]) ) -- interview 1 with light off ] ++ [ (k, (Top, [(P 0, p k `Impl` p 0), (P k, p 0 `Impl` p k)]) ) | k <- [2..n] ] -- interview k actRels = [ ("1", [[0],[1],[2..n]]) ] prisonInterview :: Int -> MultipointedActionModelS5 prisonInterview 1 = (prisonAction, [0,1]) prisonInterview k = (prisonAction, [k]) data Story a b = Story a [b] endOf :: (Update a b, Optimizable a) => Story a b -> a endOf (Story start actions) = foldl (\cur a -> optimize (vocabOf start) $ cur `update` a) start actions instance (Update a b, Optimizable a, TexAble a, TexAble b) => TexAble (Story a b) where tex (Story start actions) = adjust (tex start) ++ loop start actions where adjust thing = " \\raisebox{-.5\\height}{ \\begin{adjustbox}{max height=4cm, max width=0.3\\linewidth} $ " ++ thing ++ " $ \\end{adjustbox} } " loop _ [] = "" loop current (a:as) = let new = optimize (vocabOf start) $ current `update` a in " \\times " ++ adjust (tex a) ++ " = " ++ adjust (tex new) ++ "\\] \\[ " ++ loop new as prisonExpStory :: Story PointedModelS5 MultipointedActionModelS5 prisonExpStory = Story (prisonExpStart,1) (map prisonInterview [2,1,3,1]) prisonSymStart :: MultipointedKnowScene prisonSymStart = (KnS (map P [0..n]) law obs, actualStatesBdd) where law = boolBddOf (Conj (Neg light : [ Neg $ wasInterviewed k | k <- [1..n] ])) obs = [ ("1", []) ] actualStatesBdd = top wasInterviewed, isNowInterviewed :: Int -> Form wasInterviewed = PrpF . P isNowInterviewed k = PrpF (P (k + n)) lightSeenByOne :: Form lightSeenByOne = PrpF (P (1 + (2*n))) prisonSymEvent :: KnowTransformer prisonSymEvent = KnTrf -- agent 1 is interviewed (map P $ [ k+n | k <- [1..n] ] ++ [1+(2*n)] ) -- distinguish events (Conj [ isNowInterviewed 1 `Impl` (lightSeenByOne `Equi` light) , Disj [ Conj $ isNowInterviewed k : [Neg $ isNowInterviewed l | l <- [1..n], l /= k ] | k <- [1..n]] ] ) -- light might be switched and visits of the agents might be recorded ( [ (P 0, boolBddOf $ Conj $ isNowInterviewed 1 `Impl` Bot -- 1 turns off the light : concat [ [ Conj [Neg $ wasInterviewed k, isNowInterviewed k] `Impl` Top , Conj [ wasInterviewed k, isNowInterviewed k] `Impl` light ] | k <- [2..n] ]) , (P 1, boolBddOf $ Disj [wasInterviewed 1, Conj [ isNowInterviewed 1]]) ] ++ [ (P k, boolBddOf $ Disj [wasInterviewed k, Conj [Neg light, isNowInterviewed k]]) | k <- [2..n] ] ) -- agent 1 observes whether they are interviewed, and if so, also observes the light [ ("1", let (PrpF px, PrpF py) = (isNowInterviewed 1, lightSeenByOne) in [px, py]) ] prisonSymInterview :: Int -> MultipointedEvent prisonSymInterview k = (prisonSymEvent, boolBddOf (isNowInterviewed k)) prisonSymStory :: Story MultipointedKnowScene MultipointedEvent prisonSymStory = Story prisonSymStart (map prisonSymInterview [2,1,3,1])
jrclogic/SMCDEL
src/SMCDEL/Examples/Prisoners.hs
gpl-2.0
3,793
0
18
894
1,474
811
663
73
1
{- | Module : $Header$ Description : Maude Morphisms Copyright : (c) Martin Kuehl, Uni Bremen 2008-2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable Definition of morphisms for Maude. -} module Maude.Morphism ( -- * Types -- ** The Morphism type Morphism (..), -- ** Auxiliary type SortMap, KindMap, OpMap, -- * Construction fromSignRenamings, fromSignsRenamings, empty, identity, inclusion, -- * Combination inverse, union, compose, -- * Testing isInclusion, isLegal, -- * Conversion symbolMap, -- * Modification setTarget, qualifySorts, applyRenamings, extendWithSortRenaming, -- * Application translateSentence, translateSorts, ) where import Maude.AS_Maude import Maude.Symbol import Maude.Meta import Maude.Util import Maude.Printing () import Maude.Sign (Sign, kindRel, KindRel) import Maude.Sentence (Sentence) import qualified Maude.Sign as Sign import Data.List (partition) import Data.Maybe (fromJust) import qualified Data.Set as Set import qualified Data.Map as Map import Common.Result (Result) import Common.Doc hiding (empty) import Common.DocUtils (Pretty (..)) -- * Types -- ** Auxiliary types type SortMap = SymbolMap type KindMap = SymbolMap type OpMap = SymbolMap type LabelMap = SymbolMap -- ** The Morphism type data Morphism = Morphism { source :: Sign, target :: Sign, sortMap :: SortMap, kindMap :: KindMap, opMap :: OpMap, labelMap :: LabelMap } deriving (Show, Ord, Eq) -- ** 'Morphism' instances instance Pretty Morphism where pretty mor = let pr'pair txt left right = hsep [txt, pretty left, text "to", pretty right] pr'ops src tgt = pr'pair (text "op") src (getName tgt) pr'map fun = vcat . map (uncurry fun) . Map.toList smap = pr'map (pr'pair $ text "sort") $ sortMap mor kmap = pr'map (pr'pair $ text "kind") $ kindMap mor omap = pr'map pr'ops $ opMap mor lmap = pr'map (pr'pair $ text "label") $ labelMap mor s = pretty $ source mor t = pretty $ target mor in vcat [ smap, kmap, omap, lmap, pretty "\nSource:\n", s , pretty "\nTarget\n", t ] -- * Helper functions -- ** to modify Morphisms mapTarget :: (Sign -> Sign) -> Morphism -> Morphism mapTarget func mor = mor { target = func $ target mor } mapSortMap :: (SortMap -> SortMap) -> Morphism -> Morphism mapSortMap func mor = mor { sortMap = func $ sortMap mor } mapOpMap :: (OpMap -> OpMap) -> Morphism -> Morphism mapOpMap func mor = mor { opMap = func $ opMap mor } mapLabelMap :: (LabelMap -> LabelMap) -> Morphism -> Morphism mapLabelMap func mor = mor { labelMap = func $ labelMap mor } -- ** to handle Renamings -- TODO: Handle Attrs in Op Renamings. renamingSymbolsMaybe :: Renaming -> Maybe (Symbol, Symbol) renamingSymbolsMaybe rename = case rename of SortRenaming src tgt -> Just (asSymbol src, asSymbol tgt) LabelRenaming src tgt -> Just (asSymbol src, asSymbol tgt) OpRenaming1 src (To tgt _) -> Just (asSymbol src, asSymbol tgt) OpRenaming2 src dom cod (To tgt _) -> let src' = Op src dom cod [] tgt' = Op tgt dom cod [] in Just (asSymbol src', asSymbol tgt') TermMap _ _ -> Nothing -- | Extract the 'Symbol's from a 'Renaming', if possible. renamingSymbols :: Renaming -> (Symbol, Symbol) renamingSymbols = fromJust . renamingSymbolsMaybe -- | Separate Operator and other Renamings. partitionRenamings :: [Renaming] -> ([Renaming], [Renaming]) partitionRenamings = let is'op renaming = case renaming of OpRenaming1 _ _ -> True OpRenaming2 _ _ _ _ -> True _ -> False in partition is'op -- ** to apply Renamings to Morphisms {- | Insert an 'Operator' 'Renaming' into a 'Morphism'. Iff apply is True, apply the Renaming to the Morphism's target Signature. -} insertOpRenaming :: Bool -> Renaming -> Morphism -> Morphism insertOpRenaming apply rename = let syms = renamingSymbols rename add'op = mapOpMap $ uncurry Map.insert syms use'op attrs = if apply then mapTarget $ uncurry Sign.renameOp syms attrs else id in case rename of OpRenaming1 _ (To _ attrs) -> use'op attrs . add'op OpRenaming2 _ _ _ (To _ attrs) -> use'op attrs . add'op _ -> id {- | Insert a non-Operator 'Renaming' into a 'Morphism'. iff True, apply the Renaming to the target Sign -} insertRenaming :: Bool -> Renaming -> Morphism -> Morphism insertRenaming apply rename = let syms = renamingSymbols rename add'sort = mapSortMap $ uncurry Map.insert syms use'sort = if apply then mapTarget $ uncurry Sign.renameSort syms else id ren'sort = mapOpMap $ uncurry renameSortOpMap syms add'labl = mapLabelMap $ uncurry Map.insert syms use'labl = if apply then mapTarget $ uncurry Sign.renameLabel syms else id in case rename of SortRenaming _ _ -> ren'sort . use'sort . add'sort LabelRenaming _ _ -> use'labl . add'labl _ -> id -- | Rename sorts in the profiles of an operator map. renameSortOpMap :: Symbol -> Symbol -> OpMap -> OpMap renameSortOpMap from to = Map.map $ mapSorts $ Map.singleton from to -- | Insert 'Renaming's into a 'Morphism'. insertRenamings :: Bool -> Morphism -> [Renaming] -> Morphism insertRenamings apply mor rens = let (ops, rest) = partitionRenamings rens add'ops = flip (foldr $ insertOpRenaming apply) ops add'rest = flip (foldr $ insertRenaming apply) rest in add'rest . add'ops $ mor -- * Construction -- | Create a 'Morphism' from an initial 'Sign'ature and a list of 'Renaming's. fromSignRenamings :: Sign -> [Renaming] -> Morphism fromSignRenamings s rs = kindMorph $ insertRenamings True (identity s) rs -- | Create a 'Morphism' from a pair of 'Sign'atures and a list of 'Renaming's. fromSignsRenamings :: Sign -> Sign -> [Renaming] -> Morphism fromSignsRenamings sign1 sign2 rs = kindMorph $ insertRenamings False (inclusion sign1 sign2) rs -- | the empty 'Morphism' empty :: Morphism empty = identity Sign.empty -- | the identity 'Morphism' identity :: Sign -> Morphism identity sign = inclusion sign sign -- | the inclusion 'Morphism' inclusion :: Sign -> Sign -> Morphism inclusion src tgt = Morphism { source = src, target = tgt, sortMap = Map.empty, kindMap = Map.empty, opMap = Map.empty, labelMap = Map.empty } -- * Combination -- | the inverse 'Morphism' inverse :: Morphism -> Result Morphism inverse mor = let invertMap = Map.foldWithKey (flip Map.insert) Map.empty in return $ kindMorph Morphism { source = target mor, target = source mor, sortMap = invertMap $ sortMap mor, kindMap = invertMap $ kindMap mor, opMap = invertMap $ opMap mor, labelMap = invertMap $ labelMap mor } -- | the union of two 'Morphism's union :: Morphism -> Morphism -> Morphism union mor1 mor2 = let apply func items = func (items mor1) (items mor2) in kindMorph Morphism { source = apply Sign.union source, target = apply Sign.union target, sortMap = apply Map.union sortMap, kindMap = apply Map.union kindMap, opMap = apply Map.union opMap, labelMap = apply Map.union labelMap } -- Just a shorthand for types inside compose. type Extraction = Morphism -> SymbolMap -- | the composition of two 'Morphism's compose :: Morphism -> Morphism -> Result Morphism compose f g | target f /= source g = fail "target of the first and source of the second morphism are different" | otherwise = let {- Take SymbolMap |mp| of each Morphism. Convert each SymbolMap to a function. Compose those functions. -} map'map :: Extraction -> Symbol -> Symbol map'map mp = mapAsFunction (mp g) . mapAsFunction (mp f) {- Map |x| via the composed SymbolMaps |mp| of both Morphisms. Insert the renaming mapping into a SymbolMap. -} insert :: Extraction -> Symbol -> SymbolMap -> SymbolMap insert mp x = let y = map'map mp x in if x == y then id else Map.insert x y -- Map each symbol in |items| via the combined SymbolMaps |mp|. compose'map :: Extraction -> (Sign -> SymbolSet) -> SymbolMap compose'map mp items = if Map.null (mp g) -- if the SymbolMap of |g| is empty, we use the one from |f| then mp f {- otherwise we start with the SymbolSet from |source f| and construct a combined SymbolMap by applying both SymbolMaps (from |f| and |g|) to each item in |insert| -} else Set.fold (insert mp) Map.empty $ items (source f) -- We want a morphism from |source f| to |target g|. mor = inclusion (source f) (target g) in return $ kindMorph mor { sortMap = compose'map sortMap getSorts, opMap = compose'map opMap getOps, labelMap = compose'map labelMap getLabels } -- * Testing -- | True iff the 'Morphism' is an inclusion isInclusion :: Morphism -> Bool isInclusion mor = let null'sortMap = Map.null (sortMap mor) null'opMap = Map.null (opMap mor) null'labelMap = Map.null (labelMap mor) in all id [null'sortMap, null'opMap, null'labelMap] -- | True iff the 'Morphism' is legal isLegal :: Morphism -> Result () isLegal mor = let src = source mor tgt = target mor smap = sortMap mor omap = opMap mor lmap = labelMap mor subset mp items = let mapped = Set.map $ mapAsFunction mp in Set.isSubsetOf (mapped $ items src) $ items tgt lg'source = Sign.isLegal src lg'sortMap = subset smap getSorts lg'opMap = subset omap getOps lg'labelMap = subset lmap getLabels lg'target = Sign.isLegal tgt in if all id [lg'source, lg'sortMap, lg'opMap, lg'labelMap, lg'target] then return () else fail "illegal Maude morphism" -- * Conversion -- | extract the complete 'SymbolMap' of a 'Morphism' symbolMap :: Morphism -> SymbolMap symbolMap mor = Map.unions [sortMap mor, opMap mor, labelMap mor] -- * Modification -- | set a new target for a 'Morphism' setTarget :: Sign -> Morphism -> Morphism setTarget sg m = kindMorph $ mapTarget (const sg) m -- | qualify a list of 'Symbol's inside a 'Morphism' qualifySorts :: Morphism -> Qid -> Symbols -> Morphism qualifySorts mor qid syms = let insert symb = Map.insert symb $ qualify qid symb smap = foldr insert Map.empty syms q'tgt = mapTarget $ mapSorts smap q'smap = mapSortMap $ mapSorts smap x'smap = mapSortMap $ Map.union smap in kindMorph $ q'tgt . x'smap . q'smap $ mor -- | apply a list of 'Renaming's to a 'Morphism' applyRenamings :: Morphism -> [Renaming] -> Morphism applyRenamings m rs = kindMorph $ insertRenamings True m rs -- | apply a 'Sort' 'Renaming' to a 'Morphism' extendWithSortRenaming :: Symbol -> Symbol -> Morphism -> Morphism extendWithSortRenaming src tgt m = let add'sort = mapSortMap $ Map.insert src tgt use'sort = mapTarget $ Sign.renameSort src tgt ren'sort = mapOpMap $ renameSortOpMap src tgt in kindMorph $ ren'sort . use'sort $ add'sort m -- * Application -- | translate a 'Sentence' along a 'Morphism' translateSentence :: Morphism -> Sentence -> Result Sentence translateSentence mor = let smap = mapSorts (sortMap mor) omap = mapOps (opMap mor) lmap = mapLabels (labelMap mor) in return . lmap . smap . omap -- | translate 'Sort's along a 'Morphism' translateSorts :: (HasSorts a) => Morphism -> a -> a translateSorts = mapSorts . sortMap -- * Auxiliary functions kindMorph :: Morphism -> Morphism kindMorph morph = morph { kindMap = kindMorphAux kr1 sm kr2} where kr1 = kindRel $ source morph kr2 = kindRel $ target morph sm = Map.toList $ sortMap morph kindMorphAux :: KindRel -> [(Symbol, Symbol)] -> KindRel -> KindMap kindMorphAux _ [] _ = Map.empty kindMorphAux kr1 ((s1, s2) : ls) kr2 = Map.union m m' where m = kindMorphAux kr1 ls kr2 (k1, k2) = case (Map.lookup s1 kr1, Map.lookup s2 kr2) of (Just r1, Just r2) -> (r1, r2) _ -> (s1, s1) m' = if k1 == k2 then Map.empty else Map.singleton k1 k2
nevrenato/Hets_Fork
Maude/Morphism.hs
gpl-2.0
12,498
0
15
3,161
3,360
1,767
1,593
247
5
{-# LANGUAGE OverloadedStrings #-} module Config where import Data.Configurator import Data.Configurator.Types (Value (..),Configured (..)) import System.IO.Unsafe data List a = L [a] instance Configured a => Configured (List a) where convert (List vs) = L <$> traverse convert vs convert _ = Nothing antiQuoteStrings :: [String] quoteStrings :: [(String,String)] (antiQuoteStrings,quoteStrings) = unsafePerformIO $ do cfg <- load [Optional ".marxup"] L aq <- lookupDefault (L ["@"]) cfg "antiQuotes" L q <- lookupDefault (L [("«","»")]) cfg "quotes" return (aq,q) -- Local Variables: -- dante-target: "marxup" -- End:
jyp/MarXup
Config.hs
gpl-2.0
653
0
13
117
230
126
104
16
1
-- | Non-annotating type checker. module TypeChecker where --import qualified Data.Map as M import AbsCPP import PrintCPP import ErrM import BuiltIns import Environment typecheck :: Program -> Err () -- Program typecheck (Prog defs) = do env <- buildFunTable emptyEnvT (defs ++ builtInFunctions) checkDefs env defs -- | Builds a symbol table for functions -- in a type-checking environment. buildFunTable :: EnvT -> [Def] -> Err EnvT -- or just SigTab buildFunTable env [] = return env buildFunTable env (d:ds) = case d of Fun ftype id args _ -> do env' <- updateFunT env id (map argType args, ftype) buildFunTable env' ds _ -> fail "Bad function definition, buildFunTable" checkDefs :: EnvT -> [Def] -> Err () checkDefs env [] = return () checkDefs env (d:ds) = do env' <- checkDef env d checkDefs env' ds checkDef :: EnvT -> Def -> Err EnvT checkDef env (Fun typ id args stms) = do env' <- addArgsT (addScopeT env) args env'' <- updateVarT env' (Id "return") typ --since return i a reserved word, there will never be a variable with that as id --so we can use it to store the function type in every scope checkStms env'' stms checkStms :: EnvT -> [Stm] -> Err EnvT checkStms env [] = return env checkStms env (st:stms) = do env' <- checkStm env st checkStms env' stms checkStm :: EnvT -> Stm -> Err EnvT checkStm env s = case s of SDecl t x -> updateVarT env x t SAss x e -> do t <- lookupVarT env x checkExp env e t return env SInit typ id exp -> do env' <- checkStm env (SDecl typ id) --first declare checkStm env' (SAss id exp) --then assign SBlock stms -> do checkStms (addScopeT env) stms return env -- SPrint e -> do inferExp env e -- return env SDecls typ [] -> return env SDecls typ (i:is) -> do env' <- checkStm env (SDecl typ i) checkStm env' (SDecls typ is) SReturn exp -> do retType <- lookupVarT env (Id "return") checkExp env exp retType return env SExp exp -> do t <- inferExp env exp return env --is there anything to actually do with an exp? SIfElse exp s1 s2 -> do checkExp env exp TBool env' <- checkStm env s1 env'' <- checkStm env s2 return env SWhile exp stm -> do checkExp env exp TBool env' <- checkStm env stm return env --updateVars env ids typ _ -> fail ( "case not exhaustive in checkstm \n" ++ show s ++ " \n " ++ printTree s) checkExp :: EnvT -> Exp -> Type -> Err () -- Err Exp checkExp env e t = do t' <- inferExp env e if t' /= t then fail (printTree e ++ " has type " ++ printTree t' ++ " expected " ++ printTree t) else return () -- ETyped r t -- ETyped can be defined in the grammar -- as internal rule ETyped Exp ::= "(" Type ")" Exp1 -- Parse will fail, but we will have the info in AST inferExp :: EnvT -> Exp -> Err Type inferExp env e = case e of EId x -> lookupVarT env x EInt _ -> return TInt EDouble _ -> return TDouble EApp id exps -> inferFun env e ETrue -> return TBool EFalse -> return TBool --Assignment and type comparison, re-used many times EAss e1 e2 -> do t1 <- inferExp env e1 t2 <- inferExp env e2 if t1 == t2 then return t1 else fail (printTree e1 ++ " has type " ++ printTree t1 ++ " but " ++ printTree e2 ++ " has type " ++ printTree t2) --Comparisons ENEq e1 e2 -> inferExp env (ELtEq e1 e2) -- EEq e1 e2 -> inferExp env (ELtEq e1 e2) -- This will allow comparison between voids, EGt e1 e2 -> inferExp env (ELtEq e1 e2) -- Which doesn't have an interpretation ELt e1 e2 -> inferExp env (ELtEq e1 e2) EGtEq e1 e2 -> inferExp env (ELtEq e1 e2) ELtEq e1 e2 -> do t0 <- inferExp env (EAss e1 e2) return TBool --Arithmetics EDiv e1 e2 -> inferExp env (EPlus e1 e2) -- ETimes e1 e2 -> inferExp env (EPlus e1 e2) -- EMinus e1 e2 -> inferExp env (EPlus e1 e2) -- EPlus e1 e2 -> do t1 <- inferExp env (EAss e1 e2) if t1 == TBool || t1 == TVoid then fail "Arithmetic operation on bool or void type" else return t1 --Logic And,Or EOr e1 e2 -> inferExp env (EAnd e1 e2) EAnd e1 e2 -> do checkExp env e1 TBool checkExp env e2 TBool return TBool --Incr group EPDecr exp -> inferExp env (EIncr exp) EPIncr exp -> inferExp env (EIncr exp) EDecr exp -> inferExp env (EIncr exp) EIncr exp -> do t <- inferExp env exp if t == TBool || t == TVoid then fail "Increment operation on bool/void" else return t --Catch-all, should never happen _ -> fail ("inferExp has a non exhaustive case pattern \n" ++ show e ++ " \n " ++ printTree e) inferFun :: EnvT -> Exp -> Err Type inferFun env (EApp id exps) = do (types, ftype) <- lookupFunT env id inferFunHelper env exps types return ftype inferFunHelper :: EnvT -> [Exp] -> [Type] -> Err () inferFunHelper env [] [] = return () inferFunHelper env [] types = fail "too few args in function call" inferFunHelper env exps [] = fail "too many args in function call" inferFunHelper env (e:es) (t:ts) = do etyp <- inferExp env e if etyp == t then inferFunHelper env es ts else fail "type error in argument of function call" inferFunHelper _ _ _ = fail "inferFunHelper has non exhaustive case pattern"
izimbra/PLT2014
Lab2/TypeChecker.hs
gpl-2.0
7,120
0
19
3,202
1,887
887
1,000
120
27
--CRITICAL: Genomes are currently not compiled as safe. Relevant changes include GRPSeed, GRPSeedhr, Headless line 59 and Core line 134. --This is so Language.Haskell.Exts.Parser is viable to use. import GRPSeed import GRPCommon import GRPFitness import GRPSafety import PartitioningProblem import GRPStats import GRPGenerator import System.Environment (getArgs) import System.Random import System.Directory import System.Process (readProcessWithExitCode, createProcess, shell) import System.Exit (ExitCode(..)) import System.IO.Strict(readFile) import Data.Maybe import Data.List import Data.Either import Data.Function import Data.Tree import Data.Ord import Control.Applicative import Debug.Trace import Language.Haskell.Exts.Parser import Language.Haskell.Exts.Pretty {- This file is the core of the application. The usual procedure here is to pick GRPSeed.hs, make GRPGenome0.hs from it's source, generate AgentStats for it and save it to GRPGenome0.hs.stat, and generate GRPGenome0hl.hs based on GRPHeadless That single genome shall be our 0th generation. From here on, the application keeps refilling the genome pool to it's full size and reducing it to filtered size, both given as part of settings. Various debug informatiion will be printed and the application will save a copy of the Pool (does not contain genomes directly, but their file paths) as well as a dotfile displaying parent-child relations. -} --TODO: Implement abstract interfaces for: -- Continuous compound simulations -- Discrete compound simulations -- Discrete single-agent tasks --Compound simulations being fitness measures where there's direct competition - for example chess in versus mode(discrete), or a ALife simulations (continuous) --single-agent tasks are static fitness benchmarks for agents data Pool = Pool { maxSize :: Int, filteredSize :: Int, nextID :: Int, agents :: [AgentStats], oldAgents :: [AgentStats] } deriving (Show, Read) data Settings = Settings { initialAgent :: FilePath, resultpath :: FilePath, generations :: Int, poolMin :: Int, poolMax :: Int } --This can be used to improve the compile rate of children of the root genome. Just testing around. haskellSrcExtsTest :: IO() haskellSrcExtsTest = do source <- System.IO.Strict.readFile "./GRPSeed.hs" let parseResult = parseModule source let ast = fromParseResult parseResult putStrLn $show ast putStrLn "\n\n\n" putStrLn $ prettyPrint ast main :: IO() main = do let params = Settings "./GRPSeed.hs" "./result" 50 30 600 ag <- initializeSeed $ initialAgent params let iPool = (initialPool ag (poolMin params) (poolMax params)) :: Pool compiledPool <- evaluateFitness iPool [] iteratePool (generations params) compiledPool (resultpath params) toDotFile :: Pool -> String toDotFile (Pool _ _ _ ags oldags) = unlines ( "strict graph network {" : (map arrow (ags ++ oldags) ) ++ (map label (ags ++ oldags)) ++ ["}"] ) where arrow ag = if not $ null $ ancestry ag then "\t" ++ (shortName $ source ag) ++ "--" ++ (shortName $ head $ ancestry ag) ++ ";" else "" shortName name = drop 2 $ reverse $ drop 3 $ reverse name label ag = "\t" ++ (shortName $ source ag) ++ "[label=\"" ++ ( shortName $ source ag ) ++ " " ++ ( show $ compiledChildren ag ) ++ " / " ++ ( show $ evaluatedChildren ag ) ++ "\"];" iteratePool :: Int -> Pool -> FilePath -> IO() iteratePool 0 pool dump = do writeFile (dump ++ "hr") $ unlines $ map (\(AgentStats path _ ancestry _ _ _ evalCh compCh) -> "Agent: " ++ path ++ ", ratio " ++ (show compCh) ++ "%" ++ (show evalCh) ++ ", ancestry: " ++ show ancestry ) $ agents pool writeFile dump $ show pool writeFile "ancestry.dot" $ toDotFile pool showPool pool stopGlobalPool --stop the thread pool - not the gene pool. iteratePool n pool dump = do putStrLn "filtered at begin: " writeFile (dump ++ show n) $ show pool writeFile (dump ++ show n ++ ".dot") $ toDotFile pool writeFile (dump ++ "hr" ++ show n) $ unlines $ map (\(AgentStats path _ ancestry _ _ _ evalCh compCh) -> "Agent: " ++ path ++ ", ratio " ++ (show compCh) ++ "%" ++ (show evalCh) ++ ", ancestry: " ++ show ancestry ) $ agents pool showPool pool; (crashedParents, fullP) <- refillPool pool evalP <- evaluateFitness fullP crashedParents iteratePool (n-1) (filterPool evalP) dump initialPool :: AgentStats -> Int -> Int -> Pool initialPool ags min max = Pool max min 1 [ags] [] initializeSeed :: FilePath -> IO AgentStats initializeSeed path = do --Copy source file src <- System.IO.Strict.readFile path writeFile "./GRPGenome0.hs" ("--{-# LANGUAGE Safe #-}\nmodule GRPGenome0\n" ++ (unlines $ drop 2 $ lines src)) --Use generator to generate a valid headless file for the source file generate "./GRPGenome0.hs" --create a stats file for the base genome. let ag = AgentStats "./GRPGenome0.hs" (Unchecked, 0.0) [] 1 [] True 0 0 -- Using True, because this one doesn't have a parent, so no need to. writeFile "./GRPGenome0.hs.stat" $ show ag return ag showPool (Pool _ _ _ ags _) = do putStrLn "\n\n\n" _ <- mapM (\(AgentStats path fitness _ gen _ _ evalCh compCh) -> putStrLn ( path ++ "; fitness: " ++ (show fitness) ++ " from generation " ++ (show gen) ++ "; ratio: " ++ (show (compCh, evalCh))) ) ags putStrLn "\n\n\n" return () --TODO: Implement a duplicate-check for genome names in Pool. --Following are two options of generating new genomes. --combines every agent's code gen with every agent's source code. --This can exceed the pool's max capacity, filling up to min capacity squared. --As a remedy to that problem (a already full pool handed to cartesianProduct might just require too much computation time..), a token system should be used. cartesianProduct :: Pool -> IO ([FilePath], Pool) cartesianProduct (Pool max f id agents oldags) = do let coderSourcePairs = [(coder, source) | coder <- agents, source <- agents] children <- mapM (\(genomeID, (c, s)) -> createChild c s genomeID) $ zip [id..] coderSourcePairs return $ (rights children, Pool max f (id + length coderSourcePairs) ((lefts children) ++ agents) oldags) --Possible remedy: Use the algorithm in GRPMath refillPool :: Pool -> IO ([FilePath], Pool) refillPool (Pool max f id agents oldags) = do --TODO: We can generate each genome's children sequentially, and can do that in parallel for all the parent genomes.. children <- mapM (\(p, id) -> createChild p p id) $ zip parents [id..] return $ (rights children, Pool max f (id + length parents) ((lefts children) ++ agents) oldags) where tokens = max - length agents parentFit = sortBy (comparing snd ) $ map (\ag -> (ag, getAggregateFitness ag) ) agents sumOfFits = sum $ map snd parentFit tokenPerFit = (fromIntegral tokens) / sumOfFits agTokens = map (\ (ag, fit) -> (ag, round( tokenPerFit * fit ) ) ) parentFit parents = concatMap (\ (ag, tok) -> replicate tok ag) agTokens --Very basic approach: each leftover parent generates children, starting with the best, until all slots are filled. --More sophisticated methods with certain biases for genetic diversity and better fitness values need to be tested. --Takes a genome as codeGen and a genome as base source and generates offspring --If generating a offspring fails, the parent genome will be punished, indicated by returning "Right *it's name*" --punishment will be handled when the aggregate result is injected into evaluateFitness --Assumption: Codegen has already been compiled. createChild :: AgentStats -> AgentStats-> Int -> IO (Either AgentStats FilePath) createChild codeAg@(AgentStats path fit ancestry generation state _ _ _) (AgentStats src _ _ _ _ _ _ _) id = do let destname = "GRPGenome" ++ show id ++ ".hs" let executable = (reverse $ drop 3 $ reverse path) ++ "hl" --If the above is exchanged for a static executable, one can have a static code generator to optimize the genomes. --call Evolve - generate resulting source code and stats file. writeFile (path ++ ".stat") $show codeAg (code, out, err) <- readProcessWithExitCode "timeout" ["1s", executable, "-e", src, destname] "" --with timeout if (code == ExitSuccess) then do generate destname --generate Headless file dump <- System.IO.Strict.readFile (destname ++ ".stat") return $ Left $ read dump else if (code == ExitFailure 124) then do --error code of timeout putStrLn ("the genome " ++ (show path) ++ " hit timeout when generating!") --Maybe, this is the place to heuristically detect infinilooping programs. return $ Right path --I would really like to punish this way more! else do printEv ("errors generated by evCall on " ++ path ++ ":") printEv $ show code printEv out printEv err return $ Right path printEv :: String -> IO() printEv str = return() --Just a shortcut to mute a lot of printLns. --Map operation over agents: cast fitness on it - if returned agent is at least compilation-fit. This will compile the executable. --Done in parallel. --Then call the executable to eval the problem-specific fitness, assuming compilation was achieved. --The evalGenome function returns data on whether a child --This also keeps feedback on each Genome about the compilation rate of it's children. --TODO: -- The mechanism by which producing non-compiling offspring will result in punishing of the parent needs to respect fitness values of the children generated too. evaluateFitness :: Pool -> [FilePath] -> IO Pool evaluateFitness (Pool max min id agents oldags) crashedParents = do evalResult <- parallel $ map (evalGenome) agents let (ags, feedback) = unzip evalResult let newAgs = digestFeedback ags ((concat feedback) ++ (zip (repeat False) crashedParents)) printEv ("newPool" ++ ( show newAgs )) return (Pool max min id newAgs oldags) --This function increments the counters for evaluated children and compiled children according to whether the newly evaluated child did compile. --TODO: This is a n^2 function, could be n log n by applying sorting. digestFeedback :: [AgentStats] -> [(Bool, FilePath)] -> [AgentStats] digestFeedback ags fb = let applyOneFeedbackItem agentlist feedbackItem =map (maybeApplyItemToAgent feedbackItem) agentlist maybeApplyItemToAgent item agent = if source agent == snd item then agent { evaluatedChildren = 1 + evaluatedChildren agent, compiledChildren = (if fst item then 1 else 0) + compiledChildren agent } else agent in foldl applyOneFeedbackItem ags fb --This function evaluates the fitness value of a Genome. --It also returns the parent's name if the genome didn't compile. --This is tracked and accounted for when assigning tickets for new offspring. -- Maybe we want the fitness value noise of evaluating a genome every iteration? evalGenome :: AgentStats -> IO (AgentStats, [(Bool, String)]) evalGenome ag@(AgentStats path fitOld ancestry generation state fitToParent eval comp) = if (fst fitOld) > Unchecked then do printFit "nothing to evaluate here" return (ag, []) else do printFit ("evaluating a genome " ++ path) let statfile = path ++ ".stat" src <- System.IO.Strict.readFile path (fitNew, errors) <- computeFitness src ((reverse $ drop 3 $ reverse path) ++ "hl.hs") writeFile statfile $show $AgentStats path fitNew ancestry generation state fitToParent eval comp if fitNew >= (Compilation, -1.0 * (2^127)) then do--process call to headless: Evaluate! printFit ("ok " ++ path) let executable = (reverse $ drop 3 $ reverse path) ++ "hl" (code, out, err) <- readProcessWithExitCode "timeout" ["1s", executable, "-f", path] "" --now with timeout if code /= ExitSuccess then putStrLn ("A genome failed to execute fitness properly\n" ++ err) else return () newDump <- System.IO.Strict.readFile statfile --read the AgentStats as modified by the child process. return (read newDump, if not fitToParent then [(True, parent ag)] else []) --return compiled agent; good feedback to the parent else do printFit ("This genome failed to compile " ++ path) return (AgentStats path fitNew ancestry generation state fitToParent eval comp, if not fitToParent then [(False, parent ag)] else []) --bad feedback to the parent. printFit :: String -> IO() printFit str = return () --same as above, mutes all fitness-related printlines. --filters the pool according to the following criteria: --Junk - no compilation -> remove entirely --unfit: more than allowedStrikes failed offspring --unfit: sorted out by being unfit relative to other agents -- ->Move these two categories to the oldAgents section. --Keep them for monitoring purposes. --fit: none of the above filterPool :: Pool -> Pool filterPool (Pool m fSize id ags oldags) = Pool m fSize id fit (unfit ++ oldags) where allowedStrikes = 100 noJunk = filter (\ag -> (fst $ getFitness ag) >= Compilation) ags (f1, unfit1) = filter2 (\ag -> evaluatedChildren ag < allowedStrikes || compiledChildren ag > 0) noJunk (fit, unfit2) = if length f1 > fSize then (take fSize f1, drop fSize f1) else (f1, []) unfit = unfit1 ++ unfit2 filter2 pred lst = ( filter pred lst, filter (not.pred) lst )
vektordev/GP
src/GRPCore.hs
gpl-2.0
13,285
13
19
2,542
3,335
1,715
1,620
181
6
{-# LANGUAGE NoMonomorphismRestriction, TypeFamilies #-} import Diagrams.Prelude hiding (Point(..), union, intersection) import qualified Diagrams.Prelude as DP import Diagrams.Backend.Cairo.CmdLine import Data.Colour import GGen.Geometry.Types import GGen.Geometry.Polygon import GGen.Geometry.PolygonCSG import Control.Monad (forM_) import Text.PrettyPrint (($$)) import qualified Text.PrettyPrint as PP -- Trivial squares a, b :: Polygon R2 a = Polygon [ P ( 1, 1) , P ( 1,-1) , P (-1,-1) , P (-1, 1) , P ( 1, 1) ] b = Polygon [ P ( 0, 0) , P ( 0, 2) , P ( 2, 2) , P ( 2, 0) , P ( 0, 0) ] -- Figure 2.1 from paper c, d :: Polygon R2 c = Polygon [ P ( 0, 8) , P (-8, 8) , P (-8,-8) , P ( 0,-8) ] d = Polygon [ P ( 0, 5) , P (-4, 5) , P (-4,-1) , P ( 2,-1) , P ( 2,-3) , P ( 0,-3) , P ( 0,-5) , P ( 4,-5) , P ( 4, 1) , P (-2, 1) , P (-2, 3) , P ( 0, 3) ] p2p :: Point R2 -> DP.Point R2 p2p (P v) = DP.P v polygonToPath (Polygon ps) = close $ fromVertices $ map p2p ps edgeToPath :: (PathLike p, V p ~ R2) => LineSeg R2 -> p edgeToPath (LineSeg a b) = fromVertices [p2p a, p2p b] taggedEdgeToPath :: (HasStyle p, PathLike p, V p ~ R2) => (Edge,Tag) -> p taggedEdgeToPath (edge, tag) = edgeToPath edge # lcA (color `withOpacity` 0.5) # lw 0.05 where color = case tag of Inside -> blue Outside -> red PosBound -> green NegBound -> orange --labelledTaggedEdge :: (Edge,Tag) -> a labelledTaggedEdge (edge, tag) = taggedEdgeToPath (edge, tag) <> text tag' # translate (pos .-. P (0,0)) where pos = alerp (lsA edge) (lsB edge) 0.5 .-^ 0.5 *^ ls2Normal edge RightHanded tag' = case tag of Inside -> "I" Outside -> "O" PosBound -> "+" NegBound -> "-" prettySegmentation :: [Edge] -> [Edge] -> PP.Doc prettySegmentation a b = PP.cat $ map (\l->PP.text (show l) $$ (PP.nest 2 $ PP.vcat $ map (PP.text . show) $ segmentEdge a l) ) b main = do let segs = segmentBoth (polygonToLineSegPath c) (polygonToLineSegPath d) putStrLn "cd" print $ prettySegmentation (polygonToLineSegPath c) (polygonToLineSegPath d) putStrLn "" putStrLn "dc" print $ prettySegmentation (polygonToLineSegPath d) (polygonToLineSegPath c) --let segs = segmentEdge (polygonToLineSegPath d) (LineSeg (P (0,-8)) (P (0,8))) -- ++ segmentEdge (polygonToLineSegPath c) (LineSeg (P (0,-5)) (P (0,-3))) -- ++ segmentEdge (polygonToLineSegPath c) (LineSeg (P (0,5)) (P (0,3))) --print $ segmentEdge (polygonToLineSegPath d) (LineSeg (P (0,-8)) (P (0,8))) --print $ segmentEdge (polygonToLineSegPath c) (LineSeg (P (0,-5)) (P (0,-3))) --print $ segmentEdge (polygonToLineSegPath c) (LineSeg (P (0,5)) (P (0,3))) defaultMain $ mconcat $ map edgeToPath $ (polygonToLineSegPath c) `union` (polygonToLineSegPath d) --defaultMain $ mconcat $ map labelledTaggedEdge segs
bgamari/GGen
CSGTest.hs
gpl-3.0
3,264
13
16
1,022
1,129
599
530
80
4
{-# LANGUAGE DeriveGeneric #-} -- This type represents all messages that an Estuary client can send -- to an Estuary server via WebSockets. module Estuary.Types.Request where import Data.Time.Clock import Data.Text import GHC.Generics import Data.Aeson import Estuary.Types.EnsembleRequest import Estuary.Types.Definition data Request = BrowserInfo Text | -- text is browser userAgent field, issued at client launch (by alternateWebSocket) ClientInfo Int Int Int NominalDiffTime UTCTime | -- load animationFPS animationLoad serverLatency pingTime, issued every 5s (by alternateWebSocket) GetEnsembleList | -- issued when client enters Lobby page JoinEnsemble Text Text Text Text | -- ensemble username location password (username, location, and password can be "") RejoinEnsemble Text Text Text Text | -- for re-authenticating when websocket connections close and re-open EnsembleRequest EnsembleRequest | -- see Estuary.Types.EnsembleRequest, request "within" an ensemble LeaveEnsemble | CreateEnsemble Text Text Text Text (Maybe NominalDiffTime) | -- communityPassword ensembleName ownerPassword joinerPassword expiryTime (empty for no password) DeleteThisEnsemble Text | -- ownerPassword DeleteEnsemble Text Text -- ensembleName moderatorPassword deriving (Generic) instance ToJSON Request where toEncoding = genericToEncoding defaultOptions instance FromJSON Request
d0kt0r0/estuary
common/src/Estuary/Types/Request.hs
gpl-3.0
1,432
0
8
231
168
101
67
23
0
module Main (module Language.Lambda.Compiler) where import Language.Lambda.Compiler
justinmanley/lambda
Compiler.hs
gpl-3.0
86
0
5
9
19
13
6
2
0
{-| Module : Graphics.QML.Transient.Signal License : BSD3 Maintainer : [email protected] Stability : experimental Setup QML signals. -} {-# LANGUAGE ConstraintKinds , ExplicitForAll , FlexibleContexts , ScopedTypeVariables , TypeFamilies #-} module Graphics.QML.Transient.Signal ( module Graphics.QML.Transient.Signal , GMkSignal ) where import Graphics.QML.Transient.Internal import Graphics.QML.Transient.Internal.Signal import Graphics.QML.Transient.Internal.Types import Control.Monad.IO.Class import Control.Monad.Reader import Data.Proxy import GHC.Generics import Graphics.QML import Graphics.QML.Objects.ParamNames -- | A constraint synonym for types that can be used as an argument for a signal. type SignalArg t = ( Generic t , GMkSignal (Rep t) , (SignalParamNames (Suffix (Rep t) (IO ()))) ~ (Params (Rep t) ()) , SignalSuffix (Suffix (Rep t) (IO ())) ) signal :: forall t. SignalArg t => String -> Build (t -> Qml ()) -- ^Add a signal of with a given name, returning an action to fire it. signal name = do key <- liftIO newSignalKey let (mkParamNames, mkSuffix) = gMkSignal p addMember . defSignalNamedParams name key $ mkParamNames noNames return $ \t -> do o <- ask liftIO . mkSuffix (fireSignal key o) $ from t where p :: Proxy (Rep t) = Proxy nullarySignal :: String -> Build (Qml ()) -- ^Add a signal of with a given name that doesn't take any arguments. nullarySignal name = do key <- liftIO newSignalKey addMember $ defSignal name key return $ do o <- ask liftIO $ fireSignal key o
marcinmrotek/hsqml-transient
src/Graphics/QML/Transient/Signal.hs
gpl-3.0
1,636
0
15
349
421
221
200
49
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module CMS where import Detector.Type cms2011 :: DetectorDescription ImportList cms2011 = DetectorDescription { detectorName = "CMS2011" , detectorDescription = "CMS 2011 detector description" , detectorReference = "arXiv:xxxx.yyyy" , detectorComment = "extracted the efficiencies from the plot 3,4,5 in the reference" , detectorValidationInfo = "Validated on 2014/02" , detectorRange = RangeDescription (ImportList []) , detectorIdentification = cms2011Object , detectorSmearing = cmsSmearing } cms2011Object :: IdentificationDescription ImportList cms2011Object = IdentificationDescription { electron = ImportList [ Left (Import "Electron_PF_CMS") , Left (Import "Electron_CicSTight_CMS") , Left (Import "Electron_CicLoose_CMS") , Left (Import "Electron_WP80_CMS") , Left (Import "Electron_WP95_CMS") ] , photon = ImportList [ Left (Import "Photon_PF_CMS") , Left (Import "Photon_Tight_CMS") , Left (Import "Photon_Loose_CMS") ] , bJet = ImportList [ Left (Import "BJet_TCHEL_CMS") , Left (Import "BJet_SSVHPT_CMS") , Left (Import "BJet_SSVHEM_CMS") ] , muon = ImportList [ Left (Import "Muon_S_CMS") , Left (Import "Muon_P_CMS") , Left (Import "Muon_T_CMS") ] , jet = ImportList [ Left (Import "Jet_PF_CMS") , Left (Import "Jet_Calo_CMS") ] , tau = ImportList [ Left (Import "Tau_TaNCL_CMS") , Left (Import "Tau_TaNCM_CMS") , Left (Import "Tau_TaNCT_CMS") , Left (Import "Tau_TaHPSL_CMS") , Left (Import "Tau_TaHPSM_CMS") , Left (Import "Tau_TaHPST_CMS") , Left (Import "Tau_TaTCT_CMS") ] , track = Just (ImportList [Left (Import "Track_CMS")]) , ptThresholds = ImportList [ Left (Import "CMS_PTThreshold") ] } cmsSmearing :: SmearingDescription ImportList cmsSmearing = SmearingDescription { smearElectron = ImportList [ Left (Import "Smear_Electron_CMS") ] , smearPhoton = ImportList [ Left (Import "Smear_Photon_CMS") ] , smearMuon = ImportList [ Left (Import "Smear_Muon_CMS") ] , smearJet = ImportList [ Left (Import "Smear_TopoJet_CMS") ] , smearTrack = ImportList [ Left (Import "Smear_Track_CMS") ] , smearTau = ImportList [ Left (Import "Smear_Tau_CMS") ] , smearMET = ImportList [ Left (Import "Smear_MissingET_CMS") ] } cmsBTagTCHEL :: BJetEffData cmsBTagTCHEL = BJetEffData { bJetName = "BJet_TCHEL_CMS" , bJetMetaInfo = MetaInfo { tag = "CMS" , description = "CMS BJet Tagging TCHEL" , comment = "table X" , reference = "arXiv:xxxx.yyyy" } , bJetEfficiency = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 100.0, 120.0, 240.0 ] , etaBins = [ 0.0, 1.2, 2.4 ] , grid = GridConst { gridConst = 0.7 } } , bJetRejection = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0 ] , etaBins = [ 0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4 ] , grid = GridConst { gridConst = 100.0 } } } cmsBTagSSVHPT :: BJetEffData cmsBTagSSVHPT = BJetEffData { bJetName = "BJet_SSVHPT_CMS" , bJetMetaInfo = MetaInfo { tag = "CMS" , description = "CMS BJet Tagging SSVHPT" , comment = "table X" , reference = "arXiv:xxxx.yyyy" } , bJetEfficiency = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 100.0, 120.0, 240.0 ] , etaBins = [ 0.0, 1.2, 2.4 ] , grid = GridConst { gridConst = 0.5 } } , bJetRejection = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0 ] , etaBins = [ 0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4 ] , grid = GridConst { gridConst = 100.0 } } } cmsBTagSSVHEM :: BJetEffData cmsBTagSSVHEM = BJetEffData { bJetName = "BJet_SSVHEM_CMS" , bJetMetaInfo = MetaInfo { tag = "CMS" , description = "CMS BJet Tagging SSVHEM" , comment = "table X" , reference = "arXiv:xxxx.yyyy" } , bJetEfficiency = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 100.0, 120.0, 240.0 ] , etaBins = [ 0.0, 1.2, 2.4 ] , grid = GridConst { gridConst = 0.825 } } , bJetRejection = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0 ] , etaBins = [ 0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4 ] , grid = GridConst { gridConst = 10.0 } } } cmsMuonS :: MuonEffData cmsMuonS = MuonEffData { muonName = "Muon_S_CMS" , muonMetaInfo = MetaInfo { tag = "CMS" , description = "CMS S Muon" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , muonEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 7.0, 9.0, 11.0, 14.0, 17.0, 20.0, 30.0, 40.0, 60.0, 100.0 ] , etaBins = [ -2.4, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.4 ] , grid = GridConst { gridConst = 1.0 } } } cmsMuonP :: MuonEffData cmsMuonP = MuonEffData { muonName = "Muon_P_CMS" , muonMetaInfo = MetaInfo { tag = "CMS" , description = "CMS P Muon" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , muonEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 7.0, 9.0, 11.0, 14.0, 17.0, 20.0, 30.0, 40.0, 60.0, 100.0 ] , etaBins = [ -2.4, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.4 ] , grid = GridConst { gridConst = 1.0 } } } cmsMuonT :: MuonEffData cmsMuonT = MuonEffData { muonName = "Muon_T_CMS" , muonMetaInfo = MetaInfo { tag = "CMS" , description = "CMS T Muon" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , muonEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 7.0, 9.0, 11.0, 14.0, 17.0, 20.0, 30.0, 40.0, 60.0, 100.0 ] , etaBins = [ -2.4, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.4 ] , grid = GridConst { gridConst = 1.0 } } } cmsElePF :: ElectronEffData cmsElePF = ElectronEffData { eleName = "Electron_PF_CMS" , eleMetaInfo = MetaInfo { tag = "CMS" , description = "electron PF CMS" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , eleEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 15.0, 17.5, 20.0, 30.0, 40.0, 50.0, 150.0 ] , etaBins = [ -2.5, -1.56, -1.442, 0.0, 1.442, 1.56, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsEleCicSTight :: ElectronEffData cmsEleCicSTight = ElectronEffData { eleName = "Electron_CicSTight_CMS" , eleMetaInfo = MetaInfo { tag = "CMS" , description = "electron CicSTight CMS" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , eleEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 15.0, 17.5, 20.0, 30.0, 40.0, 50.0, 150.0 ] , etaBins = [ -2.5, -1.56, -1.442, 0.0, 1.442, 1.56, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsEleCicLoose :: ElectronEffData cmsEleCicLoose = ElectronEffData { eleName = "Electron_CicLoose_CMS" , eleMetaInfo = MetaInfo { tag = "CMS" , description = "electron CicLoose CMS" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , eleEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 15.0, 17.5, 20.0, 30.0, 40.0, 50.0, 150.0 ] , etaBins = [ -2.5, -1.56, -1.442, 0.0, 1.442, 1.56, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsEleWP80 :: ElectronEffData cmsEleWP80 = ElectronEffData { eleName = "Electron_WP80_CMS" , eleMetaInfo = MetaInfo { tag = "CMS" , description = "electron WP80 CMS" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , eleEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 15.0, 17.5, 20.0, 30.0, 40.0, 50.0, 150.0 ] , etaBins = [ -2.5, -1.56, -1.442, 0.0, 1.442, 1.56, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsEleWP95 :: ElectronEffData cmsEleWP95 = ElectronEffData { eleName = "Electron_WP95_CMS" , eleMetaInfo = MetaInfo { tag = "CMS" , description = "electron WP95 CMS" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , eleEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 15.0, 17.5, 20.0, 30.0, 40.0, 50.0, 150.0 ] , etaBins = [ -2.5, -1.56, -1.442, 0.0, 1.442, 1.56, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsPhoPF :: PhotonEffData cmsPhoPF = PhotonEffData { phoName = "Photon_PF_CMS" , phoMetaInfo = MetaInfo { tag = "CMS" , description = "Photon PF CMS" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , phoEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 20.0, 35.0, 45.0, 100.0 ] , etaBins = [ -2.5, -1.56, -1.442, 0.0, 1.442, 1.56, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsPhoTight :: PhotonEffData cmsPhoTight = PhotonEffData { phoName = "Photon_Tight_CMS" , phoMetaInfo = MetaInfo { tag = "CMS" , description = "Photon Tight CMS" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , phoEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 20.0, 35.0, 45.0, 100.0 ] , etaBins = [ -2.5, -1.56, -1.442, 0.0, 1.442, 1.56, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsPhoLoose :: PhotonEffData cmsPhoLoose = PhotonEffData { phoName = "Photon_Loose_CMS" , phoMetaInfo = MetaInfo { tag = "CMS" , description = "Photon Loose CMS" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , phoEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 20.0, 35.0, 45.0, 100.0 ] , etaBins = [ -2.5, -1.56, -1.442, 0.0, 1.442, 1.56, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsTrack :: TrackEffData cmsTrack = TrackEffData { trackName = "Track_CMS" , trackMetaInfo = MetaInfo { tag = "CMS" , description = "Track CMS" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , trackEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 4.0, 6.0, 8.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0 ] , etaBins = [ -2.5, -1.56, -1.442, 0.0, 1.442, 1.56, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsTauTaNCL :: TauEffData cmsTauTaNCL = TauEffData { tauName = "Tau_TaNCL_CMS" , tauMetaInfo = MetaInfo { tag = "CMS" , description = "CMS Tau TaNC Loose" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , tauTagMethod = "TaNCL" , tauEfficiency = TauCombined { tauCombEff = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100.0 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } , tauCombRej = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } } cmsTauTaNCM :: TauEffData cmsTauTaNCM = TauEffData { tauName = "Tau_TaNCM_CMS" , tauMetaInfo = MetaInfo { tag = "CMS" , description = "CMS Tau TaNC Medium" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , tauTagMethod = "TaNCM" , tauEfficiency = TauCombined { tauCombEff = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100.0 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } , tauCombRej = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } } cmsTauTaNCT :: TauEffData cmsTauTaNCT = TauEffData { tauName = "Tau_TaNCT_CMS" , tauMetaInfo = MetaInfo { tag = "CMS" , description = "CMS Tau TaNC Tight" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , tauTagMethod = "TaNCT" , tauEfficiency = TauCombined { tauCombEff = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100.0 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } , tauCombRej = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } } cmsTauHPSL :: TauEffData cmsTauHPSL = TauEffData { tauName = "Tau_TaHPSL_CMS" , tauMetaInfo = MetaInfo { tag = "CMS" , description = "CMS Tau HPS Loose" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , tauTagMethod = "HPSL" , tauEfficiency = TauCombined { tauCombEff = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100.0 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } , tauCombRej = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } } cmsTauHPSM :: TauEffData cmsTauHPSM = TauEffData { tauName = "Tau_TaHPSM_CMS" , tauMetaInfo = MetaInfo { tag = "CMS" , description = "CMS Tau HPS Medium" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , tauTagMethod = "HPSM" , tauEfficiency = TauCombined { tauCombEff = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100.0 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } , tauCombRej = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } } cmsTauHPST :: TauEffData cmsTauHPST = TauEffData { tauName = "Tau_TaHPST_CMS" , tauMetaInfo = MetaInfo { tag = "CMS" , description = "CMS Tau HPS Tight" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , tauTagMethod = "HPST" , tauEfficiency = TauCombined { tauCombEff = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100.0 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } , tauCombRej = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } } cmsTauTCT :: TauEffData cmsTauTCT = TauEffData { tauName = "Tau_TaTCT_CMS" , tauMetaInfo = MetaInfo { tag = "CMS" , description = "CMS Tau TC Tight" , comment = "table" , reference = "arXiv:xxxx.yyyy" } , tauTagMethod = "TCT" , tauEfficiency = TauCombined { tauCombEff = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100.0 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } , tauCombRej = PTEtaGrid { isEtaSymmetric = True , ptBins = [ 15.0, 17.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 70.0, 100 ] , etaBins = [ 0.0, 1.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } } cmsJetPF :: JetEffData cmsJetPF = JetEffData { jetName = "Jet_PF_CMS" , jetMetaInfo = MetaInfo { tag = "CMS" , description = "CMS PF Jet" , comment = "table" , reference = "PFT-09-001-pas" } , jetEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 80.0, 100.0 ] , etaBins = [ -2.5, -1.5, 0.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsJetCalo :: JetEffData cmsJetCalo = JetEffData { jetName = "Jet_Calo_CMS" , jetMetaInfo = MetaInfo { tag = "CMS" , description = "CMS Calorimeter Jet" , comment = "table" , reference = "PFT-09-001-pas" } , jetEfficiency = PTEtaGrid { isEtaSymmetric = False , ptBins = [ 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 50.0, 60.0, 80.0, 100.0 ] , etaBins = [ -2.5, -1.5, 0.0, 1.5, 2.5 ] , grid = GridConst { gridConst = 1.0 } } } cmsPTThresholds :: PTThresholds cmsPTThresholds = PTThresholds { pTThreName = "CMS_PTThreshold" , muPTMin = 20.0 , elePTMin = 5.0 , phoPTMin = 20.0 , jetPTMin = 20.0 , bJetPTMin = 20.0 , trkPTMin = 0.5 , tauPTMin = 5.0 } cmsSmearElectron :: SmearData TElectron cmsSmearElectron = SmearData "Smear_Electron_CMS" MetaInfo { tag = "CMS", description = "electron", comment = "table", reference = "XXX" } PTEtaInterpolation { isEtaSymmetric = True, interpol = IPConstant 1.0 } cmsSmearPhoton :: SmearData TPhoton cmsSmearPhoton = SmearData "Smear_Photon_CMS" MetaInfo { tag = "CMS", description = "photon", comment = "table", reference = "XXX" } PTEtaInterpolation { isEtaSymmetric = True, interpol = IPConstant 1.0 } cmsSmearMuon :: SmearData TMuon cmsSmearMuon = SmearData "Smear_Muon_CMS" MetaInfo { tag = "CMS", description = "muon", comment = "table", reference = "XXX" } PTEtaInterpolation { isEtaSymmetric = True, interpol = IPConstant 1.0 } cmsSmearTopoJet :: SmearData TJet cmsSmearTopoJet = SmearData "Smear_TopoJet_CMS" MetaInfo { tag = "CMS", description = "topojet", comment = "table", reference = "XXX" } PTEtaInterpolation { isEtaSymmetric = True, interpol = IPConstant 1.0 } cmsSmearTrack :: SmearData TTrack cmsSmearTrack = SmearData "Smear_Track_CMS" MetaInfo { tag = "CMS", description = "track", comment = "table", reference = "XXX" } PTEtaInterpolation { isEtaSymmetric = True, interpol = IPConstant 1.0 } cmsSmearTau :: SmearData TTau cmsSmearTau = SmearData "Smear_Tau_CMS" MetaInfo { tag = "CMS", description = "tau", comment = "table", reference = "XXX" } PTEtaInterpolation { isEtaSymmetric = True, interpol = IPConstant 1.0 } cmsSmearMET :: SmearData TMET cmsSmearMET = SmearData "Smear_MissingET_CMS" MetaInfo { tag = "CMS", description = "missingET", comment = "table", reference = "XXX" } PTEtaInterpolation { isEtaSymmetric = True, interpol = IPConstant 1.0 }
wavewave/detector-yaml
lib/CMS.hs
gpl-3.0
20,557
0
13
6,474
5,613
3,546
2,067
471
1
{-# LANGUAGE OverloadedStrings #-} {- NICTA t3as NER Client Copyright 2014 NICTA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.html>. -} import Nicta.Ner.Client import Control.Monad (liftM) import Data.ByteString (ByteString, empty) import Data.Maybe (catMaybes) import Data.Version (showVersion) import qualified Data.Text.IO as TIO (readFile) import qualified Data.Text as T (pack) import Data.Text.Encoding as TE (encodeUtf8) import Paths_nicta_ner_client_hs (version) import System.Console.GetOpt (ArgOrder (Permute), ArgDescr (NoArg, ReqArg) , OptDescr (Option), getOpt, usageInfo) import System.Environment (getProgName, getArgs) import System.Exit (exitSuccess) defaultOpts :: Opts defaultOpts = Opts { usage = False , url = "http://ner.t3as.org/nicta-ner-web/rest/v1.0/ner" , txt = empty } cmdLineArgs :: [OptDescr (Opts -> Opts)] cmdLineArgs = [ Option "h" ["help"] (NoArg (\opts -> opts {usage = True})) "Show this help message." , Option [] ["url"] (ReqArg (\arg opts -> opts {url = arg}) "<webservice url>") ("The full URL to the NER web service. Default: " ++ url defaultOpts) , Option [] ["txt"] (ReqArg (\arg opts -> opts {txt = (TE.encodeUtf8 . T.pack) arg}) "<text to analyse>") "The text to perform NER analysis on." ] main :: IO () main = do args <- getArgs progName <- getProgName (opts, files) <- parseArgs progName args if usage opts || (txt opts == empty && null files) then do putStrLn $ usageInfo (header progName) cmdLineArgs exitSuccess else do results <- sequence $ runWith opts files mapM_ (putStrLn . responseToString) (catMaybes results) parseArgs :: String -> [String] -> IO (Opts, [String]) parseArgs progName args = case getOpt Permute cmdLineArgs args of (opts, files, []) -> return (foldl (flip id) defaultOpts opts, files) (_, _, errMsgs) -> error $ concat errMsgs ++ usageInfo (header progName) cmdLineArgs header :: String -> String header progName = "\nVersion " ++ showVersion version ++ "\n\n" ++ "Usage: " ++ progName ++ " [OPTIONS...] [FILES...]\n\n" ++ "Please pass either the --txt option, or some files with text to " ++ "analyse - do not pass both.\n" runWith :: Opts -> [String] -> [IO (Maybe NerResponse)] runWith opts files = do let ner = performNer $ url opts t = txt opts if t /= empty then [ner t] else map (>>= ner) $ readToLbs files readToLbs :: [String] -> [IO ByteString] readToLbs [] = [] -- is it really necessary to encode to UTF8? readToLbs files = map (liftM encodeUtf8 . TIO.readFile) files
NICTA/nicta-ner
nicta-ner-client-hs/src-cmdline/nicta-ner-client-hs.hs
gpl-3.0
3,462
0
16
910
826
452
374
63
2
module WinShop.Types ( WSRequest ) where import qualified Network.HTTP as H type WSRequest = H.Request String
RayRacine/winshop
src/WinShop/Types.hs
gpl-3.0
114
0
6
20
30
19
11
4
0
{-# LANGUAGE OverloadedStrings #-} module Users.ControllerSpec (spec) where import Test.Hspec import Test.Hspec.Fn import Common import Users.Model spec :: Spec spec = fnTests $ do describe "/users" $ do it "should list all the users" $ do get "/users" >>= should200 describe "/users/create" $ do it "should create a new user" $ do post "/users/create" [("username", "new") ,("email", "[email protected]") ,("password", "pass") ,("password-confirmation", "pass")] >>= should200 [user] <- eval (\ctxt -> getUsers ctxt) userEmail user `shouldEqual` "[email protected]" it "should not create a new user if password doesn't match" $ do post "/users/create" [("username", "new") ,("email", "[email protected]") ,("password", "pass") ,("password-confirmation", "random")] >>= should200 eval (\ctxt -> getUsers ctxt) >>= shouldEqual [] it "should not create a new user if email is invalid" $ do post "/users/create" [("username", "new") ,("email", "newtest.com") ,("password", "pass") ,("password-confirmation", "random")] >>= should200 eval (\ctxt -> getUsers ctxt) >>= shouldEqual []
huggablemonad/smooch
app/tests/Users/ControllerSpec.hs
gpl-3.0
1,462
0
18
539
347
185
162
36
1
{-# LANGUAGE DeriveDataTypeable #-} import Data.Ratio import Data.List import XMonad -- import XMonad.Config.Desktop --import XMonad.Config.Gnome import XMonad.Config.Kde import XMonad.Config.Xfce import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Hooks.FadeInactive import XMonad.Util.Run import XMonad.Util.EZConfig import XMonad.Util.Font import XMonad.Layout import XMonad.Layout.Tabbed import XMonad.Layout.PerWorkspace import XMonad.Layout.LayoutHints (layoutHints) -- GIMP stuff import XMonad.Layout.IM as IM import XMonad.Layout.Reflect import XMonad.Layout.TrackFloating -- End GIMP stuff import XMonad.Actions.CycleWS import XMonad.Actions.OnScreen import qualified XMonad.StackSet as W import qualified Data.Map as M import System.IO import qualified DBus as D import qualified DBus.Client as D import qualified Codec.Binary.UTF8.String as UTF8 import Graphics.X11.ExtraTypes.XF86 import XMonad.Util.WorkspaceCompare import XMonad.Actions.WorkspaceNames hiding (workspaceNamesPP) import Control.Monad (liftM) import XMonad.Actions.SpawnOn import XMonad.Prompt import XMonad.Prompt.Window import XMonad.Operations import XMonad.Hooks.EwmhDesktops import XMonad.Hooks.SetWMName import XMonad.Hooks.ManageHelpers import XMonad.Util.Loggers import XMonad.Util.Paste import XMonad.Actions.WindowGo -- DynamicWorkspaces Stuff import XMonad.Actions.DynamicWorkspaces as DW import qualified XMonad.Util.ExtensibleState as XS import Control.Applicative filterWorkspaces :: [WorkspaceId] -> [WindowSpace] -> [WindowSpace] filterWorkspaces ws = filter (\(W.Workspace tag _ _) -> tag `elem` ws) -- xScreen are the type classes which hold the workspace name lists newtype LeftScreen = LeftScreen {getLeftScreen :: [WorkspaceId]} deriving (Typeable,Read,Show) instance ExtensionClass LeftScreen where initialValue = LeftScreen [] extensionType = PersistentExtension newtype RightScreen = RightScreen {getRightScreen :: [WorkspaceId]} deriving (Typeable,Read,Show) instance ExtensionClass RightScreen where initialValue = RightScreen [] extensionType = PersistentExtension -- End DynamicWorkspaces code (keybindings are below) -- -- get these with xprop myManageHook = composeAll [ isDialog --> doFloat , className =? "Gnome-dictionary" --> doFloat , className =? "Xfce4-dict" --> doFloat , className =? "Last.fm" --> doFloat , className =? "Xmessage" --> doFloat , className =? "Audacious" --> doFloat --, className =? "Gimp" --> doFloat , className =? "Skype" --> doFloat , className =? "Keepassx" --> doFloat , className =? "Kcalc" --> doFloat , className =? "Clementine" --> doFloat , className =? "SpiderOak" --> doFloat , className =? "Pavucontrol" --> doFloat {- The following sets doFloat on the Orage window (as above) But also ensures that it appears only on the left screen (screen 0). (screenWorkspace 0) returns X (Maybe WorkspaceId), and the liftX function lifts an X action to a Query (which is Maybe WorkspaceId) and the next lines return the workspace (if not empty), or do nothing if (Maybe WorkspaceId) -> Nothing. idHook maps to mempty, which means do nothing -} , className =? "Orage" --> doFloat <+> do ws <- liftX (screenWorkspace 0) case ws of Just w -> doShift w Nothing -> idHook -- end Orage window stuff -- Weather report stuff , className =? "Wrapper" --> doFloat <+> do ws <- liftX (screenWorkspace 0) case ws of Just w -> doShift w Nothing -> idHook -- end Weather Report window stuff , className =? "Plasma-desktop" --> doFloat <+> do ws <- liftX (screenWorkspace 0) case ws of Just w -> doShift w Nothing -> idHook -- end Plasma desktop stuff , className =? "Xfce4-notifyd" --> doIgnore ] shiftInsert w = let translatedProgs = ["Chromium", "Chrome"] in do c <- runQuery className w; let toTranslate = any (== c) translatedProgs if toTranslate then spawn ("CLIP=$(xclip -out -selection clipboard); xclip -out" ++ " | xclip -in -selection clipboard; xdotool key --clearmodifiers --window " ++ show w ++ " ctrl+v; echo -n $CLIP | xclip -in -selection clipboard") else sendKey shiftMask xK_Insert layoutH = layoutHints -- $ onWorkspace "5:" (Mirror tiled2 -- ||| tiled ||| Full) -- $ onWorkspaces ["1:wkbr","2:wksh"] (Full -- ||| tiled ||| Mirror tiled) $ tiled ||| Mirror tiled ||| Full where tiled = Tall 1 (3 % 100) (1/2) --tiled2 = Tall 1 (3 % 100) (5 % 9) fadeHook = fadeInactiveLogHook fadeAmount where fadeAmount = 0.2 makeLauncher yargs run exec close = concat ["exe=`yeganesh ", yargs, "` && ", run, " ", exec, "$exe", close] launcher = makeLauncher "-x -- -nf grey -nb black" "eval" "\"exec " "\"" main = do -- xmproc <- spawnPipe "xmobar" -- xmonad $ gnomeConfig { dbus <- D.connectSession getWellKnownName dbus; -- xmonad $ kde4Config { xmonad $ xfceConfig { -- workspaces = slotWksp workspaces = ["sh","sb","of","wc","ws","wb","hng"] -- workspaces = [ "dee", "dum" ] , terminal = myTerminal -- Goodbye, my sweet, sweet, sloppy focus -- , focusFollowsMouse = False -- Hello again, my sweet, sweet, sloppy focus! , focusFollowsMouse = True , manageHook = manageDocks <+> myManageHook -- <+> manageHook defaultConfig , layoutHook = avoidStruts $ onWorkspace "gimp" gimp $ layoutH , logHook = dynamicLogWithPP (ppL dbus) >> dynamicLogWithPP (ppR dbus) >> fadeHook , borderWidth = 1 , normalBorderColor = "#333333" , focusedBorderColor = "#CCCC00" , modMask = winKey , startupHook = startupHook xfceConfig >> setWMName "L3GD" --, startupHook = do -- setWMName "LG3D" } `additionalKeys` myKeys where --{ gimp = IM.withIM 0.11 (Role "gimp-toolbox") $ reflectHoriz $ IM.withIM 0.15 (Role "gimp-dock") Full --, vbox = --} getWellKnownName :: D.Client -> IO() getWellKnownName dbus = do D.requestName dbus (D.busName_ "org.xmonad.Log") [D.nameAllowReplacement, D.nameReplaceExisting, D.nameDoNotQueue] return() outputThroughDBusR :: D.Client -> String -> IO() outputThroughDBusR dbus str = do let signal = (D.signal (D.objectPath_ "/org/xmonad/Log") (D.interfaceName_ "org.xmonad.Log") (D.memberName_ "Update")) { D.signalBody = [D.toVariant ("<span font=\"Terminus Bold 9\">" ++ (UTF8.decodeString str) ++ "</span>")] } D.emit dbus signal outputThroughDBusL :: D.Client -> String -> IO() outputThroughDBusL dbus str = do let signal = (D.signal (D.objectPath_ "/org/xmonad/LogL") (D.interfaceName_ "org.xmonad.LogL") (D.memberName_ "Update")) { D.signalBody = [D.toVariant ("<span font=\"Terminus Bold 9\">" ++ (UTF8.decodeString str) ++ "</span>")] } D.emit dbus signal pangoColor :: String -> String -> String pangoColor fg = wrap left right where left = "<span foreground=\"" ++ fg ++ "\">" right = "</span>" pangoSanitize :: String -> String pangoSanitize = foldr sanitize "" where sanitize '>' acc = "&gt;" ++ acc sanitize '<' acc = "&lt;" ++ acc sanitize '\"' acc = "" ++ acc sanitize '&' acc = "&amp;" ++ acc sanitize x acc = x:acc {--- Now here's some fuckin' Voodoo Magic filterOutLeft :: [WindowSpace] -> [WindowSpace] filterOutLeft = filter (\(W.Workspace tag _ _) -> tag `elem` rightWksp) filterOutRight :: [WindowSpace] -> [WindowSpace] filterOutRight = filter (\(W.Workspace tag _ _) -> tag `elem` leftWksp) -- End Voodoo -} ppR dbus = defaultPP { ppOutput = outputThroughDBusR dbus , ppCurrent = pangoColor "yellow" . wrap "[" "]" . pangoSanitize , ppVisible = pangoColor "cyan" . wrap "(" ")" . pangoSanitize , ppTitle = pangoColor "green" . shorten 50. pangoSanitize , ppUrgent = pangoColor "red" , ppSep = " " -- , ppSort = (.) <$> XS.gets (filterWorkspaces . getRightScreen) <*> getSortByTag , ppSort = (.) <$> XS.gets (filterWorkspaces . getRightScreen) <*> getSortByIndex --, ppSort = (.) <$> XS.gets (filterWorkspaces . getRightScreen) <*> getSortByXineramaPhysicalRule --, ppSort = (.) <$> XS.gets (filterWorkspaces . getRightScreen) <*> getSortByXineramaRule --, ppSort = fmap (.filterOutLeft) getSortByTag , ppHiddenNoWindows = const "" , ppHidden = pangoColor "gray" } ppL dbus = defaultPP { ppOutput = outputThroughDBusL dbus , ppCurrent = pangoColor "yellow" . wrap "[" "]" . pangoSanitize , ppVisible = pangoColor "cyan" . wrap "(" ")" . pangoSanitize , ppTitle = pangoColor "maroon" . shorten 50. pangoSanitize , ppUrgent = pangoColor "red" , ppSep = " " --, ppSort = fmap (.filterOutRight) getSortByTag -- , ppSort = (.) <$> XS.gets (filterWorkspaces . getLeftScreen) <*> getSortByTag , ppSort = (.) <$> XS.gets (filterWorkspaces . getLeftScreen) <*> getSortByIndex --, ppSort = (.) <$> XS.gets (filterWorkspaces . getLeftScreen) <*> getSortByXineramaPhysicalRule --, ppSort = (.) <$> XS.gets (filterWorkspaces . getLeftScreen) <*> getSortByXineramaRule , ppHidden = pangoColor "gray" , ppHiddenNoWindows = const "" -- , ppExtras = [logCmd "qdbus org.mpris.clementine /Player org.freedesktop.MediaPlayer.GetMetadata | grep -E 'performer|title' | awk -F':' '{print $2}' | sed 'N;s/\n/ -/; s/^[[:space:]]*//'"] , ppExtras = [pangoColor "orange" `onLogger` logCmd "~/bin/now_playing"] --logCmd "qdbus org.mpris.clementine /Player org.freedesktop.MediaPlayer.GetMetadata | grep -E 'performer|title' | awk -F':' '{print $2}' | sed 'N;s/\n/ -/; s/^[[:space:]]*//'"] --, ppExtras = onLogger $ pangoColor "orange" . logCmd "qdbus org.mpris.clementine /Player org.freedesktop.MediaPlayer.GetMetadata | grep -E 'performer|title' | awk -F':' '{print $2}' | sed 'N;s/\n/ -/; s/^[[:space:]]*//'" -- logCmd "mpc | awk -F: 'NR > 1 { exit }; { print $NF }'"] -- , ppExtras = fixedWidthL AlignRight " " 99 <$> pangoColor "orange" <$> logCmd "qdbus org.mpris.clementine /Player org.freedesktop.MediaPlayer.GetMetadata | grep -E 'performer|title' | awk -F':' '{print $2}' | sed 'N;s/\n/ -/; s/^[[:space:]]*//'" -- logCmd "mpc | awk -F: 'NR > 1 { exit }; { print $NF }'" --, ppExtras = [Just `fmap` runProcessWithInput "/bin/bash" [] -- ("mpc | awk -F: 'NR > 1 { exit }; { print $NF }'")] --("qdbus org.mpris.clementine /Player org.freedesktop.MediaPlayer.GetMetadata | grep -E 'performer|title' | awk -F':' '{print $2}' | sed 'N;s/\\n/ -/; s/^\s*//'")] --("qdbus org.mpris.clementine /Player org.freedesktop.MediaPlayer.GetMetadata | grep -E 'performer|title' | awk -F':' '{print $2}' | sed 'N;s/\n/ -/; s/^[[:space:]]*//'")] } winKey :: KeyMask winKey = mod4Mask lAlt :: KeyMask lAlt = mod1Mask {-Multiline comment for reference winKey :: KeyMask winKey :: KeyMask-} --myTerminal :: String --myTerminal = "konsole" myTerminal = "urxvtc -cd ~" altTerminal = "urxvtc -cd ~ -name altUrxvt" --myTerminal = "gnome-terminal" --myTerminal = "terminator" {-slotWksp = ["1:main", "2:jobs", "3:is660","4:office","5:sysadmin","6:irc","7:digium", "8:vm","9:dump","0:music","F1:man","F2:jobs","F3:isovr","F4:offovr","F5:sysovr","F6:ircovr","F7:dgmovr","F8:vmovr","F9:dmpovr","F10:musovr"] leftWksp = ["01:main","02:jobs","03:is660","04:office","05:sysadmin","06:irc","07:digium","08:vm","09:dump","10:music"] rightWksp = [ "F1:man" , "F2:jobs" , "F3:isovr" , "F4:offovr" , "F5:sysovr" , "F6:ircovr" , "F7:dgmovr" , "F8:vmovr" , "F9:dmpovr" , "F10:musovr" ]-} {- Many of the key combinations below match or are analogs of key combinations - in Windows. This is to keep the amount of mental context switching to a - minimum. - -} myKeys = [ --((winKey , xK_l), spawnHere "xscreensaver-command --lock && sleep 3 && xset dpms force off") ((winKey , xK_l), spawnHere "dm-tool lock && sleep 3 && xset dpms force off") -- ((winKey , xK_l), spawnHere "xscreensaver-command --lock") -- ((winKey , xK_l), spawnHere "qdbus org.kde.krunner /ScreenSaver Lock") , ((winKey , xK_Return), do windows (viewOnScreen 0 "sh") ifWindows (resource =? "urxvt") (mapM_ focus) (spawnHere myTerminal)) , ((controlMask .|. lAlt, xK_BackSpace), (spawnHere "xfdesktop --quit")) , ((controlMask .|. shiftMask, xK_Return), do windows (viewOnScreen 1 "ws") ifWindows (resource =? "altUrxvt") (mapM_ focus) (spawnHere altTerminal)) , ((winKey , xK_v), do windows (viewOnScreen 1 "ws") ifWindows (className =? "Gvim") (mapM_ focus) (spawnHere "gvim")) , ((lAlt , xK_v), spawnHere "xfce4-popup-clipman") --, ((winKey , xK_x), windowPromptGoto dXPConfig) , ((winKey .|. shiftMask, xK_x), windowPromptBring dXPConfig) --, ((winKey .|. shiftMask, xK_Return), windows W.swapMaster) --, ((winKey .|. shiftMask, xK_Return), spawnHere myTerminal) , ((winKey , xK_b), sendMessage ToggleStruts) --, ((winKey , xK_g), spawnHere "chromium --allow-outdated-plugins --purge-memory-button ") --, ((winKey , xK_g), ifWindows (className =? "Google-chrome") (mapM_ focus) (spawnHere "google-chrome")) , ((winKey , xK_g), do windows (viewOnScreen 1 "sb") ifWindows (className =? "chromium") (mapM_ focus) (spawnHere "chromium")) --ifWindows (className =? "Chromium-browser") (mapM_ focus) (spawnHere "chromium-browser")) --, ((winKey , xK_r), do -- windows (viewOnScreen 1 "wb") -- ifWindows (className =? "Google-chrome-stable") (mapM_ focus) (spawnHere "google-chrome-stable")) --ifWindows (className =? "Google-chrome") (mapM_ focus) (spawnHere "chromium --user-data-directory=~/work/avoxi/chromium")) --, ((winKey , xK_g), spawnHere "google-chrome --purge-memory-button ") --, ((winKey , xK_i), spawnHere "iceweasel") --, ((winKey , xK_i), spawnHere "clementine") , ((winKey , xK_i), ifWindows (className =? "Clementine") (mapM_ killWindow) (spawnHere "clementine")) --, ((winKey , xK_d), spawnHere "xfce4-dict") , ((winKey , xK_d), ifWindows (className =? "Xfce4-dict") (mapM_ killWindow) (spawnHere "xfce4-dict")) , ((winKey , xK_f), spawnHere (myTerminal ++ " -e vifm . ~")) --, ((winKey , xK_f), spawnHere ("export SHELL=/bin/bash && " ++ myTerminal ++ " -e mc")) --, ((winKey , xK_e), spawnHere ("export SHELL=/bin/bash && " ++ myTerminal ++ " -e mc")) -- key stroke matches Win+E (from Win7) , ((winKey , xK_o), do --windows (viewOnScreen 0 "of") ifWindows (fmap("libreoffice" `isPrefixOf`) className) (mapM_ focus) (spawnHere "libreoffice")) -- , ((winKey , xK_o), do -- windows (viewOnScreen 1 "rbank") -- ifWindows (className =? "Opera") (mapM_ focus) (spawnHere "opera")) -- , ((winKey .|. controlMask , xK_a), spawnHere "/home/trey/launchers/airdroid.desktop") -- , ((winKey , xK_s), do -- windows (viewOnScreen 1 "hng") -- ifWindows (className =? "Skype") (mapM_ focus) (spawnHere "skype")) , ((winKey , xK_s), ifWindows (className =? "Pavucontrol") (mapM_ killWindow) (spawnHere "pavucontrol")) , ((winKey , xK_c), kill) --, ((winKey , xK_m), windows W.focusMaster) , ((winKey , xK_comma), sendMessage (IncMasterN 1)) , ((winKey , xK_period), sendMessage (IncMasterN (-1))) , ((winKey , xK_j), windows W.focusDown) -- explicitly setting the default , ((winKey .|. controlMask, xK_j), windows W.swapDown) -- explicitly setting the default , ((winKey , xK_k), windows W.focusUp) -- explicitly setting the default , ((winKey .|. controlMask, xK_k), windows W.swapUp) -- explicitly setting the default , ((lAlt , xK_Tab), windows W.focusDown) -- replicating MS Windows task switcher behavior , ((lAlt .|. shiftMask, xK_Tab), windows W.focusUp) -- replicating MS Windows task switcher behavior , ((winKey .|. controlMask, xK_Return), windows W.swapMaster) --, ((winKey .|. shiftMask, xK_space), setLayout $ XMonad.layoutHook conf) -- the default, commented here for documentation and posterity , ((winKey , xK_p), spawnHere launcher) , ((winKey .|. shiftMask, xK_p), spawnHere "gmrun") --, ((winKey .|. controlMask , xK_d), spawn ("sleep 1 && date +%F | tr -d '\n' | ~/bin/genxmacro | xmacroplay -d 0.1 $DISPLAY")) --, ((controlMask .|. shiftMask , xK_d), spawn ("sleep 1 && date '+%F %T %p: ' | tr -d '\n' | ~/bin/genxmacro | xmacroplay -d 0.1 $DISPLAY")) --, ((winKey .|. controlMask , xK_k), spawn ("sleep 1 && cat ~/.macros/code.macro | xmacroplay -d 0.1 $DISPLAY")) , ((shiftMask, xK_Insert), withFocused shiftInsert) --, ((controlMask, xK_n), raiseMaybe (spawnHere myTerminal) (className =? "URxvt")) , ((winKey , xK_Print), spawnHere "xfce4-screenshooter") , ((winKey , xK_Left), prevWS) , ((winKey , xK_Right), nextWS) , ((winKey , xK_Up), spawnHere "skippy-xd") --, ((0, xF86XK_Calculator), spawnHere "/home/trey/bin/calc") --, ((0, xF86XK_Calculator), ifWindows (className =? "Gcalctool") (mapM_ killWindow) (spawnHere "gcalctool")) , ((0, xF86XK_Calculator), ifWindows (className =? "Gnome-calculator") (mapM_ killWindow) (spawnHere "gnome-calculator")) , ((0, xF86XK_AudioPlay), spawn "clementine --play-pause") --, ((0, xF86XK_AudioMute), spawn "amixer -c 0 set Master toggle") , ((0, xF86XK_AudioMute), spawn "/home/trey/bin/mute") , ((0, xF86XK_AudioRaiseVolume), spawn "amixer -c 0 set Master 5dB+") , ((0, xF86XK_AudioLowerVolume), spawn "amixer -c 0 set Master 5dB-") -- , ((winKey .|. controlMask, xK_Left), shiftToPrev >> prevWS) -- , ((winKey .|. controlMask, xK_Right), shiftToNext >> nextWS) , ((winKey .|. controlMask, xK_h), sendMessage Shrink) , ((winKey .|. lAlt, xK_h), do --windows (viewOnScreen 1 "hng") windows (viewOnScreen 1 "sb") ifWindows (className =? "chromium") (mapM_ focus) (spawnHere "chromium")) --ifWindows (className =? "Iceweasel") (mapM_ focus) (spawnHere "iceweasel")) , ((winKey .|. controlMask, xK_l), sendMessage Expand) , ((winKey , xK_1), windows (viewOnScreen 0 "sh")) , ((winKey , xK_2), windows (viewOnScreen 0 "sb")) , ((winKey , xK_a), do windows (viewOnScreen 1 "hip") --ifWindows (className =? "Pidgin") (mapM_ focus) (spawnHere "pidgin")) ifWindows (className =? "Hipchat") (mapM_ focus) (spawnHere "hipchat")) {- , ((winKey , xK_2), windows (viewOnScreen 0 "02:jobs")) , ((winKey , xK_3), windows (viewOnScreen 0 "03:is660")) , ((winKey , xK_4), windows (viewOnScreen 0 "04:office")) , ((winKey , xK_5), windows (viewOnScreen 0 "05:sysadmin")) , ((winKey , xK_6), windows (viewOnScreen 0 "06:irc")) , ((winKey , xK_7), windows (viewOnScreen 0 "07:digium")) , ((winKey , xK_8), windows (viewOnScreen 0 "08:vm")) , ((winKey , xK_9), windows (viewOnScreen 0 "09:dump")) , ((winKey , xK_0), windows (viewOnScreen 0 "10:music")) , ((winKey , xK_F1), windows (viewOnScreen 1 "F1:man")) , ((winKey , xK_F2), windows (viewOnScreen 1 "F2:jobs")) , ((winKey , xK_F3), windows (viewOnScreen 1 "F3:isovr")) , ((winKey , xK_F4), windows (viewOnScreen 1 "F4:offovr")) , ((winKey , xK_F5), windows (viewOnScreen 1 "F5:sysovr")) , ((winKey , xK_F6), windows (viewOnScreen 1 "F6:ircovr")) , ((winKey , xK_F7), windows (viewOnScreen 1 "F7:dgmovr")) , ((winKey , xK_F8), windows (viewOnScreen 1 "F8:vmovr")) , ((winKey , xK_F9), windows (viewOnScreen 1 "F9:dmpovr")) , ((winKey , xK_F10), windows (viewOnScreen 1 "F10:musovr"))-} , ((winKey .|. shiftMask , xK_q), spawn "xfce4-session-logout") -- win+h shows the selected workspace , ((winKey , xK_h), DW.withWorkspace myXPConfigSelect $ \wk -> do sc <- screenBy 0 if sc == 0 --then XS.modify $ LeftScreen . (wk :) . getLeftScreen -- prefix to list then XS.modify $ LeftScreen . (++ [wk]) . getLeftScreen -- append to list --else XS.modify $ RightScreen . (wk :) . getRightScreen -- prefix to list else XS.modify $ RightScreen . (++ [wk]) . getRightScreen -- append to list windows $ W.view wk) -- win+z moves the current window to the selected workspace , ((winKey , xK_z), DW.withWorkspace myXPConfigSelect (\ws -> do sc <- screenBy 0 if sc == 0 then XS.modify $ LeftScreen . nub . (ws :) . getLeftScreen -- prefix to list else XS.modify $ RightScreen . nub . (ws :) . getRightScreen -- prefix to list --then XS.modify $ LeftScreen . nub . (++ [ws]) . getLeftScreen -- append to list --else XS.modify $ RightScreen . nub . (++ [ws]) . getRightScreen -- append to list windows $ W.shift ws -- refresh )) -- win+BackSpace removes the current workspace , ((winKey , xK_BackSpace), do curr <- gets (W.currentTag . windowset) sc <- screenBy 0 if sc == 0 then do ws <- XS.gets getLeftScreen XS.put (LeftScreen (filter (/= curr) ws)) else do ws <- XS.gets getRightScreen XS.put (RightScreen (filter (/= curr) ws)) DW.removeWorkspace ) -- win+ctrl+r renames the current workspace , ((winKey .|. controlMask , xK_r), do old <- gets (W.currentTag . windowset) DW.renameWorkspace myXPConfigNew created <- gets (W.currentTag . windowset) sc <- screenBy 0 if sc == 0 then do ws <- XS.gets getLeftScreen XS.put (LeftScreen (filter (/= old) ws)) --XS.modify $ LeftScreen . (created :) . getLeftScreen -- prefix to list XS.modify $ LeftScreen . (++ [created]) . getLeftScreen -- append to list else do ws <- XS.gets getRightScreen XS.put (RightScreen (filter (/= old) ws)) --XS.modify $ RightScreen . (created :) . getRightScreen -- prefix to list XS.modify $ RightScreen . (++ [created]) . getRightScreen -- append to list refresh) -- win+m creates a new workspace , ((winKey , xK_m) , DW.withWorkspace myXPConfigNew $ \wk -> do sc <- screenBy 0 if sc == 0 --then XS.modify $ LeftScreen . (wk :) . getLeftScreen -- prefix to list then XS.modify $ LeftScreen . (++ [wk]) . getLeftScreen -- append to list --else XS.modify $ RightScreen . (wk :) . getRightScreen -- prefix to list else XS.modify $ RightScreen . (++ [wk]) . getRightScreen -- append to list windows $ W.view wk) --, ((winKey .|. shiftMask, xK_d) -- macro conflict dialog problem needs to be resolved ] ++ -- Set up window -> workspace keys [((m .|. winKey, key), screenWorkspace sc >>= flip whenJust (windows . f)) -- | (key, sc) <- zip [xK_w, xK_r] [0..] -- | (key, sc) <- zip [xK_Left, xK_Right] [0..] -- For arrow keys | (key, sc) <- zip [xK_w, xK_r] [0..] -- For w,e keys , (f, m) <- [(W.view, 0), (W.shift, controlMask)]] dXPConfig = defaultXPConfig { bgColor = "yellow" , fgColor = "blue" } myXPConfigSelect = defaultXPConfig { bgColor = "yellow" , fgColor = "blue" , autoComplete = Just 0 , showCompletionOnTab = True } myXPConfigNew = defaultXPConfig { bgColor = "yellow" , fgColor = "blue" , autoComplete = Nothing , showCompletionOnTab = True }
tblancher/xmonad.hs
xmonad.hs
gpl-3.0
26,739
268
19
8,154
4,500
2,527
1,973
303
6
-- 4.1 halve :: [a] -> ([a],[a]) halve xs = splitAt (length xs `div` 2) xs {- halve xs = splitAt len xs where len = length xs `div` 2 -} -- 4.2 third :: [a] -> a -- third xs = head (tail(tail xs)) -- third xs = xs !! 2 third (_:_:x:_) = x -- 4.3 safetail :: [a] -> [a] -- safetail xs = if (null xs) then xs else tail xs -- safetail xs | null xs = xs -- | otherwise = tail xs safetail [] = [] safetail xs = tail xs -- 4.4 (||) :: Bool -> Bool -> Bool --(||) True _ = True --(||) _ True = True (||) False b = b (||) b False = b -- 4.5 -- (&&) :: Bool -> Bool -> Bool -- (&&) a b = if (a == True Prelude.&& b == True) then True else False -- 4.6 (&&) :: Bool -> Bool -> Bool (&&) a b = if (a == True) then b else False -- 4.7 mult :: Int -> Int -> Int -> Int --mult x y z = x*y*z mult = \x -> (\y -> (\z -> x*y*z)) luhnDouble :: Int -> Int luhnDouble x | x < 5 = x+x | otherwise = x+x-9 luhn :: Int -> Int -> Int -> Int -> Bool luhn a b c d = if mod ((luhnDouble a) + b + (luhnDouble c) + d) 10 > 0 then False else True
senavi/haskell
chp4.hs
gpl-3.0
1,108
0
13
344
400
226
174
21
2
import H99.Problem11 main = do putStrLn "Enter a list of characters:" inputList <- readLn :: IO [Char] putStrLn (show (encodeModified inputList))
shimanekb/H-99SetTwo
problem11/src/Main.hs
gpl-3.0
171
0
11
46
51
24
27
5
1
-- filter the values in the give list based on the predicate function -- Ex: filter' (>10) [1..12] -- [11,12] filter' :: (a -> Bool) -> [a] -> [a] filter' _ [] = [] filter' f (x:xs) | f x = x:filter' f xs | otherwise = filter' f xs -- filter with left fold filter'' :: (a -> Bool) -> [a] -> [a] filter'' pred list = foldl (\acc x -> if pred x then acc ++ [x] else acc) [] list -- filter with right fold filter''' :: (a -> Bool) -> [a] -> [a] filter''' pred list = foldr(\x acc -> if pred x then x:acc else acc) [] list -- we can omit the list parameter anyways it's gonna retrun a curried function -- filter''' pred = foldr(\x acc -> if pred x then x:acc else acc) []
muralikrishna8/Haskell-problems
filter.hs
gpl-3.0
681
1
10
155
244
130
114
9
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AlertCenter.Alerts.Undelete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Restores, or \"undeletes\", an alert that was marked for deletion within -- the past 30 days. Attempting to undelete an alert which was marked for -- deletion over 30 days ago (which has been removed from the Alert Center -- database) or a nonexistent alert returns a \`NOT_FOUND\` error. -- Attempting to undelete an alert which has not been marked for deletion -- has no effect. -- -- /See:/ <https://developers.google.com/admin-sdk/alertcenter/ Google Workspace Alert Center API Reference> for @alertcenter.alerts.undelete@. module Network.Google.Resource.AlertCenter.Alerts.Undelete ( -- * REST Resource AlertsUndeleteResource -- * Creating a Request , alertsUndelete , AlertsUndelete -- * Request Lenses , auXgafv , auUploadProtocol , auAccessToken , auAlertId , auUploadType , auPayload , auCallback ) where import Network.Google.AlertCenter.Types import Network.Google.Prelude -- | A resource alias for @alertcenter.alerts.undelete@ method which the -- 'AlertsUndelete' request conforms to. type AlertsUndeleteResource = "v1beta1" :> "alerts" :> CaptureMode "alertId" "undelete" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] UndeleteAlertRequest :> Post '[JSON] Alert -- | Restores, or \"undeletes\", an alert that was marked for deletion within -- the past 30 days. Attempting to undelete an alert which was marked for -- deletion over 30 days ago (which has been removed from the Alert Center -- database) or a nonexistent alert returns a \`NOT_FOUND\` error. -- Attempting to undelete an alert which has not been marked for deletion -- has no effect. -- -- /See:/ 'alertsUndelete' smart constructor. data AlertsUndelete = AlertsUndelete' { _auXgafv :: !(Maybe Xgafv) , _auUploadProtocol :: !(Maybe Text) , _auAccessToken :: !(Maybe Text) , _auAlertId :: !Text , _auUploadType :: !(Maybe Text) , _auPayload :: !UndeleteAlertRequest , _auCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AlertsUndelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'auXgafv' -- -- * 'auUploadProtocol' -- -- * 'auAccessToken' -- -- * 'auAlertId' -- -- * 'auUploadType' -- -- * 'auPayload' -- -- * 'auCallback' alertsUndelete :: Text -- ^ 'auAlertId' -> UndeleteAlertRequest -- ^ 'auPayload' -> AlertsUndelete alertsUndelete pAuAlertId_ pAuPayload_ = AlertsUndelete' { _auXgafv = Nothing , _auUploadProtocol = Nothing , _auAccessToken = Nothing , _auAlertId = pAuAlertId_ , _auUploadType = Nothing , _auPayload = pAuPayload_ , _auCallback = Nothing } -- | V1 error format. auXgafv :: Lens' AlertsUndelete (Maybe Xgafv) auXgafv = lens _auXgafv (\ s a -> s{_auXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). auUploadProtocol :: Lens' AlertsUndelete (Maybe Text) auUploadProtocol = lens _auUploadProtocol (\ s a -> s{_auUploadProtocol = a}) -- | OAuth access token. auAccessToken :: Lens' AlertsUndelete (Maybe Text) auAccessToken = lens _auAccessToken (\ s a -> s{_auAccessToken = a}) -- | Required. The identifier of the alert to undelete. auAlertId :: Lens' AlertsUndelete Text auAlertId = lens _auAlertId (\ s a -> s{_auAlertId = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). auUploadType :: Lens' AlertsUndelete (Maybe Text) auUploadType = lens _auUploadType (\ s a -> s{_auUploadType = a}) -- | Multipart request metadata. auPayload :: Lens' AlertsUndelete UndeleteAlertRequest auPayload = lens _auPayload (\ s a -> s{_auPayload = a}) -- | JSONP auCallback :: Lens' AlertsUndelete (Maybe Text) auCallback = lens _auCallback (\ s a -> s{_auCallback = a}) instance GoogleRequest AlertsUndelete where type Rs AlertsUndelete = Alert type Scopes AlertsUndelete = '["https://www.googleapis.com/auth/apps.alerts"] requestClient AlertsUndelete'{..} = go _auAlertId _auXgafv _auUploadProtocol _auAccessToken _auUploadType _auCallback (Just AltJSON) _auPayload alertCenterService where go = buildClient (Proxy :: Proxy AlertsUndeleteResource) mempty
brendanhay/gogol
gogol-alertcenter/gen/Network/Google/Resource/AlertCenter/Alerts/Undelete.hs
mpl-2.0
5,500
0
17
1,273
790
464
326
112
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.Storage -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Stores and retrieves potentially large, immutable data objects. -- -- /See:/ <https://developers.google.com/storage/docs/json_api/ Cloud Storage JSON API Reference> module Network.Google.Storage ( -- * Service Configuration storageService -- * OAuth Scopes , cloudPlatformReadOnlyScope , cloudPlatformScope , storageReadOnlyScope , storageReadWriteScope , storageFullControlScope -- * API Declaration , StorageAPI -- * Resources -- ** storage.bucketAccessControls.delete , module Network.Google.Resource.Storage.BucketAccessControls.Delete -- ** storage.bucketAccessControls.get , module Network.Google.Resource.Storage.BucketAccessControls.Get -- ** storage.bucketAccessControls.insert , module Network.Google.Resource.Storage.BucketAccessControls.Insert -- ** storage.bucketAccessControls.list , module Network.Google.Resource.Storage.BucketAccessControls.List -- ** storage.bucketAccessControls.patch , module Network.Google.Resource.Storage.BucketAccessControls.Patch -- ** storage.bucketAccessControls.update , module Network.Google.Resource.Storage.BucketAccessControls.Update -- ** storage.buckets.delete , module Network.Google.Resource.Storage.Buckets.Delete -- ** storage.buckets.get , module Network.Google.Resource.Storage.Buckets.Get -- ** storage.buckets.insert , module Network.Google.Resource.Storage.Buckets.Insert -- ** storage.buckets.list , module Network.Google.Resource.Storage.Buckets.List -- ** storage.buckets.patch , module Network.Google.Resource.Storage.Buckets.Patch -- ** storage.buckets.update , module Network.Google.Resource.Storage.Buckets.Update -- ** storage.channels.stop , module Network.Google.Resource.Storage.Channels.Stop -- ** storage.defaultObjectAccessControls.delete , module Network.Google.Resource.Storage.DefaultObjectAccessControls.Delete -- ** storage.defaultObjectAccessControls.get , module Network.Google.Resource.Storage.DefaultObjectAccessControls.Get -- ** storage.defaultObjectAccessControls.insert , module Network.Google.Resource.Storage.DefaultObjectAccessControls.Insert -- ** storage.defaultObjectAccessControls.list , module Network.Google.Resource.Storage.DefaultObjectAccessControls.List -- ** storage.defaultObjectAccessControls.patch , module Network.Google.Resource.Storage.DefaultObjectAccessControls.Patch -- ** storage.defaultObjectAccessControls.update , module Network.Google.Resource.Storage.DefaultObjectAccessControls.Update -- ** storage.objectAccessControls.delete , module Network.Google.Resource.Storage.ObjectAccessControls.Delete -- ** storage.objectAccessControls.get , module Network.Google.Resource.Storage.ObjectAccessControls.Get -- ** storage.objectAccessControls.insert , module Network.Google.Resource.Storage.ObjectAccessControls.Insert -- ** storage.objectAccessControls.list , module Network.Google.Resource.Storage.ObjectAccessControls.List -- ** storage.objectAccessControls.patch , module Network.Google.Resource.Storage.ObjectAccessControls.Patch -- ** storage.objectAccessControls.update , module Network.Google.Resource.Storage.ObjectAccessControls.Update -- ** storage.objects.compose , module Network.Google.Resource.Storage.Objects.Compose -- ** storage.objects.copy , module Network.Google.Resource.Storage.Objects.Copy -- ** storage.objects.delete , module Network.Google.Resource.Storage.Objects.Delete -- ** storage.objects.get , module Network.Google.Resource.Storage.Objects.Get -- ** storage.objects.insert , module Network.Google.Resource.Storage.Objects.Insert -- ** storage.objects.list , module Network.Google.Resource.Storage.Objects.List -- ** storage.objects.patch , module Network.Google.Resource.Storage.Objects.Patch -- ** storage.objects.rewrite , module Network.Google.Resource.Storage.Objects.Rewrite -- ** storage.objects.update , module Network.Google.Resource.Storage.Objects.Update -- ** storage.objects.watchAll , module Network.Google.Resource.Storage.Objects.WatchAll -- * Types -- ** ObjectOwner , ObjectOwner , objectOwner , ooEntity , ooEntityId -- ** ObjectsInsertProjection , ObjectsInsertProjection (..) -- ** BucketVersioning , BucketVersioning , bucketVersioning , bvEnabled -- ** BucketsUpdatePredefinedDefaultObjectACL , BucketsUpdatePredefinedDefaultObjectACL (..) -- ** ObjectsComposeDestinationPredefinedACL , ObjectsComposeDestinationPredefinedACL (..) -- ** BucketsInsertPredefinedACL , BucketsInsertPredefinedACL (..) -- ** Buckets , Buckets , buckets , bNextPageToken , bKind , bItems -- ** BucketLogging , BucketLogging , bucketLogging , blLogBucket , blLogObjectPrefix -- ** ObjectMetadata , ObjectMetadata , objectMetadata , omAddtional -- ** ObjectsPatchPredefinedACL , ObjectsPatchPredefinedACL (..) -- ** BucketLifecycleRuleItemCondition , BucketLifecycleRuleItemCondition , bucketLifecycleRuleItemCondition , blricAge , blricIsLive , blricNumNewerVersions , blricMatchesStorageClass , blricCreatedBefore -- ** ObjectsRewriteDestinationPredefinedACL , ObjectsRewriteDestinationPredefinedACL (..) -- ** BucketLifecycle , BucketLifecycle , bucketLifecycle , blRule -- ** Channel , Channel , channel , cResourceURI , cResourceId , cKind , cExpiration , cToken , cAddress , cPayload , cParams , cId , cType -- ** BucketLifecycleRuleItem , BucketLifecycleRuleItem , bucketLifecycleRuleItem , blriAction , blriCondition -- ** ObjectsWatchAllProjection , ObjectsWatchAllProjection (..) -- ** BucketCORSItem , BucketCORSItem , bucketCORSItem , bciMaxAgeSeconds , bciOrigin , bciResponseHeader , bciMethod -- ** ObjectAccessControlProjectTeam , ObjectAccessControlProjectTeam , objectAccessControlProjectTeam , oacptProjectNumber , oacptTeam -- ** ObjectCustomerEncryption , ObjectCustomerEncryption , objectCustomerEncryption , oceKeySha256 , oceEncryptionAlgorithm -- ** Bucket , Bucket , bucket , bucEtag , bucLocation , bucKind , bucWebsite , bucProjectNumber , bucLifecycle , bucOwner , bucSelfLink , bucName , bucStorageClass , bucVersioning , bucCORS , bucTimeCreated , bucId , bucUpdated , bucDefaultObjectACL , bucMetageneration , bucLogging , bucACL -- ** BucketsGetProjection , BucketsGetProjection (..) -- ** Objects , Objects , objects , oNextPageToken , oKind , oItems , oPrefixes -- ** BucketsPatchProjection , BucketsPatchProjection (..) -- ** BucketAccessControls , BucketAccessControls , bucketAccessControls , bacKind , bacItems -- ** BucketsUpdateProjection , BucketsUpdateProjection (..) -- ** ComposeRequest , ComposeRequest , composeRequest , crDestination , crKind , crSourceObjects -- ** ObjectsInsertPredefinedACL , ObjectsInsertPredefinedACL (..) -- ** ObjectsListProjection , ObjectsListProjection (..) -- ** BucketsInsertPredefinedDefaultObjectACL , BucketsInsertPredefinedDefaultObjectACL (..) -- ** BucketsUpdatePredefinedACL , BucketsUpdatePredefinedACL (..) -- ** ObjectsCopyDestinationPredefinedACL , ObjectsCopyDestinationPredefinedACL (..) -- ** ObjectsUpdatePredefinedACL , ObjectsUpdatePredefinedACL (..) -- ** BucketOwner , BucketOwner , bucketOwner , boEntity , boEntityId -- ** ComposeRequestSourceObjectsItem , ComposeRequestSourceObjectsItem , composeRequestSourceObjectsItem , crsoiName , crsoiObjectPreconditions , crsoiGeneration -- ** BucketsInsertProjection , BucketsInsertProjection (..) -- ** ChannelParams , ChannelParams , channelParams , cpAddtional -- ** BucketsListProjection , BucketsListProjection (..) -- ** ObjectsUpdateProjection , ObjectsUpdateProjection (..) -- ** Object , Object , object' , objEtag , objTimeStorageClassUpdated , objSize , objKind , objTimeDeleted , objCrc32c , objCustomerEncryption , objBucket , objOwner , objSelfLink , objMediaLink , objComponentCount , objName , objStorageClass , objContentEncoding , objMetadata , objTimeCreated , objId , objUpdated , objContentLanguage , objCacheControl , objMetageneration , objGeneration , objACL , objContentDisPosition , objMD5Hash , objContentType -- ** ObjectsPatchProjection , ObjectsPatchProjection (..) -- ** ComposeRequestSourceObjectsItemObjectPreconditions , ComposeRequestSourceObjectsItemObjectPreconditions , composeRequestSourceObjectsItemObjectPreconditions , crsoiopIfGenerationMatch -- ** BucketAccessControlProjectTeam , BucketAccessControlProjectTeam , bucketAccessControlProjectTeam , bacptProjectNumber , bacptTeam -- ** ObjectAccessControls , ObjectAccessControls , objectAccessControls , oacKind , oacItems -- ** BucketWebsite , BucketWebsite , bucketWebsite , bwMainPageSuffix , bwNotFoundPage -- ** BucketAccessControl , BucketAccessControl , bucketAccessControl , bacaEmail , bacaEtag , bacaKind , bacaDomain , bacaBucket , bacaRole , bacaSelfLink , bacaId , bacaProjectTeam , bacaEntity , bacaEntityId -- ** BucketLifecycleRuleItemAction , BucketLifecycleRuleItemAction , bucketLifecycleRuleItemAction , blriaStorageClass , blriaType -- ** ObjectsGetProjection , ObjectsGetProjection (..) -- ** BucketsPatchPredefinedDefaultObjectACL , BucketsPatchPredefinedDefaultObjectACL (..) -- ** BucketsPatchPredefinedACL , BucketsPatchPredefinedACL (..) -- ** ObjectAccessControl , ObjectAccessControl , objectAccessControl , oacaEmail , oacaEtag , oacaKind , oacaDomain , oacaBucket , oacaRole , oacaSelfLink , oacaObject , oacaId , oacaProjectTeam , oacaEntity , oacaGeneration , oacaEntityId -- ** ObjectsCopyProjection , ObjectsCopyProjection (..) -- ** RewriteResponse , RewriteResponse , rewriteResponse , rrKind , rrDone , rrResource , rrObjectSize , rrTotalBytesRewritten , rrRewriteToken -- ** ObjectsRewriteProjection , ObjectsRewriteProjection (..) ) where import Network.Google.Prelude import Network.Google.Resource.Storage.BucketAccessControls.Delete import Network.Google.Resource.Storage.BucketAccessControls.Get import Network.Google.Resource.Storage.BucketAccessControls.Insert import Network.Google.Resource.Storage.BucketAccessControls.List import Network.Google.Resource.Storage.BucketAccessControls.Patch import Network.Google.Resource.Storage.BucketAccessControls.Update import Network.Google.Resource.Storage.Buckets.Delete import Network.Google.Resource.Storage.Buckets.Get import Network.Google.Resource.Storage.Buckets.Insert import Network.Google.Resource.Storage.Buckets.List import Network.Google.Resource.Storage.Buckets.Patch import Network.Google.Resource.Storage.Buckets.Update import Network.Google.Resource.Storage.Channels.Stop import Network.Google.Resource.Storage.DefaultObjectAccessControls.Delete import Network.Google.Resource.Storage.DefaultObjectAccessControls.Get import Network.Google.Resource.Storage.DefaultObjectAccessControls.Insert import Network.Google.Resource.Storage.DefaultObjectAccessControls.List import Network.Google.Resource.Storage.DefaultObjectAccessControls.Patch import Network.Google.Resource.Storage.DefaultObjectAccessControls.Update import Network.Google.Resource.Storage.ObjectAccessControls.Delete import Network.Google.Resource.Storage.ObjectAccessControls.Get import Network.Google.Resource.Storage.ObjectAccessControls.Insert import Network.Google.Resource.Storage.ObjectAccessControls.List import Network.Google.Resource.Storage.ObjectAccessControls.Patch import Network.Google.Resource.Storage.ObjectAccessControls.Update import Network.Google.Resource.Storage.Objects.Compose import Network.Google.Resource.Storage.Objects.Copy import Network.Google.Resource.Storage.Objects.Delete import Network.Google.Resource.Storage.Objects.Get import Network.Google.Resource.Storage.Objects.Insert import Network.Google.Resource.Storage.Objects.List import Network.Google.Resource.Storage.Objects.Patch import Network.Google.Resource.Storage.Objects.Rewrite import Network.Google.Resource.Storage.Objects.Update import Network.Google.Resource.Storage.Objects.WatchAll import Network.Google.Storage.Types {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Cloud Storage JSON API service. type StorageAPI = BucketsInsertResource :<|> BucketsListResource :<|> BucketsPatchResource :<|> BucketsGetResource :<|> BucketsDeleteResource :<|> BucketsUpdateResource :<|> ChannelsStopResource :<|> DefaultObjectAccessControlsInsertResource :<|> DefaultObjectAccessControlsListResource :<|> DefaultObjectAccessControlsPatchResource :<|> DefaultObjectAccessControlsGetResource :<|> DefaultObjectAccessControlsDeleteResource :<|> DefaultObjectAccessControlsUpdateResource :<|> ObjectsInsertResource :<|> ObjectsListResource :<|> ObjectsCopyResource :<|> ObjectsWatchAllResource :<|> ObjectsPatchResource :<|> ObjectsGetResource :<|> ObjectsRewriteResource :<|> ObjectsComposeResource :<|> ObjectsDeleteResource :<|> ObjectsUpdateResource :<|> BucketAccessControlsInsertResource :<|> BucketAccessControlsListResource :<|> BucketAccessControlsPatchResource :<|> BucketAccessControlsGetResource :<|> BucketAccessControlsDeleteResource :<|> BucketAccessControlsUpdateResource :<|> ObjectAccessControlsInsertResource :<|> ObjectAccessControlsListResource :<|> ObjectAccessControlsPatchResource :<|> ObjectAccessControlsGetResource :<|> ObjectAccessControlsDeleteResource :<|> ObjectAccessControlsUpdateResource
rueshyna/gogol
gogol-storage/gen/Network/Google/Storage.hs
mpl-2.0
15,588
0
38
3,252
1,709
1,244
465
337
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Healthcare.Projects.Locations.DataSets.Hl7V2Stores.Messages.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes an HL7v2 message. -- -- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.hl7V2Stores.messages.delete@. module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.Hl7V2Stores.Messages.Delete ( -- * REST Resource ProjectsLocationsDataSetsHl7V2StoresMessagesDeleteResource -- * Creating a Request , projectsLocationsDataSetsHl7V2StoresMessagesDelete , ProjectsLocationsDataSetsHl7V2StoresMessagesDelete -- * Request Lenses , pldshvsmdXgafv , pldshvsmdUploadProtocol , pldshvsmdAccessToken , pldshvsmdUploadType , pldshvsmdName , pldshvsmdCallback ) where import Network.Google.Healthcare.Types import Network.Google.Prelude -- | A resource alias for @healthcare.projects.locations.datasets.hl7V2Stores.messages.delete@ method which the -- 'ProjectsLocationsDataSetsHl7V2StoresMessagesDelete' request conforms to. type ProjectsLocationsDataSetsHl7V2StoresMessagesDeleteResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Empty -- | Deletes an HL7v2 message. -- -- /See:/ 'projectsLocationsDataSetsHl7V2StoresMessagesDelete' smart constructor. data ProjectsLocationsDataSetsHl7V2StoresMessagesDelete = ProjectsLocationsDataSetsHl7V2StoresMessagesDelete' { _pldshvsmdXgafv :: !(Maybe Xgafv) , _pldshvsmdUploadProtocol :: !(Maybe Text) , _pldshvsmdAccessToken :: !(Maybe Text) , _pldshvsmdUploadType :: !(Maybe Text) , _pldshvsmdName :: !Text , _pldshvsmdCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsDataSetsHl7V2StoresMessagesDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pldshvsmdXgafv' -- -- * 'pldshvsmdUploadProtocol' -- -- * 'pldshvsmdAccessToken' -- -- * 'pldshvsmdUploadType' -- -- * 'pldshvsmdName' -- -- * 'pldshvsmdCallback' projectsLocationsDataSetsHl7V2StoresMessagesDelete :: Text -- ^ 'pldshvsmdName' -> ProjectsLocationsDataSetsHl7V2StoresMessagesDelete projectsLocationsDataSetsHl7V2StoresMessagesDelete pPldshvsmdName_ = ProjectsLocationsDataSetsHl7V2StoresMessagesDelete' { _pldshvsmdXgafv = Nothing , _pldshvsmdUploadProtocol = Nothing , _pldshvsmdAccessToken = Nothing , _pldshvsmdUploadType = Nothing , _pldshvsmdName = pPldshvsmdName_ , _pldshvsmdCallback = Nothing } -- | V1 error format. pldshvsmdXgafv :: Lens' ProjectsLocationsDataSetsHl7V2StoresMessagesDelete (Maybe Xgafv) pldshvsmdXgafv = lens _pldshvsmdXgafv (\ s a -> s{_pldshvsmdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pldshvsmdUploadProtocol :: Lens' ProjectsLocationsDataSetsHl7V2StoresMessagesDelete (Maybe Text) pldshvsmdUploadProtocol = lens _pldshvsmdUploadProtocol (\ s a -> s{_pldshvsmdUploadProtocol = a}) -- | OAuth access token. pldshvsmdAccessToken :: Lens' ProjectsLocationsDataSetsHl7V2StoresMessagesDelete (Maybe Text) pldshvsmdAccessToken = lens _pldshvsmdAccessToken (\ s a -> s{_pldshvsmdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pldshvsmdUploadType :: Lens' ProjectsLocationsDataSetsHl7V2StoresMessagesDelete (Maybe Text) pldshvsmdUploadType = lens _pldshvsmdUploadType (\ s a -> s{_pldshvsmdUploadType = a}) -- | The resource name of the HL7v2 message to delete. pldshvsmdName :: Lens' ProjectsLocationsDataSetsHl7V2StoresMessagesDelete Text pldshvsmdName = lens _pldshvsmdName (\ s a -> s{_pldshvsmdName = a}) -- | JSONP pldshvsmdCallback :: Lens' ProjectsLocationsDataSetsHl7V2StoresMessagesDelete (Maybe Text) pldshvsmdCallback = lens _pldshvsmdCallback (\ s a -> s{_pldshvsmdCallback = a}) instance GoogleRequest ProjectsLocationsDataSetsHl7V2StoresMessagesDelete where type Rs ProjectsLocationsDataSetsHl7V2StoresMessagesDelete = Empty type Scopes ProjectsLocationsDataSetsHl7V2StoresMessagesDelete = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsDataSetsHl7V2StoresMessagesDelete'{..} = go _pldshvsmdName _pldshvsmdXgafv _pldshvsmdUploadProtocol _pldshvsmdAccessToken _pldshvsmdUploadType _pldshvsmdCallback (Just AltJSON) healthcareService where go = buildClient (Proxy :: Proxy ProjectsLocationsDataSetsHl7V2StoresMessagesDeleteResource) mempty
brendanhay/gogol
gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/Hl7V2Stores/Messages/Delete.hs
mpl-2.0
5,854
0
15
1,189
698
409
289
113
1
<h3>Example 69 (UI in layout)</h3> <plot-row height=300 aspect=4> <plot axis-x-transform="log" hist="[[histogram(abs(tstdata.x), {transform:'log',nbins:10})]]"> <bars x="[[hist.centres]]" bar-min="[[hist.bins#0]]" bar-max="[[hist.bins#1]]" y="[[hist.freqs]]"></bars> </plot> <plot hist="[[histogram(tstdata.x,nbins)]]" ui-histogram-bins="nbins" ng-init="nbins=10"> <bars x="[[hist.centres]]" y="[[hist.freqs]]"></bars> </plot> </plot-row> <plot-data name="tstdata" format="csv" cols="n,x"> 1,0.581304505340074 2,1.21204235455325 3,0.191467862935979 4,0.404531617084031 5,0.506759598624394 6,0.579974647686925 7,0.382684910509303 8,-2.36128870643163 9,1.89853385492903 10,1.51575482857274 11,-0.431904144237637 12,-0.304952508634339 13,-0.0472550286669151 14,-0.0058502998104083 15,-0.455979726677393 16,-0.703417653034949 17,0.255388632630317 18,1.09731134379105 19,0.697465803808565 20,-0.264402673547431 21,1.54591244360426 22,1.09986112061775 23,1.34660874641935 24,0.456509355339534 25,0.263664668578228 26,-0.594252332034511 27,-0.294243291334233 28,0.57837626799701 29,-1.10914256320694 30,1.4434293738432 31,-1.26438302030187 32,0.101753107463398 33,0.513689399187403 34,-1.09244503560617 35,-0.552555846392525 36,0.347671234277075 37,-0.558130247609365 38,0.106963956723282 39,1.2032287934846 40,0.525191012512843 41,-1.03690272776065 42,-0.235681449524533 43,0.297027399890552 44,-2.05693751007016 45,-0.0417084132399849 46,0.582637025317222 47,1.42125980798211 48,-0.580608768909434 49,0.0956243769571078 50,0.802005931303493 51,0.824003277478335 52,-2.14783912515121 53,0.807233255372811 54,-1.52513452641772 55,-0.597262918993818 56,0.229519244695705 57,-0.629875815431466 58,-0.152705432076918 59,0.869737799584555 60,-0.118870157296424 61,-1.10181651496678 62,-2.13369456410395 63,-0.24742210045977 64,2.40473937762896 65,0.212164847575877 66,-0.139330958129738 67,-0.0102098201231723 68,-0.532649301154746 69,-0.658309759424839 70,0.944419601322942 71,1.92675981552114 72,0.881375787318808 73,-0.224021016626712 74,-2.41856038902337 75,-0.275075705996603 76,0.175430068000957 77,0.16340141423053 78,0.0933825118868204 79,-0.19664306453574 80,-0.0533818075386071 81,0.303397925306288 82,-0.0876865980659361 83,1.35915180280361 84,-0.636453860088958 85,0.511870772927348 86,-1.80148056676245 87,0.102986381796962 88,-0.680996883066525 89,0.129039555365379 90,-0.700970442675383 91,0.124190160122541 92,-0.675808464744478 93,-0.0662030190746051 94,-2.32028758607552 95,-1.17362062178039 96,0.642575128608807 97,-0.911472450317291 98,-0.942519871941206 99,-1.18108570774603 100,2.00060023587407 101,-0.171550620321027 102,-0.429271488243188 103,1.34903419512685 104,0.49780624972158 105,1.03108436948284 106,-1.20492821869859 107,-0.168733171053925 108,0.409747354168807 109,-1.31135097268624 110,-0.788738621269919 111,0.150780834637271 112,-0.76834524844712 113,0.367938229160688 114,-0.465370675629197 115,0.739772121356345 116,-0.774517628778821 117,1.2479317618961 118,-0.110160691076348 119,-1.3202290808219 120,0.563420811057244 121,1.18225736942164 122,1.54651798198507 123,-0.00357996201244856 124,-1.24536559718758 125,-0.601531923428799 126,0.00065203343386637 127,0.938226389255416 128,-0.854398620128164 129,1.49231245122247 130,0.261954400503337 131,-0.888858727069535 132,0.0271024519103931 133,-0.961439728449678 134,1.61451942518124 135,0.78845203329729 136,-0.240225573122382 137,0.338039975540622 138,-0.224430105475584 139,-0.423145488858262 140,-0.128891329304773 141,-0.275705006292522 142,-0.372760760058535 143,-0.0626698873986679 144,-0.537345523977488 145,0.0678603549418136 146,-1.21670762431525 147,-0.611399459618333 148,-1.17626960989247 149,-1.02293799481155 150,0.494282979259704 151,-0.754502457539321 152,1.57592674766961 153,1.91659419062246 154,0.418047881765635 155,0.629723220318726 156,0.308737918206588 157,-0.115064730174841 158,-1.42861596789923 159,-1.24854569659509 160,-1.07525479998502 161,-0.736764936828812 162,0.781132884529203 163,0.783316749112937 164,1.60936292914163 165,0.537798519340024 166,-1.44591500013095 167,0.648653212215553 168,-0.299465569001379 169,0.400058080976256 170,-1.67773087684039 171,1.17776148134736 172,0.435446027025588 173,-1.83194625907076 174,0.907819091227666 175,0.806474644499277 176,-0.833694412862375 177,1.74454557913016 178,1.27030762097459 179,0.772261413935723 180,0.218169249835251 181,-0.0990929702140498 182,0.586000490441215 183,0.402059353311619 184,-0.675415811448084 185,-0.234406469648711 186,0.164208425026398 187,-0.807504046452839 188,-0.886484136559894 189,-1.90495017559016 190,0.710101355941829 191,0.371741709364903 192,1.28880520774802 193,-0.525869279008791 194,1.13059761237859 195,-0.843551898930933 196,-0.81692055465668 197,1.05370936347226 198,-0.56261643681832 199,1.16103432289882 200,-0.948027229335353 201,0.996923366008889 202,0.441844462038733 203,-0.852856875884511 204,0.481752847811884 205,-1.90302750857959 206,1.52045791091913 207,-0.0275065587232198 208,1.08369781189724 209,-0.357387363094251 210,0.911301821033973 211,-0.452005301216677 212,0.221164975728594 213,-0.286975088579797 214,-2.36851333327686 215,-1.81983730667811 216,0.116250452408321 217,-0.827456383436207 218,-0.671683018599487 219,-1.31773060695083 220,0.199680579963757 221,1.19685113294236 222,-0.483254110665315 223,0.231947206866812 224,0.889036065142043 225,1.54807062941433 226,-0.913527054335245 227,-0.0970726679074887 228,-0.620333800957168 229,1.67212344089489 230,-0.907386945773644 231,0.166834397883082 232,-1.20824195912739 233,0.485829416862303 234,0.296188702518597 235,-0.132764050477799 236,-1.58415927047644 237,1.35930155457182 238,0.821874642020641 239,-0.189805769247142 240,-0.458586059431771 241,0.159793687424306 242,0.401001452842642 243,0.545075251689394 244,0.00750241290496845 245,0.541266630408081 246,-1.95103685588892 247,-0.494696956434973 248,1.06796758097058 249,-0.103322676962074 250,-0.339813025195118 251,-1.25283941282152 252,0.619689418381593 253,0.270924068524239 254,-0.546554047271335 255,-0.213537995852268 256,0.998211866248194 257,1.3737557002061 258,0.616584873925329 259,-1.232121033713 260,-1.70765237395592 261,1.9072905354085 262,-0.551121491957606 263,-0.789813803778333 264,1.18455098795674 265,-0.711821785943869 266,-0.961933993144581 267,-0.202215086540066 268,-0.389761149426567 269,1.31371770851131 270,0.25087230317096 271,-2.20997671884169 272,1.43977639105047 273,-0.76947803357973 274,0.178099185848976 275,-0.99191481939144 276,0.172723455239124 277,-0.360681055251426 278,-1.0278872164095 279,-0.252119864940456 280,-1.10948012006894 281,-0.0806350496564546 282,0.778584087770331 283,0.251540931139913 284,-0.111010122702107 285,-0.574499264278291 286,1.9383853335539 287,0.084106718939731 288,-0.0783940442150708 289,0.487203926266261 290,0.163408626093081 291,0.463628284943623 292,0.825758567066444 293,0.0861176465196436 294,-0.719326906214852 295,-1.21575745272619 296,1.60773374517567 297,-0.184600785390465 298,-1.67422145422977 299,-1.57626146257376 300,0.134281910316044 301,1.17198637428403 302,-1.19698391898972 303,0.439396962835662 304,0.246399896283238 305,-1.84117468603921 306,0.655837617755532 307,1.33256011625454 308,-1.70522471577044 309,-1.58198635282305 310,2.25805492713324 311,-0.0230608665911755 312,-0.598864622770893 313,-1.91144749258034 314,-0.653795004543117 315,1.72159497457253 316,0.0810542080303895 317,0.131800947273124 318,-0.0228001695842552 319,0.904227618963941 320,-1.27776706388104 321,1.15692935540042 322,-0.559462064682648 323,0.0309379515139439 324,-0.629868756649808 325,0.988546340875198 326,0.159038881605657 327,2.5860267767014 328,-0.761591306321063 329,1.47166126902885 330,1.81052557347233 331,-1.40567506471575 332,-1.1238743326457 333,-0.438813163448333 334,-1.41504543887722 335,-1.1758589978877 336,-0.241993778106371 337,-1.38850476039263 338,-0.587283173904634 339,0.686735190019949 340,1.00786054830359 341,-0.0543719834770949 342,0.707578579682358 343,-1.15315901528323 344,0.472322114662884 345,-0.493030863057756 346,-0.399061616248822 347,-0.0608312800688757 348,0.0956359677526711 349,0.284587735928472 350,0.226104623480562 351,0.781014212153452 352,-0.732929798808536 353,1.86657107807315 354,0.229235588576792 355,1.4099308379926 356,0.858675127664058 357,2.8561556651777 358,-0.046726116253407 359,0.750653904023443 360,0.891470361543305 361,1.84168624298464 362,2.13462714114365 363,2.15094966110615 364,2.00762260578766 365,0.0989530109933001 366,-0.405733340786729 367,0.294778588430519 368,1.37209358345816 369,-0.168735664923268 370,-0.863071628455621 371,-2.48337696630615 372,0.333797021043419 373,-0.564734171889018 374,-0.522507580720376 375,0.948050339769532 376,0.566243330108368 377,1.38415083641645 378,-1.61781756883314 379,1.06744752294832 380,-0.224126171283262 381,0.100752656282536 382,0.450227919278265 383,0.398495386378657 384,0.897866589231506 385,0.928973690814877 386,-0.75821276697024 387,0.702760082339478 388,-0.49822291157154 389,0.348984720313933 390,0.280981383587609 391,-0.618550046541062 392,0.46491725364276 393,0.00862621436331049 394,0.905154272621152 395,-0.51508352465454 396,-0.0122079949511342 397,1.28681703799685 398,-1.83601076015539 399,1.2867536591868 400,1.44894011440049 401,-0.724936528137437 402,0.862204219746617 403,0.86247000997088 404,0.639815905247209 405,-0.205337046765014 406,-0.982275725503387 407,0.700829423198498 408,-1.02849915340837 409,-1.36759126070836 410,0.600902688908239 411,-0.789496705421206 412,-0.993936714165506 413,0.000438340540509028 414,-0.908226767451531 415,0.558861422624497 416,-1.19753970466825 417,1.13247216743728 418,-0.936808911331148 419,-0.862582791094581 420,-0.336757326822107 421,0.324907176144949 422,-1.63370461957597 423,0.625028781770988 424,0.530712487514642 425,1.27973489084353 426,-0.676487673459008 427,0.100649183203181 428,1.32874284302104 429,-1.72171127839598 430,1.47357464113856 431,0.609423721727337 432,-0.806268500455108 433,-0.589904348632866 434,0.45345005673409 435,0.731618465837137 436,0.570986317297279 437,-0.165560346946315 438,1.75330072719015 439,0.0957997433357354 440,-1.98304551807937 441,1.35948900096037 442,-0.0710824124373133 443,0.854557757587512 444,-1.3817232181048 445,1.79217681711835 446,0.0343742877900416 447,1.47327786361259 448,-0.458792256091705 449,-1.14421622995988 450,-1.16215700338276 451,-1.16839614097253 452,-0.881673011006101 453,0.446957411404416 454,-1.88418907901248 455,-1.7183791084907 456,-0.757539110244134 457,0.433124098563154 458,0.045656108270228 459,-0.369897130377909 460,-0.158648428610961 461,0.261018411806017 462,0.302857387824001 463,-1.5053883190382 464,-0.0762566855145924 465,-0.665102208109862 466,0.0281792919544456 467,1.76577953217513 468,-0.190932489858799 469,-0.732619983215393 470,-0.0778475251954681 471,0.199726679397128 472,0.232604403455499 473,-0.94536434075653 474,-0.879516017608702 475,0.42435616244207 476,0.160892249429933 477,-0.71621796710002 478,-0.398238783536296 479,-0.500720041516363 480,-1.44204272833286 481,-0.162255455505292 482,0.895090837047363 483,-0.261254591212928 484,1.08901672761194 485,0.112072004652568 486,2.48798475983767 487,0.0824778185235224 488,0.00589036038221653 489,-1.45415675375309 490,-0.422245665546738 491,0.532335725819459 492,0.105042771271434 493,-1.48154563923078 494,0.303995690517052 495,-2.12152158715213 496,-1.23535011202778 497,0.205254042816672 498,0.729257031320897 499,-1.00480793568048 500,0.948108624586325 </plot-data>
openbrainsrc/hRadian
examples/Example/defunct/Eg69.hs
mpl-2.0
11,535
1,038
10
576
5,240
1,861
3,379
-1
-1
module Graph (GraphG, GraphE, GraphA, Node, unique) where -- -- DATA CONSTRUCTORS data Node a = Node a deriving Eq data Edge a = Edge (Node a, Node a) data Arc a = Arc (Node a, Node a, Int) deriving Eq data Path a = Path [Node a] deriving (Show, Eq) -- graph-term form data GraphG a = GraphG [Node a] [Edge a] deriving Eq -- edge-term form data GraphE a = GraphE [Edge a] deriving Eq -- adjacency form data GraphA a = GraphA [(Node a, [Node a])] deriving Eq data GraphC a = GraphC [Node a] [Arc a] deriving Eq -- TODO: validation functions for these forms instance Show a => Show (Node a) where show (Node x) = show x instance Show a => Show (Edge a) where show (Edge (Node x, Node y)) = "<" ++ show x ++ "," ++ show y ++ ">" instance Eq a => Eq (Edge a) where (==) x y = if ((inco x == inco y && outg x == outg y) || (inco x == outg y && outg x == inco y)) then True else False instance Show a => Show (Arc a) where show (Arc (Node x, Node y, d)) = "<" ++ show x ++ "," ++ show y ++ "," ++ show d ++ ">" instance Show a => Show (GraphC a) where show (GraphC nodes arcs) = "GraphC: \n\t" ++ "Nodes: " ++ show nodes ++ "\n\tArcs: " ++ show arcs instance Show a => Show (GraphG a) where show (GraphG nodes edges) = "GraphG: \n\t" ++ "Nodes: " ++ show nodes ++ "\n\tEdges: " ++ show edges instance Show a => Show (GraphE a) where show (GraphE edges) = "GraphE: \n\tEdges: " ++ show edges instance Show a => Show (GraphA a) where show (GraphA nodecons) = "GraphA: " ++ flatten ["\n\t" ++ show nc | nc <- nodecons] -- -- FUNCTIONS -- conversions convert_gtoe :: GraphG a -> GraphE a convert_gtoe (GraphG nodes edges) = (GraphE edges) convert_etog :: Eq a => GraphE a -> GraphG a convert_etog (GraphE edges) = let nodes = unique $ extract_nodes edges in GraphG nodes edges convert_gtoa :: (Eq a, Show a) => GraphG a -> GraphA a convert_gtoa (GraphG nodes edges) = GraphA [(n, [edgecomp e n | e <- edges, edgecontains e n]) | n <- nodes] convert_atog :: (Eq a, Show a) => GraphA a -> GraphG a convert_atog ga = GraphG (nodesA ga) (edgesA ga) convert_etoa :: (Eq a, Show a) => GraphE a -> GraphA a convert_etoa = convert_gtoa . convert_etog convert_atoe :: (Eq a, Show a) => GraphA a -> GraphE a convert_atoe = convert_gtoe . convert_atog inco :: Edge a -> Node a inco (Edge (nx, ny)) = ny outg :: Edge a -> Node a outg (Edge (nx, ny)) = nx edgecomp :: (Eq a, Show a) => Edge a -> Node a -> Node a edgecomp e n | n == inco e = outg e | n == outg e = inco e | otherwise = -- error "tuple does not contain node" error ("<" ++ show e ++ "> does not contain <" ++ show n ++ ">") edgecontains :: (Eq a) => Edge a -> Node a -> Bool edgecontains e n | n == inco e = True | n == outg e = True | otherwise = False -- basic functionality nodesG :: GraphG a -> [Node a] nodesG (GraphG ns es) = ns edgesG :: GraphG a -> [Edge a] edgesG (GraphG ns es) = es nodeconsA :: GraphA a -> [(Node a, [Node a])] nodeconsA (GraphA ncs) = ncs nodesA :: GraphA a -> [Node a] nodesA (GraphA ncs) = [fst x | x <- ncs] edgesA :: Eq a => GraphA a -> [Edge a] edgesA (GraphA ncs) = uniqueEdgesA $ flatten [[Edge (fst nc, ne) | ne <- snd nc] | nc <- ncs] edgesA_nonEq :: GraphA a -> [Edge a] edgesA_nonEq = edgeAhelper -- calculate paths in a GraphG paths :: Node a -> Node a -> GraphG a -> [Path a] -- paths = error "Not implemented" paths n1 n2 (GraphG nodes edges) = let pps = initpospath b gg in -- TODO -- pospath [[a] | a <- getadjnodes b gg] gg initpospath :: (Eq a, Show a) => Node a -> GraphG a -> [[Node a]] initpospath n g = [[a, n] | a <- getadjnodes n g] getadjnodes :: (Eq a, Show a) => Node a -> GraphG a -> [Node a] getadjnodes n g = [edgecomp e n | e <- edgesG g, edgecontains e n] pospath :: (Eq a, Show a) => [[Node a]] -> GraphG a -> [[Node a]] pospath pps g = [n:pp | pp <- pps, n <- getadjnodes (head pp) g, not (elem n pp)] -- <snd result> are complete paths, <fst result> are not yet complete complpathssplit :: (Eq a, Show a) => [[Node a]] -> Node a -> ([[Node a]], [[Node a]]) complpathssplit pps n = ([pp | pp <- pps, (head pp) == n], [pp | pp <-pps, (head pp) /= n]) -- helpers edgeAhelper :: GraphA a -> [Edge a] edgeAhelper (GraphA ncs) = flatten [[Edge (fst nc, ne) | ne <- snd nc] | nc <- ncs] uniqueEdgesA :: Eq a => [Edge a] -> [Edge a] uniqueEdgesA [] = [] uniqueEdgesA (e:es) = if (elem e es) then ues else e:ues where ues = uniqueEdgesA es extract_nodes :: Eq a => [Edge a] -> [Node a] -- extract_nodes [] = [] extract_nodes = unique . flatten . map (\t -> [inco t, outg t]) flatten :: [[a]] -> [a] flatten [] = [] flatten (x:xs) = x ++ flatten xs unique :: Eq a => [a] -> [a] unique [] = [] unique (x:xs) = x:(unique [y | y <- xs, y /= x]) -- -- TESTING COMPONENTS b = Node 'b' c = Node 'c' d = Node 'd' f = Node 'f' g = Node 'g' h = Node 'h' k = Node 'k' ns = [b, c, d, f, g, h, k] es = [Edge e | e <- [(g, h), (b, c), (b, f), (c, f), (f, k)]] e = es !! 1 gg = GraphG ns es ga = convert_gtoa gg ge = convert_gtoe gg m = Node 'm' q = Node 'q' p = Node 'p' nsc = [m, p, q, k] arcs = [Arc a | a <- [(p, m, 5), (m, q, 7), (p, q, 9)]] gc = GraphC nsc arcs
ekalosak/haskell-practice
Graph.hs
lgpl-3.0
5,374
0
13
1,422
2,688
1,383
1,305
-1
-1
import Control.Monad (replicateM) chocs n c m = let chocs = div n c swap c | c >= m = (\(d, d') -> d + swap (d + d')) $divMod c m | otherwise = 0 in chocs + swap chocs trip = do [n, c, m] <- fmap (take 3 . map read . words) getLine return $ chocs n c m main = mapM print =<< flip replicateM trip =<< readLn
itsbruce/hackerrank
alg/implementation/chocFeast.hs
unlicense
359
2
16
126
195
91
104
11
1
{-# LANGUAGE ExistentialQuantification, FlexibleContexts, RankNTypes, ScopedTypeVariables, UndecidableInstances #-} module World.Utils ( actionDirection, cellAgent, cellWumpus, cellEntity, cellHas, light, light', numItems, shortestPaths, searchPaths, dist, coordDist, lineDistance, angle, angleToDirection, getCircle, rotateCW, rotateCCW, angleOf, coneOf, inCone, onAgent, getEntityType, onEntity, onAgentMind, sendMsg, entityAt, agentAt, cellAt, onCell, onCellM, inDirection, getDirections, makeEntityIndex, getEntity, makeRel, makeAbs, emptyInventory, itemLens, isPresent, entityPosition, ) where import Control.Lens import Control.Monad (guard) import Data.Functor.Monadic ((>=$>)) import qualified Data.Map as M import Data.Maybe import qualified Data.Semigroup as SG import Math.Geometry.Grid hiding (null) import Math.Geometry.Grid.Square import Math.Geometry.Grid.SquareInternal (SquareDirection(..)) import Math.Utils import Types import Debug.Trace.Wumpus -- Module-specific logging function. logF :: (String -> a) -> a logF f = f "World.Utils" -- |Unsafely gets the 'Direction'-field of an action, if there is one. actionDirection :: Action -> SquareDirection actionDirection (Rotate dir) = dir actionDirection (Move dir) = dir actionDirection (Attack dir) = dir actionDirection (Give dir _) = dir actionDirection (Gesture dir _) = dir actionDirection x = error $ "error: actionDirection called with " ++ show x -- |Returns True iff the given cell has an agent. cellAgent :: CellInd -> World -> Bool cellAgent = cellHas (^. entity . to (maybe False isAgent)) -- |Returns Truee iff the given cell has a Wumpus. cellWumpus :: CellInd -> World -> Bool cellWumpus = cellHas (^. entity . to (maybe False isWumpus)) -- |Returns True iff a given cell exists and has an entity (an agent or a Wumpus) -- on it. cellEntity :: CellInd -> World -> Bool cellEntity = cellHas (^. entity . to isJust) -- |Returns True iff a given cell exists and if it satisfies a predicate. cellHas :: (CellData -> Bool) -> CellInd -> World -> Bool cellHas p i world = world ^. cellData . at i . to (maybe False p) -- |Gets a light value from 0 to 4, depending on the time. light :: Int -> Int light t | 20 <= t' = 0 | t' `between` (15,20) = 1 | t' `between` (10,15) = 2 | t' `between` (5,10) = 3 | otherwise = 4 where t' = abs (t - 25) between n (l, u) = l <= n && n < u -- |Converts a time into a temperature. light' :: Int -> Temperature light' = toEnum . light -- |Returns the number of items of a given type in the agent's inventory. numItems :: Entity (Agent s) t -> Item -> Int numItems e item = case e of Ag a -> fromMaybe 0 $ a ^. inventory . at item Wu _ -> 0 -- Helpers ------------------------------------------------------------------------------- -- |Gets the shortest paths with monotoically decreasing distance from i to j -- in the world. Only paths over existing cells are returned. -- Note that termination/optimality is ensured by NEVER taking away a path -- in which the distance to target increases. If you want to consider all -- nodes at some distance, use 'searchPaths'. shortestPaths :: World -> CellInd -> CellInd -> [[CellInd]] shortestPaths world cur t = if cur == t then return [cur] else do next <- adjacentTilesToward (world ^. graph) cur t guard $ M.member next (world ^. cellData) rest <- shortestPaths world next t return (cur : rest) -- |Searches all paths between i and j depending on a cost function. This is a -- DFS in which the caller has to define the cost of node expansion. The initial -- cost is 'mempty'. searchPaths :: Monoid a => World -> (a -> CellInd -> CellData -> a) -- ^Cost function -> (a -> Bool) -- ^Cost predicate. If a cell fails, it is not expanded. -> CellInd -> CellInd -> [[CellInd]] searchPaths world costUpd costPred = go mempty where cells = world ^. cellData go curCost cur t = if cur == t then return [cur] else do next <- neighbours (world ^. graph) cur let cellData = cells ^. at next guard $ isJust cellData let nextCost = costUpd curCost next $ fromMaybe (error "[searchPaths.nextCost]: Nothing") cellData guard $ costPred nextCost rest <- go nextCost next t return (cur : rest) -- |Gets the Euclidean distance between two cells. dist :: CellInd -> CellInd -> Rational dist i j = toRational $ sqrt $ fromIntegral $ (xd ^ 2) + (yd ^ 2) where (xd,yd) = coordDist i j -- |Gets the distance between to cells as deltaX and deltaY. -- Both values are absolute. coordDist :: CellInd -> CellInd -> (Int, Int) coordDist (x,y) (x',y') = (abs $ x - x', abs $ y - y') -- |Gets the shortest distance from point D to the infinite line passing -- through V and W. -- From <http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points> lineDistance :: CellInd -- V -> CellInd -- W -> CellInd -- D -> Rational lineDistance v@(x1,y1) w@(x2,y2) (dx,dy) = if dist v w == 0 then 0 else fromIntegral (abs nom) / dist v w where nom = (y2 - y1)*dx - (x2-x1)*dy + x2*y1 - y2*x1 -- |Gets the angle between point i and point j in radians (CCW from East). angle :: CellInd -> CellInd -> Float angle (x1,y1) (x2,y2) = if rawVal < 0 then (2*pi) + rawVal else rawVal where dx = fromIntegral $ x2 - x1 dy = fromIntegral $ y2 - y1 rawVal = atan2 dy dx -- |Returns the SquareDirection that corresponds most closely to an angle. angleToDirection :: Float -- ^he angle in radians. -> SquareDirection angleToDirection x | x `between` (pi*0.25, pi*0.75) = North | x `between` (pi*0.75, pi*1.25) = West | x `between` (pi*1.25, pi*1.75) = South | otherwise = East where between n (l,u) = l <= n && n < u -- |Gets all coordinates that are within a given distance of a CellInd. getCircle :: CellInd -> Rational -> [CellInd] getCircle o@(oi, oj) r = filter ((<= r) . dist o) [(i,j) | i <- inds oi, j <- inds oj] where inds x = [x - ceiling r .. x + ceiling r] -- |Rotates a SquareDirection clockwise (N-E-S-W). rotateCW :: SquareDirection -> SquareDirection rotateCW = succMod -- |Rotates a SquareDirection counterclockwise (N-W-S-E). rotateCCW :: SquareDirection -> SquareDirection rotateCCW = prevMod -- |Gets the angle associated with a square direction by drawing an infinite -- line from a point into the given direction. Noth is pi/4, i.e. up. angleOf :: SquareDirection -> Float angleOf North = pi*0.5 angleOf West = pi angleOf South = pi*1.5 angleOf East = 0 -- |Gets a 45°-wide cone centered around a square direction, given by 'angleOf'. coneOf :: SquareDirection -> (Float, Float) coneOf North = (pi/4, 3*pi/4) coneOf West = (3*pi/4, 5*pi/4) coneOf South = (5*pi/4, 7*pi/4) coneOf East = (7*pi/4, pi/4) -- |Indicates whether an angle lies within a cone. For a cone @(l,r)@, the angle @a@ -- has to satisfy @l <= a <= r@. inCone :: (Float, Float) -> Float -> Bool inCone (l,r) a = if l <= r then l <= a && a <= r else l <= a || a <= r -- |Applies a function on an agent. Non-agent entities are left unchanged. onAgent :: (Agent SomeMind -> Agent SomeMind) -> CellData -> CellData onAgent f cell = cell & entity . _Just %~ f' where f' (Ag s) = Ag (f s) f' s = s -- |Gets the type of an entity. getEntityType :: Entity s t -> EntityType getEntityType (Ag _) = TyAgent getEntityType (Wu _) = TyWumpus -- |Applies a function on an entity. onEntity :: (Entity' -> Entity') -> CellData -> CellData onEntity f cell = cell & entity . _Just %~ f -- |Applies a function on a agent's state. onAgentMind :: (s -> s) -> Agent s -> Agent s onAgentMind f a = a & state %~ f -- |Sends a message to an agent via 'receiveMessage'. sendMsg :: Message -> Agent SomeMind -> Agent SomeMind sendMsg = over state . receiveMessage -- |Gets the entity on a given cell. Fails if the cell does not exist or has -- has no entity. entityAt :: String -> CellInd -> World -> Entity' entityAt err i world = world ^. cellData . at' i . juM ("World.Utils.entityAt/" ++ err) entity -- |Gets the agent on a given cell. Fails of the cell does not exist or has -- not agent. agentAt :: String -> CellInd -> World -> Agent SomeMind agentAt err i = fromAgent . entityAt ("agentAt/" ++ err) i -- |Gets the cell with a given index. Fails if the cell does not exist. cellAt :: CellInd -> World -> CellData cellAt i world = world ^. cellData . at i . to (fromMaybe $ error "[cellAt]: Nothing") -- |Applies a function to a given cell. onCell :: CellInd -> (CellData -> CellData) -> World -> World onCell i f world = world & cellData . ix i %~ f -- |Applies a monadic function to a given cell. onCellM :: (Functor m, Monad m) => CellInd -> (CellData -> m CellData) -> World -> m World onCellM i f world = maybe (return world) (f >=$> (\c -> (world & cellData . ix i .~ c))) (world ^. cellData . at i) -- |Moves an index by 1 in a given direction. inDirection :: CellInd -> SquareDirection -> CellInd inDirection i d = fromMaybe (error "[inDirection]: Nothing") $ neighbour UnboundedSquareGrid i d -- |Gets all directions in which movement decreases the distance from i j. -- -- This function will always return at least one item. getDirections :: CellInd -> CellInd -> [SquareDirection] getDirections i j = directionTo UnboundedSquareGrid i j instance Monoid Int where mempty = 0 mappend = (+) -- |Goes through a collection of cells and creates an index of the entities -- contained therein. makeEntityIndex :: (HasEntity c (Maybe (Entity s t)), HasName (Entity s t) EntityName) => M.Map CellInd c -> M.Map EntityName CellInd makeEntityIndex = logF trace "[makeEntityIndex]" $ M.foldrWithKey (\k cd -> if isJust (cd ^. entity) then logF trace ("[makeEntityIndex] -> inserting entity at " ++ show k) $ M.insert (cd ^. entity . to (maybe (error $ show k ++ "MEI nothing!!!") id) . name) k else logF trace ("[makeEntityIndex] no entity at " ++ show k) id) M.empty -- |Gets a given entity's name and location, if it exists. Partial. getEntity :: EntityName -> World -> (CellInd, CellData) getEntity en = head . M.toList . M.filter f . (^. cellData) where f c = maybe False (en ==) (c ^? entity . _Just . name) -- |Gets the difference between two coordinates. makeRel :: CellInd -- |The desired center of the coordinate system -> CellInd -- |The index which should be relative. -> RelInd -- |The difference between the given center and the second coordinate. makeRel (i1,j1) (i2,j2) = RI (i2-i1,j2-j1) -- |Centers coordinates to (0,0). makeAbs :: CellInd -- |Vector 1 -> RelInd -- |Vector 2 -> CellInd -- |Sum of vectors 1 and 2 makeAbs (i1,j1) (RI (i2,j2)) = (i1+i2, j1+j2) -- |Returns an empty inventory with all items present, with quantities of 0. emptyInventory :: M.Map Item Int emptyInventory = M.fromList [(Gold, 0), (Meat, 0), (Fruit, 0)] -- |Gets the lens associated with an item. itemLens :: Item -> Lens' CellData Int itemLens Meat = meat itemLens Gold = gold itemLens Fruit = fruit -- |Returns Truee iff an agent with the given name is present in the world's -- entity index. isPresent :: EntityName -> BaseWorld s t -> Bool isPresent n = M.member n . view agents -- |Returns an agent's position in the world, if present. entityPosition :: EntityName -> BaseWorld s t -> Maybe CellInd entityPosition e = M.lookup e . view agents -- |Always takes the right argument and throws away the left. instance SG.Semigroup VisualCellData where _ <> r = r -- |Always takes the right argument and throws away the left. instance SG.Semigroup CellData where _ <> r = r -- |Always takes the right argument and throws away the left. instance SG.Semigroup EdgeData where _ <> r = r -- |Union-instance. The operator computes the union of two worlds. -- If a cell or edge exists in both worlds, the two are combined using -- their semigroup-instances. -- -- The entity index is regenerated. -- -- If an entity with the same name occurs in two different places in the -- two worlds, we delete it from the left. This is nesessary for internal consistency. instance (SG.Semigroup c, SG.Semigroup e, HasEntity c (Maybe (Entity s t)), HasName (Entity s t) EntityName) => SG.Semigroup (BaseWorld c e) where l <> r = BaseWorld (r ^. worldData) (r ^. graph) (M.unionWith (SG.<>) (l ^. edgeData) (r ^. edgeData)) cells' (makeEntityIndex cells') where -- we first delete the entities from the left world that also occur -- in the right. This is done to prevent an entity showing up in two -- different cells in the following scenario: -- Let an entity E be on a cell X which only occurs in the in the left world. -- Let E also be on a cell Y in the right world and X != Y. -- If we didn't delete E from X, it'd show up in both X and Y. cells' = M.unionWith (SG.<>) cleanedLeftCells (r ^. cellData) cleanedLeftCells = fmap cleanEntities . view cellData $ l cleanEntities v = if fromMaybe False . fmap (\e -> M.member (e ^. name) (r ^. agents)) . view entity $ v then v & entity .~ Nothing else v
jtapolczai/wumpus
World/Utils.hs
apache-2.0
13,859
0
21
3,434
3,652
1,970
1,682
-1
-1
{- © Utrecht University (Department of Information and Computing Sciences) -} module Domain.Scenarios.Services.ExtraServices where import Control.Arrow import Data.Maybe import Ideas.Common.Library import Ideas.Service.State import Domain.Scenarios.Expression import Domain.Scenarios.Globals import Domain.Scenarios.Scenario import Domain.Scenarios.ScenarioState import Domain.Scenarios.Services.Types import qualified Domain.Scenarios.DomainData as DD -- ScenarioList and Info Service ------------------------------------------------------------------------------------- -- Scenariolist service: lists all info for each scenario scenariolist :: [(Id, Scenario)] -> [ScenarioInfo] scenariolist = map getScenarioInfo -- Scenarioinfo service: shows the info for a specific scenario (exercise) scenarioinfo :: [(Id, Scenario)] -> Exercise a -> ScenarioInfo scenarioinfo fs ex = getScenarioInfo (findScenario "scenarioinfo" fs ex) getScenarioInfo :: (Id, Scenario) -> ScenarioInfo getScenarioInfo (sId, ~(Scenario definitions expressions metadata _)) = ScenarioInfo sId (scenarioName metadata) (scenarioLanguage metadata) (scenarioDescription metadata) (scenarioDifficulty metadata) (scenarioVersion metadata) (map describeCharacterDefinition (definitionsCharacters definitions)) (map describeDefinition expressions) (map describeDefinition (useredUserDefined (fst (definitionsParameters definitions)))) (scenarioPropertyValues metadata) where describeCharacterDefinition definition = CharacterDefinitionInfo (characterDefinitionId definition) (characterDefinitionName definition) describeDefinition definition = DefinitionInfo (definitionId definition) (definitionName definition) (definitionDescription definition) (definitionType definition) evaluate :: [(Id, Scenario)] -> State a -> Assocs DD.Value evaluate fs st = Assocs (map (definitionId &&& evaluateExpression tm state . definitionContent) exprs) where ex = exercise st scen = snd (findScenario "evaluate" fs ex) tm = snd (definitionsParameters (scenarioDefinitions scen)) exprs = scenarioExpressions scen ScenarioState state _ = fromMaybe (error "Cannot evaluate exercise: casting failed.") $ castFrom ex (stateTerm st) :: ScenarioState -- | Finds the scenario of the exercise in the given scenario list findScenario :: String -> [(Id, Scenario)] -> Exercise a -> (Id, Scenario) findScenario usage scenarios ex = fromMaybe (error $ "Cannot " ++ usage ++ " exercise: exercise is apparently not a scenario.") (tupleWithId <$> lookup sId scenarios) where sId = getId ex tupleWithId s = (sId, s)
UURAGE/ScenarioReasoner
src/Domain/Scenarios/Services/ExtraServices.hs
apache-2.0
2,881
0
13
609
631
338
293
-1
-1
{-# OPTIONS -fglasgow-exts -#include "../include/gui/qtc_hs_QItemSelection.h" #-} ----------------------------------------------------------------------------- {-| Module : QItemSelection.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:14 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QItemSelection ( QqItemSelection(..) ,QqItemSelection_nf(..) ,qItemSelectionSplit ,qItemSelection_delete ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QItemSelectionModel 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 QqItemSelection x1 where qItemSelection :: x1 -> IO (QItemSelection ()) instance QqItemSelection (()) where qItemSelection () = withQItemSelectionResult $ qtc_QItemSelection foreign import ccall "qtc_QItemSelection" qtc_QItemSelection :: IO (Ptr (TQItemSelection ())) instance QqItemSelection ((QModelIndex t1, QModelIndex t2)) where qItemSelection (x1, x2) = withQItemSelectionResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QItemSelection1 cobj_x1 cobj_x2 foreign import ccall "qtc_QItemSelection1" qtc_QItemSelection1 :: Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO (Ptr (TQItemSelection ())) class QqItemSelection_nf x1 where qItemSelection_nf :: x1 -> IO (QItemSelection ()) instance QqItemSelection_nf (()) where qItemSelection_nf () = withObjectRefResult $ qtc_QItemSelection instance QqItemSelection_nf ((QModelIndex t1, QModelIndex t2)) where qItemSelection_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QItemSelection1 cobj_x1 cobj_x2 instance Qqcontains (QItemSelection a) ((QModelIndex t1)) where qcontains x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QItemSelection_contains cobj_x0 cobj_x1 foreign import ccall "qtc_QItemSelection_contains" qtc_QItemSelection_contains :: Ptr (TQItemSelection a) -> Ptr (TQModelIndex t1) -> IO CBool instance Qindexes (QItemSelection a) (()) where indexes x0 () = withQListObjectRefResult $ \arr -> withObjectPtr x0 $ \cobj_x0 -> qtc_QItemSelection_indexes cobj_x0 arr foreign import ccall "qtc_QItemSelection_indexes" qtc_QItemSelection_indexes :: Ptr (TQItemSelection a) -> Ptr (Ptr (TQModelIndex ())) -> IO CInt instance Qmerge (QItemSelection a) ((QItemSelection t1, SelectionFlags)) where merge x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QItemSelection_merge cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2) foreign import ccall "qtc_QItemSelection_merge" qtc_QItemSelection_merge :: Ptr (TQItemSelection a) -> Ptr (TQItemSelection t1) -> CLong -> IO () instance Qselect (QItemSelection a) ((QModelIndex t1, QModelIndex t2)) where select x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QItemSelection_select cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QItemSelection_select" qtc_QItemSelection_select :: Ptr (TQItemSelection a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO () qItemSelectionSplit :: ((QItemSelectionRange t1, QItemSelectionRange t2, QItemSelection t3)) -> IO () qItemSelectionSplit (x1, x2, x3) = withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QItemSelection_split cobj_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QItemSelection_split" qtc_QItemSelection_split :: Ptr (TQItemSelectionRange t1) -> Ptr (TQItemSelectionRange t2) -> Ptr (TQItemSelection t3) -> IO () qItemSelection_delete :: QItemSelection a -> IO () qItemSelection_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QItemSelection_delete cobj_x0 foreign import ccall "qtc_QItemSelection_delete" qtc_QItemSelection_delete :: Ptr (TQItemSelection a) -> IO ()
uduki/hsQt
Qtc/Gui/QItemSelection.hs
bsd-2-clause
4,210
0
13
648
1,149
595
554
-1
-1
module RaptrSpec where import Network.Raptr.Raptr import Test.Tasty import Test.Tasty.Hspec raptrSpec = describe "Raptr" $ do it "runs 3 node cluster" $ do result <- runRaptr result `shouldBe` True
capital-match/raptr
test/RaptrSpec.hs
bsd-3-clause
243
0
11
73
59
32
27
8
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| This module contains logic for converting Dhall expressions to and from CBOR expressions which can in turn be converted to and from a binary representation -} module Dhall.Binary ( -- * Encoding and decoding encodeExpression , decodeExpression -- * Exceptions , DecodingFailure(..) ) where import Codec.CBOR.Decoding (Decoder, TokenType (..)) import Codec.CBOR.Encoding (Encoding) import Codec.Serialise (Serialise (decode, encode)) import Control.Applicative (empty, (<|>)) import Control.Exception (Exception) import Data.ByteString.Lazy (ByteString) import Dhall.Syntax ( Binding (..) , Chunks (..) , Const (..) , DhallDouble (..) , Directory (..) , Expr (..) , File (..) , FilePrefix (..) , FunctionBinding (..) , Import (..) , ImportHashed (..) , ImportMode (..) , ImportType (..) , MultiLet (..) , PreferAnnotation (..) , RecordField (..) , Scheme (..) , URL (..) , Var (..) , WithComponent (..) ) import Data.Foldable (toList) import Data.Ratio ((%)) import Data.Void (Void, absurd) import GHC.Float (double2Float, float2Double) import Numeric.Half (fromHalf, toHalf) import Prelude hiding (exponent) import qualified Codec.CBOR.ByteArray import qualified Codec.CBOR.Decoding as Decoding import qualified Codec.CBOR.Encoding as Encoding import qualified Codec.CBOR.Read as Read import qualified Codec.Serialise as Serialise import qualified Data.ByteString import qualified Data.ByteString.Lazy import qualified Data.ByteString.Short import qualified Data.Foldable as Foldable import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Sequence import qualified Data.Time as Time import qualified Dhall.Crypto import qualified Dhall.Map import qualified Dhall.Syntax as Syntax import qualified Text.Printf as Printf {-| Convert a function applied to multiple arguments to the base function and the list of arguments -} unApply :: Expr s a -> (Expr s a, [Expr s a]) unApply e₀ = (baseFunction₀, diffArguments₀ []) where ~(baseFunction₀, diffArguments₀) = go e₀ go (App f a) = (baseFunction, diffArguments . (a :)) where ~(baseFunction, diffArguments) = go f go (Note _ e) = go e go baseFunction = (baseFunction, id) decodeExpressionInternal :: (Int -> Decoder s a) -> Decoder s (Expr t a) decodeExpressionInternal decodeEmbed = go where go = do let die message = fail ("Dhall.Binary.decodeExpressionInternal: " <> message) tokenType₀ <- Decoding.peekTokenType case tokenType₀ of TypeUInt -> do !n <- fromIntegral <$> Decoding.decodeWord return (Var (V "_" n)) TypeUInt64 -> do !n <- fromIntegral <$> Decoding.decodeWord64 return (Var (V "_" n)) TypeFloat16 -> do !n <- float2Double <$> Decoding.decodeFloat return (DoubleLit (DhallDouble n)) TypeFloat32 -> do !n <- float2Double <$> Decoding.decodeFloat return (DoubleLit (DhallDouble n)) TypeFloat64 -> do !n <- Decoding.decodeDouble return (DoubleLit (DhallDouble n)) TypeBool -> do !b <- Decoding.decodeBool return (BoolLit b) TypeString -> do !ba <- Decoding.decodeUtf8ByteArray let sb = Codec.CBOR.ByteArray.toShortByteString ba case Data.ByteString.Short.length sb of 4 | sb == "Bool" -> return Bool | sb == "Date" -> return Date | sb == "List" -> return List | sb == "None" -> return None | sb == "Text" -> return Text | sb == "Time" -> return Time | sb == "Type" -> return (Const Type) | sb == "Kind" -> return (Const Kind) | sb == "Sort" -> return (Const Sort) 6 | sb == "Double" -> return Double 7 | sb == "Integer" -> return Integer | sb == "Natural" -> return Natural 8 | sb == "Optional" -> return Optional | sb == "TimeZone" -> return TimeZone 9 | sb == "List/fold" -> return ListFold | sb == "List/head" -> return ListHead | sb == "List/last" -> return ListLast | sb == "Text/show" -> return TextShow 10 | sb == "List/build" -> return ListBuild 11 | sb == "Double/show" -> return DoubleShow | sb == "List/length" -> return ListLength | sb == "Natural/odd" -> return NaturalOdd 12 | sb == "Integer/show" -> return IntegerShow | sb == "List/indexed" -> return ListIndexed | sb == "List/reverse" -> return ListReverse | sb == "Natural/even" -> return NaturalEven | sb == "Natural/fold" -> return NaturalFold | sb == "Natural/show" -> return NaturalShow | sb == "Text/replace" -> return TextReplace 13 | sb == "Integer/clamp" -> return IntegerClamp | sb == "Natural/build" -> return NaturalBuild 14 | sb == "Integer/negate" -> return IntegerNegate | sb == "Natural/isZero" -> return NaturalIsZero 16 | sb == "Integer/toDouble" -> return IntegerToDouble | sb == "Natural/subtract" -> return NaturalSubtract 17 | sb == "Natural/toInteger" -> return NaturalToInteger _ -> die ("Unrecognized built-in: " <> show sb) TypeListLen -> do len <- Decoding.decodeListLen case len of 0 -> die "Missing tag" _ -> return () tokenType₁ <- Decoding.peekTokenType case tokenType₁ of TypeString -> do x <- Decoding.decodeString if x == "_" then die "Non-standard encoding of an α-normalized variable" else return () tokenType₂ <- Decoding.peekTokenType case tokenType₂ of TypeUInt -> do !n <- fromIntegral <$> Decoding.decodeWord return (Var (V x n)) TypeUInt64 -> do !n <- fromIntegral <$> Decoding.decodeWord64 return (Var (V x n)) _ -> die ("Unexpected token type for variable index: " <> show tokenType₂) TypeUInt -> do tag <- Decoding.decodeWord case tag of 0 -> do !f <- go let loop n !acc | n <= 0 = return acc | otherwise = do !x <- go loop (n - 1) (App acc x) let nArgs = len - 2 if nArgs <= 0 then die "Non-standard encoding of a function with no arguments" else loop nArgs f 1 -> case len of 3 -> do _A <- go b <- go return (Lam mempty (Syntax.makeFunctionBinding "_" _A) b) 4 -> do x <- Decoding.decodeString if x == "_" then die "Non-standard encoding of a λ expression" else return () _A <- go b <- go return (Lam mempty (Syntax.makeFunctionBinding x _A) b) _ -> die ("Incorrect number of tokens used to encode a λ expression: " <> show len) 2 -> case len of 3 -> do _A <- go _B <- go return (Pi mempty "_" _A _B) 4 -> do x <- Decoding.decodeString if x == "_" then die "Non-standard encoding of a ∀ expression" else return () _A <- go _B <- go return (Pi mempty x _A _B) _ -> die ("Incorrect number of tokens used to encode a ∀ expression: " <> show len) 3 -> do opcode <- Decoding.decodeWord op <- case opcode of 0 -> return BoolOr 1 -> return BoolAnd 2 -> return BoolEQ 3 -> return BoolNE 4 -> return NaturalPlus 5 -> return NaturalTimes 6 -> return TextAppend 7 -> return ListAppend 8 -> return (Combine mempty Nothing) 9 -> return (Prefer mempty PreferFromSource) 10 -> return (CombineTypes mempty) 11 -> return ImportAlt 12 -> return (Equivalent mempty) 13 -> return RecordCompletion _ -> die ("Unrecognized operator code: " <> show opcode) l <- go r <- go return (op l r) 4 -> case len of 2 -> do _T <- go return (ListLit (Just (App List _T)) empty) _ -> do Decoding.decodeNull xs <- Data.Sequence.replicateA (len - 2) go return (ListLit Nothing xs) 5 -> do Decoding.decodeNull t <- go return (Some t) 6 -> do t <- go u <- go case len of 3 -> return (Merge t u Nothing) 4 -> do _T <- go return (Merge t u (Just _T)) _ -> die ("Incorrect number of tokens used to encode a `merge` expression: " <> show len) 7 -> do mapLength <- Decoding.decodeMapLen xTs <- replicateDecoder mapLength $ do x <- Decoding.decodeString _T <- go return (x, Syntax.makeRecordField _T) return (Record (Dhall.Map.fromList xTs)) 8 -> do mapLength <- Decoding.decodeMapLen xts <- replicateDecoder mapLength $ do x <- Decoding.decodeString t <- go return (x, Syntax.makeRecordField t) return (RecordLit (Dhall.Map.fromList xts)) 9 -> do t <- go x <- Decoding.decodeString return (Field t (Syntax.makeFieldSelection x)) 10 -> do t <- go xs <- case len of 3 -> do tokenType₂ <- Decoding.peekTokenType case tokenType₂ of TypeListLen -> do _ <- Decoding.decodeListLen _T <- go return (Right _T) TypeString -> do x <- Decoding.decodeString return (Left [x]) _ -> die ("Unexpected token type for projection: " <> show tokenType₂) _ -> do xs <- replicateDecoder (len - 2) Decoding.decodeString return (Left xs) return (Project t xs) 11 -> do mapLength <- Decoding.decodeMapLen xTs <- replicateDecoder mapLength $ do x <- Decoding.decodeString tokenType₂ <- Decoding.peekTokenType mT <- case tokenType₂ of TypeNull -> do Decoding.decodeNull return Nothing _ -> do _T <- go return (Just _T) return (x, mT) return (Union (Dhall.Map.fromList xTs)) 14 -> do t <- go l <- go r <- go return (BoolIf t l r) 15 -> do tokenType₂ <- Decoding.peekTokenType case tokenType₂ of TypeUInt -> do !n <- fromIntegral <$> Decoding.decodeWord return (NaturalLit n) TypeUInt64 -> do !n <- fromIntegral <$> Decoding.decodeWord64 return (NaturalLit n) TypeInteger -> do !n <- fromIntegral <$> Decoding.decodeInteger return (NaturalLit n) _ -> die ("Unexpected token type for Natural literal: " <> show tokenType₂) 16 -> do tokenType₂ <- Decoding.peekTokenType case tokenType₂ of TypeUInt -> do !n <- fromIntegral <$> Decoding.decodeWord return (IntegerLit n) TypeUInt64 -> do !n <- fromIntegral <$> Decoding.decodeWord64 return (IntegerLit n) TypeNInt -> do !n <- fromIntegral <$> Decoding.decodeNegWord return (IntegerLit $! (-1 - n)) TypeNInt64 -> do !n <- fromIntegral <$> Decoding.decodeNegWord64 return (IntegerLit $! (-1 - n)) TypeInteger -> do n <- Decoding.decodeInteger return (IntegerLit n) _ -> die ("Unexpected token type for Integer literal: " <> show tokenType₂) 18 -> do xys <- replicateDecoder ((len - 2) `quot` 2) $ do x <- Decoding.decodeString y <- go return (x, y) z <- Decoding.decodeString return (TextLit (Chunks xys z)) 19 -> do t <- go return (Assert t) 24 -> fmap Embed (decodeEmbed len) 25 -> do bindings <- replicateDecoder ((len - 2) `quot` 3) $ do x <- Decoding.decodeString tokenType₂ <- Decoding.peekTokenType mA <- case tokenType₂ of TypeNull -> do Decoding.decodeNull return Nothing _ -> do _A <- go return (Just (Nothing, _A)) a <- go return (Binding Nothing x Nothing mA Nothing a) b <- go return (foldr Let b bindings) 26 -> do t <- go _T <- go return (Annot t _T) 27 -> do t <- go mT <- case len of 2 -> return Nothing 3 -> do _T <- go return (Just _T) _ -> die ("Incorrect number of tokens used to encode a type annotation: " <> show len) return (ToMap t mT) 28 -> do _T <- go return (ListLit (Just _T) empty) 29 -> do l <- go n <- Decoding.decodeListLen let decodeWithComponent = do tokenType₂ <- Decoding.peekTokenType case tokenType₂ of TypeString -> do fmap WithLabel Decoding.decodeString _ -> do m <- Decoding.decodeInt case m of 0 -> return WithQuestion _ -> die ("Unexpected integer encoding a with expression: " <> show n) ks₀ <- replicateDecoder n decodeWithComponent ks₁ <- case NonEmpty.nonEmpty ks₀ of Nothing -> die "0 field labels in decoded with expression" Just ks₁ -> return ks₁ r <- go return (With l ks₁ r) 30 -> do _YYYY <- Decoding.decodeInt _MM <- Decoding.decodeInt _HH <- Decoding.decodeInt case Time.fromGregorianValid (fromIntegral _YYYY) _MM _HH of Nothing -> die "Invalid date" Just day -> return (DateLiteral day) 31 -> do hh <- Decoding.decodeInt mm <- Decoding.decodeInt tag₂ <- Decoding.decodeTag case tag₂ of 4 -> do return () _ -> do die ("Unexpected tag for decimal fraction: " <> show tag) n <- Decoding.decodeListLen case n of 2 -> do return () _ -> do die ("Invalid list length for decimal fraction: " <> show n) exponent <- Decoding.decodeInt tokenType₂ <- Decoding.peekTokenType mantissa <- case tokenType₂ of TypeUInt -> do fromIntegral <$> Decoding.decodeWord TypeUInt64 -> do fromIntegral <$> Decoding.decodeWord64 TypeNInt -> do !i <- fromIntegral <$> Decoding.decodeNegWord return (-1 - i) TypeNInt64 -> do !i <- fromIntegral <$> Decoding.decodeNegWord64 return (-1 - i) TypeInteger -> do Decoding.decodeInteger _ -> die ("Unexpected token type for mantissa: " <> show tokenType₂) let precision = fromIntegral (negate exponent) let ss = fromRational (mantissa % (10 ^ precision)) return (TimeLiteral (Time.TimeOfDay hh mm ss) precision) 32 -> do b <- Decoding.decodeBool _HH <- Decoding.decodeInt _MM <- Decoding.decodeInt let sign = if b then id else negate let minutes = sign (_HH * 60 + _MM) return (TimeZoneLiteral (Time.TimeZone minutes False "")) 34 -> do t <- go return (ShowConstructor t) _ -> die ("Unexpected tag: " <> show tag) _ -> die ("Unexpected tag type: " <> show tokenType₁) _ -> die ("Unexpected initial token: " <> show tokenType₀) encodeExpressionInternal :: (a -> Encoding) -> Expr Void a -> Encoding encodeExpressionInternal encodeEmbed = go where go e = case e of Var (V "_" n) -> Encoding.encodeInt n Var (V x n) -> Encoding.encodeListLen 2 <> Encoding.encodeString x <> Encoding.encodeInt n NaturalBuild -> Encoding.encodeUtf8ByteArray "Natural/build" NaturalFold -> Encoding.encodeUtf8ByteArray "Natural/fold" NaturalIsZero -> Encoding.encodeUtf8ByteArray "Natural/isZero" NaturalEven -> Encoding.encodeUtf8ByteArray "Natural/even" NaturalOdd -> Encoding.encodeUtf8ByteArray "Natural/odd" NaturalToInteger -> Encoding.encodeUtf8ByteArray "Natural/toInteger" NaturalShow -> Encoding.encodeUtf8ByteArray "Natural/show" NaturalSubtract -> Encoding.encodeUtf8ByteArray "Natural/subtract" IntegerToDouble -> Encoding.encodeUtf8ByteArray "Integer/toDouble" IntegerClamp -> Encoding.encodeUtf8ByteArray "Integer/clamp" IntegerNegate -> Encoding.encodeUtf8ByteArray "Integer/negate" IntegerShow -> Encoding.encodeUtf8ByteArray "Integer/show" DoubleShow -> Encoding.encodeUtf8ByteArray "Double/show" ListBuild -> Encoding.encodeUtf8ByteArray "List/build" ListFold -> Encoding.encodeUtf8ByteArray "List/fold" ListLength -> Encoding.encodeUtf8ByteArray "List/length" ListHead -> Encoding.encodeUtf8ByteArray "List/head" ListLast -> Encoding.encodeUtf8ByteArray "List/last" ListIndexed -> Encoding.encodeUtf8ByteArray "List/indexed" ListReverse -> Encoding.encodeUtf8ByteArray "List/reverse" Bool -> Encoding.encodeUtf8ByteArray "Bool" Optional -> Encoding.encodeUtf8ByteArray "Optional" None -> Encoding.encodeUtf8ByteArray "None" Natural -> Encoding.encodeUtf8ByteArray "Natural" Integer -> Encoding.encodeUtf8ByteArray "Integer" Double -> Encoding.encodeUtf8ByteArray "Double" Text -> Encoding.encodeUtf8ByteArray "Text" TextReplace -> Encoding.encodeUtf8ByteArray "Text/replace" TextShow -> Encoding.encodeUtf8ByteArray "Text/show" Date -> Encoding.encodeUtf8ByteArray "Date" Time -> Encoding.encodeUtf8ByteArray "Time" TimeZone -> Encoding.encodeUtf8ByteArray "TimeZone" List -> Encoding.encodeUtf8ByteArray "List" Const Type -> Encoding.encodeUtf8ByteArray "Type" Const Kind -> Encoding.encodeUtf8ByteArray "Kind" Const Sort -> Encoding.encodeUtf8ByteArray "Sort" a@App{} -> encodeListN (2 + length arguments) ( Encoding.encodeInt 0 : go function : map go arguments ) where (function, arguments) = unApply a Lam _ (FunctionBinding { functionBindingVariable = "_", functionBindingAnnotation = _A }) b -> encodeList3 (Encoding.encodeInt 1) (go _A) (go b) Lam _ (FunctionBinding { functionBindingVariable = x, functionBindingAnnotation = _A }) b -> encodeList4 (Encoding.encodeInt 1) (Encoding.encodeString x) (go _A) (go b) Pi _ "_" _A _B -> encodeList3 (Encoding.encodeInt 2) (go _A) (go _B) Pi _ x _A _B -> encodeList4 (Encoding.encodeInt 2) (Encoding.encodeString x) (go _A) (go _B) BoolOr l r -> encodeOperator 0 l r BoolAnd l r -> encodeOperator 1 l r BoolEQ l r -> encodeOperator 2 l r BoolNE l r -> encodeOperator 3 l r NaturalPlus l r -> encodeOperator 4 l r NaturalTimes l r -> encodeOperator 5 l r TextAppend l r -> encodeOperator 6 l r ListAppend l r -> encodeOperator 7 l r Combine _ _ l r -> encodeOperator 8 l r Prefer _ _ l r -> encodeOperator 9 l r CombineTypes _ l r -> encodeOperator 10 l r ImportAlt l r -> encodeOperator 11 l r Equivalent _ l r -> encodeOperator 12 l r RecordCompletion l r -> encodeOperator 13 l r ListLit _T₀ xs | null xs -> encodeList2 (Encoding.encodeInt label) _T₁ | otherwise -> encodeListN (2 + length xs) ( Encoding.encodeInt 4 : Encoding.encodeNull : map go (Data.Foldable.toList xs) ) where (label, _T₁) = case _T₀ of Nothing -> (4 , Encoding.encodeNull) Just (App List t) -> (4 , go t ) Just t -> (28, go t ) Some t -> encodeList3 (Encoding.encodeInt 5) Encoding.encodeNull (go t) Merge t u Nothing -> encodeList3 (Encoding.encodeInt 6) (go t) (go u) Merge t u (Just _T) -> encodeList4 (Encoding.encodeInt 6) (go t) (go u) (go _T) Record xTs -> encodeList2 (Encoding.encodeInt 7) (encodeMapWith (go . recordFieldValue) xTs) RecordLit xts -> encodeList2 (Encoding.encodeInt 8) (encodeMapWith (go. recordFieldValue) xts) Field t (Syntax.fieldSelectionLabel -> x) -> encodeList3 (Encoding.encodeInt 9) (go t) (Encoding.encodeString x) Project t (Left xs) -> encodeListN (2 + length xs) ( Encoding.encodeInt 10 : go t : map Encoding.encodeString xs ) Project t (Right _T) -> encodeList3 (Encoding.encodeInt 10) (go t) (encodeList1 (go _T)) Union xTs -> encodeList2 (Encoding.encodeInt 11) (encodeMapWith encodeValue xTs) where encodeValue Nothing = Encoding.encodeNull encodeValue (Just _T) = go _T BoolLit b -> Encoding.encodeBool b BoolIf t l r -> encodeList4 (Encoding.encodeInt 14) (go t) (go l) (go r) NaturalLit n -> encodeList2 (Encoding.encodeInt 15) (Encoding.encodeInteger (fromIntegral n)) IntegerLit n -> encodeList2 (Encoding.encodeInt 16) (Encoding.encodeInteger (fromIntegral n)) DoubleLit (DhallDouble n64) | useHalf -> Encoding.encodeFloat16 n32 | useFloat -> Encoding.encodeFloat n32 | otherwise -> Encoding.encodeDouble n64 where n32 = double2Float n64 n16 = toHalf n32 useFloat = n64 == float2Double n32 useHalf = n64 == (float2Double $ fromHalf n16) -- Fast path for the common case of an uninterpolated string TextLit (Chunks [] z) -> encodeList2 (Encoding.encodeInt 18) (Encoding.encodeString z) TextLit (Chunks xys z) -> encodeListN (2 + 2 * length xys) ( Encoding.encodeInt 18 : concatMap encodePair xys ++ [ Encoding.encodeString z ] ) where encodePair (x, y) = [ Encoding.encodeString x, go y ] Assert t -> encodeList2 (Encoding.encodeInt 19) (go t) Embed x -> encodeEmbed x Let a₀ b₀ -> encodeListN (2 + 3 * length as) ( Encoding.encodeInt 25 : concatMap encodeBinding (toList as) ++ [ go b₁ ] ) where MultiLet as b₁ = Syntax.multiLet a₀ b₀ encodeBinding (Binding _ x _ mA₀ _ a) = [ Encoding.encodeString x , mA₁ , go a ] where mA₁ = case mA₀ of Nothing -> Encoding.encodeNull Just (_, _A) -> go _A Annot t _T -> encodeList3 (Encoding.encodeInt 26) (go t) (go _T) ToMap t Nothing -> encodeList2 (Encoding.encodeInt 27) (go t) ToMap t (Just _T) -> encodeList3 (Encoding.encodeInt 27) (go t) (go _T) With l ks r -> encodeList4 (Encoding.encodeInt 29) (go l) (encodeList (fmap encodeWithComponent ks)) (go r) where encodeWithComponent WithQuestion = Encoding.encodeInt 0 encodeWithComponent (WithLabel k ) = Encoding.encodeString k DateLiteral day -> encodeList4 (Encoding.encodeInt 30) (Encoding.encodeInt (fromInteger _YYYY)) (Encoding.encodeInt _MM) (Encoding.encodeInt _DD) where (_YYYY, _MM, _DD) = Time.toGregorian day TimeLiteral (Time.TimeOfDay hh mm ss) precision -> encodeList4 (Encoding.encodeInt 31) (Encoding.encodeInt hh) (Encoding.encodeInt mm) ( Encoding.encodeTag 4 <> encodeList2 (Encoding.encodeInt exponent) encodedMantissa ) where exponent = negate (fromIntegral precision) mantissa :: Integer mantissa = truncate (ss * 10 ^ precision) encodedMantissa | fromIntegral (minBound :: Int) <= mantissa && mantissa <= fromIntegral (maxBound :: Int) = Encoding.encodeInt (fromInteger mantissa) | otherwise = Encoding.encodeInteger mantissa TimeZoneLiteral (Time.TimeZone minutes _ _) -> encodeList4 (Encoding.encodeInt 32) (Encoding.encodeBool sign) (Encoding.encodeInt _HH) (Encoding.encodeInt _MM) where sign = 0 <= minutes (_HH, _MM) = abs minutes `divMod` 60 ShowConstructor t -> encodeList2 (Encoding.encodeInt 34) (go t) Note _ b -> go b encodeOperator n l r = encodeList4 (Encoding.encodeInt 3) (Encoding.encodeInt n) (go l) (go r) encodeMapWith encodeValue m = Encoding.encodeMapLen (fromIntegral (Dhall.Map.size m)) <> foldMap encodeKeyValue (Dhall.Map.toList (Dhall.Map.sort m)) where encodeKeyValue (k, v) = Encoding.encodeString k <> encodeValue v encodeList1 :: Encoding -> Encoding encodeList1 a = Encoding.encodeListLen 1 <> a {-# INLINE encodeList1 #-} encodeList2 :: Encoding -> Encoding -> Encoding encodeList2 a b = Encoding.encodeListLen 2 <> a <> b {-# INLINE encodeList2 #-} encodeList3 :: Encoding -> Encoding -> Encoding -> Encoding encodeList3 a b c = Encoding.encodeListLen 3 <> a <> b <> c {-# INLINE encodeList3 #-} encodeList4 :: Encoding -> Encoding -> Encoding -> Encoding -> Encoding encodeList4 a b c d = Encoding.encodeListLen 4 <> a <> b <> c <> d {-# INLINE encodeList4 #-} encodeListN :: Foldable f => Int -> f Encoding -> Encoding encodeListN len xs = Encoding.encodeListLen (fromIntegral len) <> Foldable.fold xs {-# INLINE encodeListN #-} encodeList :: Foldable f => f Encoding -> Encoding encodeList xs = encodeListN (length xs) xs {-# INLINE encodeList #-} decodeImport :: Int -> Decoder s Import decodeImport len = do let die message = fail ("Dhall.Binary.decodeImport: " <> message) tokenType₀ <- Decoding.peekTokenType hash <- case tokenType₀ of TypeNull -> do Decoding.decodeNull return Nothing TypeBytes -> do bytes <- Decoding.decodeBytes let (prefix, suffix) = Data.ByteString.splitAt 2 bytes case prefix of "\x12\x20" -> return () _ -> die ("Unrecognized multihash prefix: " <> show prefix) case Dhall.Crypto.sha256DigestFromByteString suffix of Nothing -> die ("Invalid sha256 digest: " <> show bytes) Just digest -> return (Just digest) _ -> die ("Unexpected hash token: " <> show tokenType₀) m <- Decoding.decodeWord importMode <- case m of 0 -> return Code 1 -> return RawText 2 -> return Location _ -> die ("Unexpected code for import mode: " <> show m) let remote scheme = do tokenType₁ <- Decoding.peekTokenType headers <- case tokenType₁ of TypeNull -> do Decoding.decodeNull return Nothing _ -> do headers <- decodeExpressionInternal decodeImport return (Just headers) authority <- Decoding.decodeString paths <- replicateDecoder (len - 8) Decoding.decodeString file <- Decoding.decodeString tokenType₂ <- Decoding.peekTokenType query <- case tokenType₂ of TypeNull -> do Decoding.decodeNull return Nothing _ -> fmap Just Decoding.decodeString let components = reverse paths let directory = Directory {..} let path = File {..} return (Remote (URL {..})) let local prefix = do paths <- replicateDecoder (len - 5) Decoding.decodeString file <- Decoding.decodeString let components = reverse paths let directory = Directory {..} return (Local prefix (File {..})) let missing = return Missing let env = do x <- Decoding.decodeString return (Env x) n <- Decoding.decodeWord importType <- case n of 0 -> remote HTTP 1 -> remote HTTPS 2 -> local Absolute 3 -> local Here 4 -> local Parent 5 -> local Home 6 -> env 7 -> missing _ -> fail ("Unrecognized import type code: " <> show n) let importHashed = ImportHashed {..} return (Import {..}) encodeImport :: Import -> Encoding encodeImport import_ = case importType of Remote (URL { scheme = scheme₀, .. }) -> encodeList ( prefix ++ [ Encoding.encodeInt scheme₁ , using , Encoding.encodeString authority ] ++ map Encoding.encodeString (reverse components) ++ [ Encoding.encodeString file ] ++ [ case query of Nothing -> Encoding.encodeNull Just q -> Encoding.encodeString q ] ) where using = case headers of Nothing -> Encoding.encodeNull Just h -> encodeExpressionInternal encodeImport (Syntax.denote h) scheme₁ = case scheme₀ of HTTP -> 0 HTTPS -> 1 File{..} = path Directory {..} = directory Local prefix₀ path -> encodeList ( prefix ++ [ Encoding.encodeInt prefix₁ ] ++ map Encoding.encodeString components₁ ++ [ Encoding.encodeString file ] ) where File{..} = path Directory{..} = directory prefix₁ = case prefix₀ of Absolute -> 2 Here -> 3 Parent -> 4 Home -> 5 components₁ = reverse components Env x -> encodeList (prefix ++ [ Encoding.encodeInt 6, Encoding.encodeString x ]) Missing -> encodeList (prefix ++ [ Encoding.encodeInt 7 ]) where prefix = [ Encoding.encodeInt 24, h, m ] where h = case hash of Nothing -> Encoding.encodeNull Just digest -> Encoding.encodeBytes ("\x12\x20" <> Dhall.Crypto.unSHA256Digest digest) m = Encoding.encodeInt (case importMode of Code -> 0; RawText -> 1; Location -> 2;) Import{..} = import_ ImportHashed{..} = importHashed decodeVoid :: Int -> Decoder s Void decodeVoid _ = fail "Dhall.Binary.decodeVoid: Cannot decode an uninhabited type" encodeVoid :: Void -> Encoding encodeVoid = absurd instance Serialise (Expr Void Void) where encode = encodeExpressionInternal encodeVoid decode = decodeExpressionInternal decodeVoid instance Serialise (Expr Void Import) where encode = encodeExpressionInternal encodeImport decode = decodeExpressionInternal decodeImport -- | Encode a Dhall expression as a CBOR-encoded `ByteString` encodeExpression :: Serialise (Expr Void a) => Expr Void a -> ByteString encodeExpression = Serialise.serialise -- | Decode a Dhall expression from a CBOR `Codec.CBOR.Term.Term` decodeExpression :: Serialise (Expr s a) => ByteString -> Either DecodingFailure (Expr s a) decodeExpression bytes = case decodeWithoutVersion <|> decodeWithVersion of Just expression -> Right expression Nothing -> Left (CBORIsNotDhall bytes) where adapt (Right ("", x)) = Just x adapt _ = Nothing decode' = decodeWith55799Tag decode -- This is the behavior specified by the standard decodeWithoutVersion = adapt (Read.deserialiseFromBytes decode' bytes) -- tag to ease the migration decodeWithVersion = adapt (Read.deserialiseFromBytes decodeWithTag bytes) where decodeWithTag = do 2 <- Decoding.decodeListLen version <- Decoding.decodeString -- "_" has never been a valid version string, and this ensures that -- we don't interpret `[ "_", 0 ]` as the expression `_` (encoded as -- `0`) tagged with a version string of `"_"` if (version == "_") then fail "Dhall.Binary.decodeExpression: \"_\" is not a valid version string" else return () decode' decodeWith55799Tag :: Decoder s a -> Decoder s a decodeWith55799Tag decoder = do tokenType <- Decoding.peekTokenType case tokenType of TypeTag -> do w <- Decoding.decodeTag if w /= 55799 then fail ("Dhall.Binary.decodeWith55799Tag: Unexpected tag: " <> show w) else return () decoder _ -> decoder {-| This indicates that a given CBOR-encoded `ByteString` did not correspond to a valid Dhall expression -} newtype DecodingFailure = CBORIsNotDhall ByteString deriving (Eq) instance Exception DecodingFailure _ERROR :: String _ERROR = "\ESC[1;31mError\ESC[0m" instance Show DecodingFailure where show (CBORIsNotDhall bytes) = _ERROR <> ": Cannot decode CBOR to Dhall\n" <> "\n" <> "The following bytes do not encode a valid Dhall expression\n" <> "\n" <> "↳ 0x" <> concatMap toHex (Data.ByteString.Lazy.unpack bytes) <> "\n" where toHex = Printf.printf "%02x " -- | This specialized version of 'Control.Monad.replicateM' reduces -- decoding timings by roughly 10%. replicateDecoder :: Int -> Decoder s a -> Decoder s [a] replicateDecoder n0 decoder = go n0 where go n | n <= 0 = pure [] | otherwise = do x <- decoder xs <- go (n - 1) pure (x:xs)
Gabriel439/Haskell-Dhall-Library
dhall/src/Dhall/Binary.hs
bsd-3-clause
47,233
977
14
24,014
9,253
4,965
4,288
988
105
-------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.Functions -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- All raw functions from the -- <http://www.opengl.org/registry/ OpenGL registry>. -- -------------------------------------------------------------------------------- module Graphics.GL.Functions ( module Graphics.GL.Functions.F01, module Graphics.GL.Functions.F02, module Graphics.GL.Functions.F03, module Graphics.GL.Functions.F04, module Graphics.GL.Functions.F05, module Graphics.GL.Functions.F06, module Graphics.GL.Functions.F07, module Graphics.GL.Functions.F08, module Graphics.GL.Functions.F09, module Graphics.GL.Functions.F10, module Graphics.GL.Functions.F11, module Graphics.GL.Functions.F12, module Graphics.GL.Functions.F13, module Graphics.GL.Functions.F14, module Graphics.GL.Functions.F15, module Graphics.GL.Functions.F16, module Graphics.GL.Functions.F17, module Graphics.GL.Functions.F18, module Graphics.GL.Functions.F19, module Graphics.GL.Functions.F20, module Graphics.GL.Functions.F21, module Graphics.GL.Functions.F22, module Graphics.GL.Functions.F23, module Graphics.GL.Functions.F24, module Graphics.GL.Functions.F25, module Graphics.GL.Functions.F26, module Graphics.GL.Functions.F27, module Graphics.GL.Functions.F28, module Graphics.GL.Functions.F29, module Graphics.GL.Functions.F30, module Graphics.GL.Functions.F31, module Graphics.GL.Functions.F32, module Graphics.GL.Functions.F33 ) where import Graphics.GL.Functions.F01 import Graphics.GL.Functions.F02 import Graphics.GL.Functions.F03 import Graphics.GL.Functions.F04 import Graphics.GL.Functions.F05 import Graphics.GL.Functions.F06 import Graphics.GL.Functions.F07 import Graphics.GL.Functions.F08 import Graphics.GL.Functions.F09 import Graphics.GL.Functions.F10 import Graphics.GL.Functions.F11 import Graphics.GL.Functions.F12 import Graphics.GL.Functions.F13 import Graphics.GL.Functions.F14 import Graphics.GL.Functions.F15 import Graphics.GL.Functions.F16 import Graphics.GL.Functions.F17 import Graphics.GL.Functions.F18 import Graphics.GL.Functions.F19 import Graphics.GL.Functions.F20 import Graphics.GL.Functions.F21 import Graphics.GL.Functions.F22 import Graphics.GL.Functions.F23 import Graphics.GL.Functions.F24 import Graphics.GL.Functions.F25 import Graphics.GL.Functions.F26 import Graphics.GL.Functions.F27 import Graphics.GL.Functions.F28 import Graphics.GL.Functions.F29 import Graphics.GL.Functions.F30 import Graphics.GL.Functions.F31 import Graphics.GL.Functions.F32 import Graphics.GL.Functions.F33
haskell-opengl/OpenGLRaw
src/Graphics/GL/Functions.hs
bsd-3-clause
2,781
0
5
271
518
383
135
67
0
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.EXT.SemaphoreFd -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.EXT.SemaphoreFd ( -- * Extension Support glGetEXTSemaphoreFd, gl_EXT_semaphore_fd, -- * Enums pattern GL_HANDLE_TYPE_OPAQUE_FD_EXT, -- * Functions glImportSemaphoreFdEXT ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/EXT/SemaphoreFd.hs
bsd-3-clause
723
0
5
101
57
43
14
9
0
-- usage: runhaskell CopyToUsbDrive.hs live-image.iso /dev/sdX -- -- This will copy the live-image.iso to your USB thumb drive. It will further -- add a partition on your bootable USB thumb drive that can be used by -- Windows. Therefore it will first remove the existing Live-Linux partition -- then create a new partition behind the Live-Linux partition. And then will -- recreate the Live-Linux partition with the same geometry as before. -- -- The resulting layout looks something like this: -- sdx2 live-linux --- (size of live-image.iso) -- sdx3 persistence ext4 ~ 1 GB -- sdx1 windata fat32 (the remaining space) import Control.Applicative ((<$>)) import Control.Concurrent (threadDelay) import Control.Monad (void, when) import Data.Maybe (fromJust) import Data.String.Utils (split) import System.Environment (getArgs) import System.Process (readProcess, readProcessWithExitCode) main :: IO () main = do [iso, device] <- getArgs putStrLn $ "This will overwrite all data on " ++ device ++ "!" putStrLn "Do you really want to continue? yes/[no]" isOk <- getLine when (isOk /= "yes") $ error "aborted by user" oldGeom <- backupGeometry device putStrLn "Copy image to device ..." dd iso device sync putStrLn "Create extra partitions ..." (disk, partitions) <- getDiskLayout device addPartition oldGeom disk $ partitions !! 0 putStrLn "Done!" where dd iso device = void $ readProcess "/bin/dd" ["bs=4096", "if=" ++ iso ,"of=" ++ device] "" sync = void $ readProcess "/bin/sync" [] "" backupGeometry :: String -> IO (Maybe [Partition]) backupGeometry device = do (_, partitions) <- getDiskLayout device return $ get partitions where get ps | length ps < 3 = Nothing get (p:ps) | partNumber p == 2 = Just ps | otherwise = Nothing getDiskLayout:: String -> IO (Disk, [Partition]) getDiskLayout device = do out <- map (split ":") <$> lines <$> parted' device ["print"] return ( toDisk $ out !! 1 , map toPart $ drop 2 out ) where readS a | last a == 's' = read $ init a toPart (number : start : end : _ : fs : _) = Partition (read number) (readS start) (readS end) fs toDisk (_ : secCnt : _ : secSize : _ : partTable : _) = Disk device (readS secCnt) (read secSize) partTable addPartition ::Maybe [Partition] -> Disk -> Partition -> IO () addPartition oldGeom disk partition = do when toSmall $ error "error: target device to small" _ <- parted device ["rm", "1"] _ <- parted device ["mkpart", "primary", "fat32", show start1, show end1] _ <- parted device ["mkpart", "primary", fs2, show start2, show end2] _ <- parted device ["mkpart", "primary", "ext4", show start3, show end3] _ <- parted device ["set", "2", "boot", "on"] _ <- parted device ["set", "2", "hidden", "on"] if reuseImpossible then do threadDelay $ 2*1000*1000 mkfs (device ++ "1") "vfat" ["-F", "32", "-n", "WINDATA"] mkfs (device ++ "3") "ext4" ["-L", "persistence"] addPersistence $ device ++ "3" else putStrLn "Re-using existing partitions!" where mbyte = 10^6 `quot` (sectorSize disk) device = devicePath disk start2 = partStart partition end2 = partEnd partition reuseImpossible = case oldGeom of Nothing -> True Just a -> end2 >= partStart (head a) start3 = if reuseImpossible then end2 + 200 * mbyte -- leave a 200 MB gap else partStart $ (fromJust oldGeom) !! 0 end3 = if reuseImpossible then start3 + 1000 * mbyte else partEnd $ (fromJust oldGeom) !! 0 start1 = if reuseImpossible then end3 + 1 else partStart $ (fromJust oldGeom) !! 1 end1 = if reuseImpossible then (sectorCount disk) - 1 else partEnd $ (fromJust oldGeom) !! 1 fs2 = fileSystem partition toSmall = (end1 - start1) < 10 * mbyte parted:: String -> [String] -> IO String parted device args = readProcess "/sbin/parted" (["-s", "-m", device, "unit", "s"] ++ args) "" parted':: String -> [String] -> IO String parted' device args = do (_, stdout, _) <- readProcessWithExitCode "/sbin/parted" (["-s", "-m", device, "unit", "s"] ++ args) "" return stdout mkfs:: String -> String -> [String] -> IO () mkfs device fsType args = void $ readProcess "/sbin/mkfs" (["-t", fsType] ++ args ++ [device]) "" addPersistence :: String -> IO () addPersistence device = do mkdir ["-p", "./.mnt"] mount [device, "./.mnt"] writeFile "./.mnt/persistence.conf" "/home union\n" umount ["./.mnt"] where mount args = void $ readProcess "/bin/mount" args "" umount args = void $ readProcess "/bin/umount" args "" mkdir args = void $ readProcess "/bin/mkdir" args "" data Partition = Partition { partNumber :: Int , partStart :: Integer , partEnd :: Integer , fileSystem :: String } deriving (Show) data Disk = Disk { devicePath :: String , sectorCount :: Integer , sectorSize :: Integer , partitionTable :: String } deriving (Show)
KaiHa/debian-live
CopyToUsbDrive.hs
bsd-3-clause
5,652
16
19
1,769
1,627
834
793
110
7
module Plot.Utils where import Data.Colour import Data.Colour.Names import Control.Lens import Data.Default.Class import Graphics.Rendering.Chart line_e, line_t, line_d :: LineStyle line_e = line_color .~ withOpacity red 0.8 $ line line_t = line_color .~ withOpacity blue 0.8 $ line line_d = line_color .~ withOpacity green 0.8 $ line line :: LineStyle line = line_width .~ 1.8 $ def lineWith :: LineStyle -> String -> [(Double, a)] -> PlotLines Double a lineWith ls txt vs = plot_lines_style .~ ls $ plot_lines_values .~ [vs] $ plot_lines_title .~ txt $ def theoreticalWith :: [(Double, Double)] -> PlotLines Double Double theoreticalWith = lineWith line_t "Theoretical" empiricalWith :: [(Double, a)] -> PlotLines Double a empiricalWith = lineWith line_e "Empirical" differenceWith :: [(Double, Double)] -> PlotLines Double Double differenceWith = lineWith line_d "Difference" stdLayout :: (PlotValue x, PlotValue y) => String -> [Either (Plot x y) (Plot x y)] -> LayoutLR x y y stdLayout title plots = layoutlr_title .~ title $ layoutlr_background .~ solidFillStyle (opaque white) $ layoutlr_plots .~ plots $ layoutlr_foreground .~ opaque black $ def
finlay/random-dist
test/Plot/Utils.hs
bsd-3-clause
1,265
0
13
280
397
213
184
33
1
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell import Prelude hiding (snd, fst) data ST a s = S (s -> (a, s)) [lq| data ST a s <pre :: s -> Prop, post :: a -> s -> Prop> = S (ys::(x:s<pre> -> ((a, s)<post>))) |] [lq| returnST :: forall <pre :: s -> Prop, post :: a -> s -> Prop>. xState:a -> ST <{v:s<post xState>| true}, post> a s |] returnST :: a -> ST a s returnST x = S $ \s -> (x, s) [lq| bindST :: forall <pbind :: s -> Prop, qbind :: a -> s -> Prop, rbind :: b -> s -> Prop>. ST <pbind, qbind> a s -> (xbind:a -> ST <{v:s<qbind xbind> | true}, rbind> b s) -> ST <pbind, rbind> b s |] bindST :: ST a s -> (a -> ST b s) -> ST b s bindST (S m) k = S $ \s -> let (a, s') = m s in apply (k a) s' [lq| apply :: forall <p :: s -> Prop, q :: a -> s -> Prop>. ST <p, q> a s -> s<p> -> (a, s)<q> |] apply :: ST a s -> s -> (a, s) apply (S f) s = f s
spinda/liquidhaskell
tests/gsoc15/unknown/pos/State.hs
bsd-3-clause
947
0
11
309
241
133
108
14
1
module FireLogic where import Data.List (find) import Data.Maybe (isNothing, fromMaybe) import Types onlyShallow :: [RequestParameter] -> Bool onlyShallow opts | (shallowIn && (length opts) == 1) || (not shallowIn) = True | otherwise = error "Shallow must be the only parameter" where shallowIn = elem Shallow (map fst opts) -- This is just... wrong! --onlyGets :: [RequestParameter] -> Bool --onlyGets opts | and (map (\x -> elem (fst x) getOnly) opts) = True -- | otherwise = error "Some parameters are not GET parameters" -- where getOnly = [Shallow, Callback, Format, Download, Print] -- Can orderBy and limits be used with POST \ PUT etc.? onlyGet :: [RequestParameter] -> Bool onlyGet opts | or (map (\x -> elem (fst x) getOnly) opts) = True | otherwise = error "Some parameters are only GET parameters" where getOnly = [Shallow, Callback, Format, Download] printValue :: [RequestParameter] -> Bool printValue opts | (isNothing a) || (snda == "pretty") || (snda == "silent") = True | otherwise = error "Print argument not recognized: it should be either pretty or silent" where a = find (\(a,b) -> a == Print) opts snda = snd (fromMaybe (Print, "") a) printValueSilent :: [RequestParameter] -> Bool printValueSilent opts | (isNothing a) || (snda == "pretty") = True | otherwise = error "Print argument not recognized or not allowed for this verb" where a = find (\(a,b) -> a == Print) opts snda = snd (fromMaybe (Print, "") a) orderByValue :: [RequestParameter] -> Bool orderByValue opts | (isNothing a) || (snda == "$key") || (snda == "$value") || (snda == "$priority") = True | otherwise = error "Order argument not recognized: it should be either $key, $value or $priority" where a = find (\(a,b) -> a == OrderBy) opts snda = snd (fromMaybe (OrderBy, "") a) anyEmpty :: [RequestParameter] -> Bool anyEmpty opts | and $ map (\(a,b) -> b /= "") opts = True | otherwise = error "Some arguments are empty" validateGet :: [RequestParameter] -> Bool validateGet xs = all ($ xs) [anyEmpty, orderByValue, printValue, onlyShallow] validatePost :: [RequestParameter] -> Bool validatePost xs = all ($ xs) [anyEmpty, onlyGet, printValue] validateDelete :: [RequestParameter] -> Bool validateDelete xs = all ($ xs) [anyEmpty, printValueSilent] validatePut :: [RequestParameter] -> Bool validatePut xs = all ($ xs) [anyEmpty] validatePatch :: [RequestParameter] -> Bool validatePatch xs = all ($ xs) [anyEmpty]
sphaso/firebase-haskell-client
src/FireLogic.hs
bsd-3-clause
2,743
0
15
727
805
433
372
40
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE QuasiQuotes #-} module Tests.Mitsuba.Class where import Mitsuba.Class import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.TH import Data.Text (Text) import Test.HUnit import GHC.Generics import Data.List import Text.Blaze import Mitsuba.XML import Text.InterpolatedString.Perl6 import Text.Blaze.Renderer.Pretty default (Text, Integer, Double) tests :: TestTree tests = $(testGroupGenerator) case_conNameToType_1 = conNameToType "Foo" "FBar" @?= "bar" case_conNameToType_2 = conNameToType "FooBar" "FBBar" @?= "bar" case_selNameToType_1 = selNameToType "Foo" "fooThing" @?= "thing" case_selNameToType_2 = selNameToType "FooType" "fooTypeThing" @?= "thing" data Foo = FType1 Type1 | FType2 Type2 deriving (Show, Eq, Generic) data FooRecord = FooRecord { fooRecordThing1 :: Type1 , fooRecordThing2 :: Type2 } deriving (Show, Eq, Generic) instance ToXML FooRecord data Forwardable = Foo1 Foo | Foo2 FooRecord deriving (Show, Eq, Generic) instance ToXML Forwardable where toXML = forwardToXML data Type1 = Type1 deriving (Show, Eq, Generic) data Type2 = Type2 deriving (Show, Eq, Generic) instance ToXML Type1 where toXML xs Type1 = foldl' (!) (ct "type1") xs instance ToXML Type2 where toXML xs Type2 = foldl' (!) (ct "type2") xs instance ToXML Foo case_Type1_toXML = renderMarkup (toXML [a "value" "hey"] Type1) @?= [q|<type1 value="hey" /> |] case_Type2_toXML = renderMarkup (toXML [a "value" "hey"] Type2) @?= [q|<type2 value="hey" /> |] case_Foo_XML = renderMarkup (toXML [] $ FType1 Type1) @?= [q|<foo type="type1"> <type1 /> </foo> |] case_FooRecord_XML = renderMarkup (toXML [] $ FooRecord Type1 Type2) @?= [q|<foorecord> <type1 name="thing1" /> <type2 name="thing2" /> </foorecord> |] case_forwardToXML_0 = renderMarkup (toXML [] $ Foo1 $ FType1 Type1) @?= [q|<foo type="type1"> <type1 /> </foo> |] case_forwardToXML_1 = renderMarkup (toXML [] $ Foo2 $ FooRecord Type1 Type2) @?= [q|<foorecord> <type1 name="thing1" /> <type2 name="thing2" /> </foorecord> |] case_Double_toXML = renderMarkup (toXML [] (1.0 :: Double)) @?= [q|<float value="1.0" /> |]
jfischoff/hs-mitsuba
tests/Tests/Mitsuba/Class.hs
bsd-3-clause
2,328
0
11
436
626
350
276
-1
-1
-- | -- Module : $Header$ -- Copyright : (c) 2013-2014 Galois, Inc. -- License : BSD3 -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- This module defines natural numbers with an additional infinity -- element, and various arithmetic operators on them. {-# LANGUAGE Safe #-} module Cryptol.TypeCheck.Solver.InfNat where -- | Natural numbers with an infinity element data Nat' = Nat Integer | Inf deriving (Show,Eq,Ord) fromNat :: Nat' -> Maybe Integer fromNat n' = case n' of Nat i -> Just i _ -> Nothing nAdd :: Nat' -> Nat' -> Nat' nAdd Inf _ = Inf nAdd _ Inf = Inf nAdd (Nat x) (Nat y) = Nat (x + y) {-| Some algerbaic properties of interest: > 1 * x = x > x * (y * z) = (x * y) * z > 0 * x = 0 > x * y = y * x > x * (a + b) = x * a + x * b -} nMul :: Nat' -> Nat' -> Nat' nMul (Nat 0) _ = Nat 0 nMul _ (Nat 0) = Nat 0 nMul Inf _ = Inf nMul _ Inf = Inf nMul (Nat x) (Nat y) = Nat (x * y) {-| Some algeibraic properties of interest: > x ^ 0 = 1 > x ^ (n + 1) = x * (x ^ n) > x ^ (m + n) = (x ^ m) * (x ^ n) > x ^ (m * n) = (x ^ m) ^ n -} nExp :: Nat' -> Nat' -> Nat' nExp _ (Nat 0) = Nat 1 nExp Inf _ = Inf nExp (Nat 0) Inf = Nat 0 nExp (Nat 1) Inf = Nat 1 nExp (Nat _) Inf = Inf nExp (Nat x) (Nat y) = Nat (x ^ y) nMin :: Nat' -> Nat' -> Nat' nMin Inf x = x nMin x Inf = x nMin (Nat x) (Nat y) = Nat (min x y) nMax :: Nat' -> Nat' -> Nat' nMax Inf _ = Inf nMax _ Inf = Inf nMax (Nat x) (Nat y) = Nat (max x y) {- | @nSub x y = Just z@ iff @z@ is the unique value such that @Add y z = Just x@. -} nSub :: Nat' -> Nat' -> Maybe Nat' nSub Inf (Nat _) = Just Inf nSub (Nat x) (Nat y) | x >= y = Just (Nat (x - y)) nSub _ _ = Nothing {- | Rounds down. > y * q + r = x > x / y = q with remainder r > 0 <= r && r < y We don't allow `Inf` in the first argument for two reasons: 1. It matches the behavior of `nMod`, 2. The well-formedness constraints can be expressed as a conjunction. -} nDiv :: Nat' -> Nat' -> Maybe Nat' nDiv _ (Nat 0) = Nothing nDiv Inf _ = Nothing nDiv (Nat x) (Nat y) = Just (Nat (div x y)) nDiv (Nat _) Inf = Just (Nat 0) nMod :: Nat' -> Nat' -> Maybe Nat' nMod _ (Nat 0) = Nothing nMod Inf _ = Nothing nMod (Nat x) (Nat y) = Just (Nat (mod x y)) nMod (Nat x) Inf = Just (Nat x) -- inf * 0 + x = 0 + x -- | Rounds up. -- @lg2 x = y@, iff @y@ is the smallest number such that @x <= 2 ^ y@ nLg2 :: Nat' -> Nat' nLg2 Inf = Inf nLg2 (Nat 0) = Nat 0 nLg2 (Nat n) = case genLog n 2 of Just (x,exact) | exact -> Nat x | otherwise -> Nat (x + 1) Nothing -> error "genLog returned Nothing" -- | @nWidth n@ is number of bits needed to represent all numbers -- from 0 to n, inclusive. @nWidth x = nLg2 (x + 1)@. nWidth :: Nat' -> Nat' nWidth Inf = Inf nWidth (Nat 0) = Nat 0 nWidth (Nat n) = case genLog n 2 of Just (x,_) -> Nat (x + 1) Nothing -> error "genLog returned Nothing" nLenFromThen :: Nat' -> Nat' -> Nat' -> Maybe Nat' nLenFromThen a@(Nat x) b@(Nat y) (Nat w) | y > x = nLenFromThenTo a b (Nat (2^w - 1)) | y < x = nLenFromThenTo a b (Nat 0) nLenFromThen _ _ _ = Nothing nLenFromThenTo :: Nat' -> Nat' -> Nat' -> Maybe Nat' nLenFromThenTo (Nat x) (Nat y) (Nat z) | step /= 0 = let len = div dist step + 1 in Just $ Nat $ max 0 (if x > y then if z > x then 0 else len else if z < x then 0 else len) where step = abs (x - y) dist = abs (x - z) nLenFromThenTo _ _ _ = Nothing -------------------------------------------------------------------------------- -- | Compute the logarithm of a number in the given base, rounded down to the -- closest integer. The boolean indicates if we the result is exact -- (i.e., True means no rounding happened, False means we rounded down). -- The logarithm base is the second argument. genLog :: Integer -> Integer -> Maybe (Integer, Bool) genLog x 0 = if x == 1 then Just (0, True) else Nothing genLog _ 1 = Nothing genLog 0 _ = Nothing genLog x base = Just (exactLoop 0 x) where exactLoop s i | i == 1 = (s,True) | i < base = (s,False) | otherwise = let s1 = s + 1 in s1 `seq` case divMod i base of (j,r) | r == 0 -> exactLoop s1 j | otherwise -> (underLoop s1 j, False) underLoop s i | i < base = s | otherwise = let s1 = s + 1 in s1 `seq` underLoop s1 (div i base)
dylanmc/cryptol
src/Cryptol/TypeCheck/Solver/InfNat.hs
bsd-3-clause
4,834
0
17
1,653
1,630
824
806
92
4
{-# LANGUAGE DeriveDataTypeable #-} module SayAnnNames (plugin, SomeAnn(..)) where import GhcPlugins import Control.Monad (unless) import Data.Data data SomeAnn = SomeAnn deriving (Data, Typeable) plugin :: Plugin plugin = defaultPlugin { installCoreToDos = install } install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo] install _ todo = do return (CoreDoPluginPass "Say name" pass : todo) pass :: ModGuts -> CoreM ModGuts pass g = do dflags <- getDynFlags mapM_ (printAnn dflags g) (mg_binds g) >> return g where printAnn :: DynFlags -> ModGuts -> CoreBind -> CoreM CoreBind printAnn dflags guts bndr@(NonRec b _) = do anns <- annotationsOn guts b :: CoreM [SomeAnn] unless (null anns) $ putMsgS $ "Annotated binding found: " ++ showSDoc dflags (ppr b) return bndr printAnn _ _ bndr = return bndr annotationsOn :: Data a => ModGuts -> CoreBndr -> CoreM [a] annotationsOn guts bndr = do (_, anns) <- getAnnotations deserializeWithData guts return $ lookupWithDefaultUFM anns [] (varUnique bndr)
sdiehl/ghc
testsuite/tests/plugins/annotation-plugin/SayAnnNames.hs
bsd-3-clause
1,103
0
14
252
378
192
186
27
2
{-# OPTIONS_HADDOCK hide #-} -- | -- Module : Streamly.Internal.Data.Strict -- Copyright : (c) 2019 Composewell Technologies -- (c) 2013 Gabriel Gonzalez -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC -- -- | Strict data types to be used as accumulator for strict left folds and -- scans. For more comprehensive strict data types see -- https://hackage.haskell.org/package/strict-base-types . The names have been -- suffixed by a prime so that programmers can easily distinguish the strict -- versions from the lazy ones. -- -- One major advantage of strict data structures as accumulators in folds and -- scans is that it helps the compiler optimize the code much better by -- unboxing. In a big tight loop the difference could be huge. -- module Streamly.Internal.Data.Strict ( Tuple' (..) , Tuple3' (..) , Tuple4' (..) , Maybe' (..) , fromStrictMaybe , Either' (..) ) where ------------------------------------------------------------------------------- -- Tuples ------------------------------------------------------------------------------- -- data Tuple' a b = Tuple' !a !b deriving Show data Tuple3' a b c = Tuple3' !a !b !c deriving Show data Tuple4' a b c d = Tuple4' !a !b !c !d deriving Show ------------------------------------------------------------------------------- -- Maybe ------------------------------------------------------------------------------- -- -- | A strict 'Maybe' data Maybe' a = Just' !a | Nothing' deriving Show -- XXX perhaps we can use a type class having fromStrict/toStrict operations. -- -- | Convert strict Maybe' to lazy Maybe {-# INLINABLE fromStrictMaybe #-} fromStrictMaybe :: Monad m => Maybe' a -> m (Maybe a) fromStrictMaybe Nothing' = return $ Nothing fromStrictMaybe (Just' a) = return $ Just a ------------------------------------------------------------------------------- -- Either ------------------------------------------------------------------------------- -- -- | A strict 'Either' data Either' a b = Left' !a | Right' !b deriving Show
harendra-kumar/asyncly
src/Streamly/Internal/Data/Strict.hs
bsd-3-clause
2,125
0
9
352
251
159
92
41
1
{- ShadowMap.hs (adapted from shadowmap.c which is (c) Silicon Graphics, Inc.) Copyright (c) Sven Panne 2002-2005 <[email protected]> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE -} import Control.Monad ( when, unless ) import Data.IORef ( IORef, newIORef ) import Foreign.Marshal.Array ( allocaArray ) import Foreign.Ptr ( nullPtr ) import System.Exit ( exitWith, ExitCode(ExitSuccess) ) import Graphics.UI.GLUT shadowMapSize :: TextureSize2D shadowMapSize = TextureSize2D 256 256 fovy, nearPlane, farPlane :: GLdouble fovy = 60 nearPlane = 10 farPlane = 100 lightPos :: Vertex4 GLfloat lightPos = Vertex4 25 25 25 1 lookat :: Vertex3 GLdouble lookat = Vertex3 0 0 0 up :: Vector3 GLdouble up = Vector3 0 0 1 data State = State { angle :: IORef GLdouble, torusAngle :: IORef GLfloat, showShadow :: IORef Bool, animate :: IORef Bool, funcMode :: IORef ComparisonFunction } makeState :: IO State makeState = do a <- newIORef 0 t <- newIORef 0 s <- newIORef False n <- newIORef True f <- newIORef Lequal return $ State { angle = a, torusAngle = t, showShadow = s, animate = n, funcMode = f } myInit :: IO () myInit = do texImage2D Nothing NoProxy 0 DepthComponent' shadowMapSize 0 (PixelData DepthComponent UnsignedByte nullPtr) position (Light 0) $= lightPos let white = Color4 1 1 1 1 specular (Light 0) $= white diffuse (Light 0) $= white textureWrapMode Texture2D S $= (Repeated, ClampToEdge) textureWrapMode Texture2D T $= (Repeated, ClampToEdge) textureFilter Texture2D $= ((Linear', Nothing), Linear') textureCompareMode Texture2D $= Just Lequal depthTextureMode Texture2D $= Luminance' colorMaterial $= Just (FrontAndBack, AmbientAndDiffuse) cullFace $= Just Back depthFunc $= Just Less light (Light 0) $= Enabled lighting $= Enabled texture Texture2D $= Enabled reshape :: ReshapeCallback reshape size@(Size w h) = do viewport $= (Position 0 0, size) matrixMode $= Projection loadIdentity perspective fovy (fromIntegral w / fromIntegral h) nearPlane farPlane matrixMode $= Modelview 0 idle :: State -> IdleCallback idle state = do angle state $~! (+ (pi / 10000)) torusAngle state $~! (+ 0.1) postRedisplay Nothing keyboard :: State -> KeyboardMouseCallback keyboard state (Char c) Down _ _ = do case c of '\27' -> exitWith ExitSuccess 't' -> texture Texture2D $~ \cap -> if cap == Enabled then Disabled else Enabled 'm' -> do fm <- get (funcMode state) textureCompareMode Texture2D $~ maybe (Just fm) (const Nothing) compareMode <- get (textureCompareMode Texture2D) putStrLn ("Compare mode " ++ maybe "Off" (const "On") compareMode) 'f' -> do funcMode state $~ \fm -> if fm == Lequal then Gequal else Lequal fm <- get (funcMode state) putStrLn ("Operator " ++ show fm) textureCompareMode Texture2D $~ maybe Nothing (const (Just fm)) 's' -> showShadow state $~ not 'p' -> do animate state $~ not animate' <- get (animate state) idleCallback $= if animate' then Just (idle state) else Nothing _ -> return () postRedisplay Nothing keyboard _ _ _ _ _ = return () drawObjects :: GLfloat -> Bool -> IO () drawObjects torusAngle' shadowRender = do textureOn <- get (texture Texture2D) when shadowRender $ texture Texture2D $= Disabled -- resolve overloading, not needed in "real" programs let normal3f = normal :: Normal3 GLfloat -> IO () color3f = color :: Color3 GLfloat -> IO () rectf = rect :: Vertex2 GLfloat -> Vertex2 GLfloat -> IO () translatef = translate :: Vector3 GLfloat -> IO () rotatef = rotate :: GLfloat -> Vector3 GLfloat -> IO () unless shadowRender $ do normal3f (Normal3 0 0 1) color3f (Color3 1 1 1) rectf (Vertex2 (-20) (-20)) (Vertex2 20 20) preservingMatrix $ do translatef (Vector3 11 11 11) rotatef 54.73 (Vector3 (-5) 5 0) rotate torusAngle' (Vector3 1 0 0) color3f (Color3 1 0 0) renderObject Solid (Torus 1 4 8 36) preservingMatrix $ do translatef (Vector3 2 2 2) color3f (Color3 0 0 1) renderObject Solid (Cube 4) preservingMatrix $ do getLightPos Vector3 >>= translate color3f (Color3 1 1 1) renderObject Wireframe (Sphere' 0.5 6 6) when (shadowRender && textureOn == Enabled) $ texture Texture2D $= Enabled getLightPos :: (GLdouble -> GLdouble -> GLdouble -> a) -> IO a getLightPos f = do Vertex4 x y z _ <- get (position (Light 0)) return $ f (realToFrac x) (realToFrac y) (realToFrac z) generateShadowMap :: GLfloat -> Bool -> IO () generateShadowMap torusAngle' showShadow' = do lightPos' <- getLightPos Vertex3 let (TextureSize2D shadowMapWidth shadowMapHeight) = shadowMapSize shadowMapSize' = Size shadowMapWidth shadowMapHeight preservingViewport $ do viewport $= (Position 0 0, shadowMapSize') clear [ ColorBuffer, DepthBuffer ] matrixMode $= Projection preservingMatrix $ do loadIdentity perspective 80 1 10 1000 matrixMode $= Modelview 0 preservingMatrix $ do loadIdentity lookAt lightPos' lookat up drawObjects torusAngle' True matrixMode $= Projection matrixMode $= Modelview 0 copyTexImage2D Nothing 0 DepthComponent' (Position 0 0) shadowMapSize 0 when showShadow' $ do let numShadowMapPixels = fromIntegral (shadowMapWidth * shadowMapHeight) allocaArray numShadowMapPixels $ \depthImage -> do let pixelData fmt = PixelData fmt Float depthImage :: PixelData GLfloat readPixels (Position 0 0) shadowMapSize' (pixelData DepthComponent) (_, Size viewPortWidth _) <- get viewport windowPos (Vertex2 (fromIntegral viewPortWidth / 2 :: GLfloat) 0) drawPixels shadowMapSize' (pixelData Luminance) swapBuffers -- Note: preservingViewport is not exception safe, but it doesn't matter here preservingViewport :: IO a -> IO a preservingViewport act = do v <- get viewport x <- act viewport $= v return x generateTextureMatrix :: IO () generateTextureMatrix = do -- Set up projective texture matrix. We use the Modelview matrix stack and -- OpenGL matrix commands to make the matrix. m <- preservingMatrix $ do loadIdentity -- resolve overloading, not needed in "real" programs let translatef = translate :: Vector3 GLfloat -> IO () scalef = scale :: GLfloat -> GLfloat -> GLfloat -> IO () translatef (Vector3 0.5 0.5 0.0) scalef 0.5 0.5 1.0 perspective 60 1 1 1000 lightPos' <- getLightPos Vertex3 lookAt lightPos' lookat up get (matrix (Just (Modelview 0))) [ sx, sy, sz, sw, tx, ty, tz, tw, rx, ry, rz, rw, qx, qy, qz, qw ] <- getMatrixComponents RowMajor (m :: GLmatrix GLdouble) textureGenMode S $= Just (ObjectLinear (Plane sx sy sz sw)) textureGenMode T $= Just (ObjectLinear (Plane tx ty tz tw)) textureGenMode R $= Just (ObjectLinear (Plane rx ry rz rw)) textureGenMode Q $= Just (ObjectLinear (Plane qx qy qz qw)) display :: State -> DisplayCallback display state = do let radius = 30 torusAngle' <- get (torusAngle state) showShadow' <- get (showShadow state) generateShadowMap torusAngle' showShadow' generateTextureMatrix unless showShadow' $ do clear [ ColorBuffer, DepthBuffer ] preservingMatrix $ do angle' <- get (angle state) lookAt (Vertex3 (radius * cos angle') (radius * sin angle') 30) lookat up drawObjects torusAngle' False swapBuffers main :: IO () main = do (progName, _args) <- getArgsAndInitialize initialDisplayMode $= [ RGBAMode, WithDepthBuffer, DoubleBuffered ] initialWindowSize $= Size 521 512 initialWindowPosition $= Position 100 100 createWindow progName state <- makeState myInit displayCallback $= display state reshapeCallback $= Just reshape keyboardMouseCallback $= Just (keyboard state) idleCallback $= Just (idle state) mainLoop
FranklinChen/hugs98-plus-Sep2006
packages/GLUT/examples/RedBook/ShadowMap.hs
bsd-3-clause
8,315
3
19
2,087
2,773
1,313
1,460
205
10
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module API where ------------------------------------------------------------------------------ import Control.Monad (mzero) import qualified Data.Aeson as A import Data.Aeson ((.:), (.=), ToJSON(..), FromJSON(..)) import Data.Map (Map) import Data.Text (Text, pack, unpack) import qualified Data.UUID.Types as UUID import Data.UUID.Types (UUID, fromText, toText) import Servant.API ((:>), (:<|>), Get, Post, Put, Delete, JSON ,Capture, ReqBody, Raw, FormUrlEncoded ,NoContent, QueryParam, QueryParams) import EntityID import Permissions import WorkerProfile import User import BrowserProfile import Job import Model ------------------------------------------------------------------------------ -- | This is the API definition of CBaaS. -- We use it to specify the activity of the server, and also to -- generate documentation and clients in a number of languages -- For more information about API specifications, see the Servant -- <http://haskell-servant.github.io documentation> type API1 = "user" :> UserAPI :<|> "worker" :> Get '[JSON] WorkerProfileMap :<|> "callfun" :> QueryParam "worker-id" (EntityID WorkerProfile) :> ReqBody '[JSON] Job :> Post '[JSON] (EntityID Job) :<|> "jobresult" :> QueryParam "job-id" (EntityID Job) :> Get '[JSON] JobResult :<|> "returnfun" :> QueryParam "worker-id" (EntityID WorkerProfile) :> QueryParam "job-id" (EntityID Job) :> ReqBody '[JSON] JobResult :> Post '[JSON] NoContent :<|> "browserupdates" :> Raw :<|> "work" :> QueryParam "name" WorkerName :> QueryParam "function" Text :> QueryParam "type" Type :> Raw ------------------------------------------------------------------------------ -- | User session sub-api -- Clients and this sites pages use this API for user and session management type UserAPI = "login" :> ReqBody '[FormUrlEncoded, JSON] LoginInfo :> Post '[JSON] Int -- AuthID :<|> "register" :> ReqBody '[FormUrlEncoded, JSON] RegisterInfo :> Post '[JSON] Int -- AuthID :<|> "currentuser" :> Get '[JSON] (Maybe Int) -- AuthID :<|> "logout" :> Post '[JSON] NoContent ------------------------------------------------------------------------------ -- | A generic API for Creating, Reading, Updating, and Deleting values -- of type `v` indexed by values of type `i`. We can reuse this API -- for any new types we come up with type CrudAPI i v = Get '[JSON] [v] :<|> Capture "id" i :> Get '[JSON] v :<|> ReqBody '[JSON] v :> Post '[JSON] i :<|> Capture "id" i :> ReqBody '[JSON] v :> Put '[JSON] Bool :<|> Capture "id" i :> Delete '[JSON] Bool
CBMM/CBaaS
cbaas-lib/src/API.hs
bsd-3-clause
3,248
0
27
978
665
375
290
56
0
{-# LANGUAGE RankNTypes #-} -- | The following module implements -- /Compact Hilbert Indices - Technical Report -- CS-2006-07/ -- by Chris Hamilton. At the time of writing this comment, the document is -- found at: -- <https://www.cs.dal.ca/sites/default/files/technical_reports/CS-2006-07.pdf> -- module Data.Algorithm.Hilbert.Utility ( -- * Gray code grayCode , grayCodeInverse -- * Bit operations , trailingSetBits , convertPointToHypercube , convertInteger , numToBool , boolToNum , entryPoint , exitPoint , direction , inverseTransform , transform , toParameters ) where import Control.Exception (assert) import Data.Algorithm.Hilbert.Types import Data.Bits import Data.List import Data.Maybe -- | Generate the ith binary reflected graycode given i. See Theorem 2.1 -- of Hamilton. grayCode :: PrecisionNum -> PrecisionNum grayCode (PrecisionNum v p) = PrecisionNum { value = v `xor` shifted, precision = p } where shifted = v `shiftR` 1 -- | Generate i given the ith binary reflected graycode. grayCodeInverse :: PrecisionNum -> PrecisionNum grayCodeInverse g | g == 0 = g | otherwise = g `xor` grayCodeInverse shifted where shifted = g `shiftR` 1 -- | Lemma 2.3 of Hamilton's paper deals with the dimension of the gray -- code change at any point in the sequence it depends on the number of -- bits that are set in the item of the sequence just before that point. -- For example, in the sequence below, the value in the trailingSetBits -- column for each entry predicts the position of the bracketed, -- changed number in the following row. -- -- -- > i | grayCode i | trailingSetBits i -- > ------------------------------------ -- > 0 | 000 | 0 -- > 1 | 00(1) | 1 -- > 2 | 0(1)1 | 0 -- > 3 | 01(0) | 2 -- > 4 | (1)10 | 0 --This is also referred to as the inter sub-hypercube dimension, g(i) trailingSetBits :: PrecisionNum -> PrecisionNum trailingSetBits val | testBit val 0 = floatingPlus 1 (trailingSetBits (val `shiftR` 1)) | otherwise = 0 -- | Calculate entry point for hypercube based on index. Referred to as -- e(i) in Hamilton. -- Is the return type here just a [Hypercube a]? entryPoint :: PrecisionNum -> PrecisionNum entryPoint i | i == 0 = i -- i is Zero. | otherwise = let r = grayCode $ clearBit (i - 1) 0 in -- Must not change precision. assert (precision r == precision i) r -- | Calculate exit point for hypercube based on index. Referred to as -- f(i) in Hamilton. exitPoint :: PrecisionNum -> PrecisionNum -> PrecisionNum exitPoint i n = entryPoint i `xor` setBit 0 (fromIntegral (direction i n)) -- From Lemma 2.11 -- -- | Lemma 2.8 Calculate the direction in the hypercube. Referred to as the -- intra sub-hypercube dimension, d(i) Note that n doesn't come into play -- as long as i < 2^n - 1 - which means that we really need to consider -- whether its worth passing n, or just limiting i in the beginning. -- direction :: PrecisionNum -> PrecisionNum -> PrecisionNum direction i n | i == 0 = 0 -- Zero | even i = trailingSetBits (i-1) `mod` fromIntegral n -- Even | otherwise = trailingSetBits i `mod` fromIntegral n -- Odd -- | See Section 2.1.3 of Hamilton, 'Rotations and Reflections', which -- describes transformation of entry and exit points. -- The rotation in this function needs to be performed with a bit size -- equal to the dimension of the problem. -- assert(b < 2^dimension && e < 2^dimension) transform :: PrecisionNum -> PrecisionNum -> PrecisionNum -> PrecisionNum transform e d b = (b `xor` e) `rotateR` amount where amount = fromIntegral (floatingPlus d 1) --transform e d b dimension = rotateRmodn (b `xor` e) (d+1) dimension -- | See Section 2.1.3 of Hamilton, 'Rotations and Reflections', which -- describes transformation of entry and exit points. -- inverseTransform returns a number in the interval (0 .. 2^order-1) inverseTransform :: PrecisionNum -> PrecisionNum -> PrecisionNum -> PrecisionNum inverseTransform e d b = (b `rotateL` amount) `xor` e where amount = fromIntegral (floatingPlus d 1) -- | convertPointToHypercube relates to s 2.1.4 'Algorithms' of Hamilton, -- and specifically the transformation of p (a vector of points) -- into l, by a formula -- l_(m-1) = [bit (p_(n-1), m - 1) ... bit (p_0, m - 1)] -- -- An example is perhaps helpful in understanding what it does. -- -- Given a list of n integers: [1, 2, 3], their binary representation is -- -- > | 0 0 1 | -- > | 0 1 0 | -- > | 0 1 1 | -- -- Transpose the above representation, to form a row from each column, -- -- > | 0 0 0 | -- > | 0 1 1 | -- > | 1 0 1 | -- -- The transposed representation is converted back to a list of -- integers [ 0, 3, 5] -- Eg: -- -- > convertPointToHypercube ([1, 2, 3]) 3 -- > = [0, 3, 5] -- -- Each integer in the list successively identifies a subhypercube -- in which our original point exists. That is, to calculate the -- Hilbert index of the point [1, 2, 3], we traverse subhypercubes -- identified by [0, 3, 5] -- -- Each subhypercube co-ordinate is large enough to uniquely identify -- any vertex. This depends only on the dimension -- When convertPointToHypercube is called from pointToIndex, it is -- passed in the Hilbert curve order as the number of bits, -- and a list representing a point on the curve as the vector p. -- -- In that situation it will return a list having a length equal to the -- /order/ of the Hilbert curve, in which each element of the list is -- representable in less than 2^dimension. -- -- convertPointToHypercube :: [PrecisionNum] -> Maybe [PrecisionNum] convertPointToHypercube point = mapM boolToNum (f point) where f = reverse . transpose . reverse . map numToBool -- | Convert an integer to a list of Bools corresponding to its binary -- representation. -- For example, to represent the integer 3 in 4 bits: -- -- > numToBool (3::Int) 4 -- > = [True,True,False,False] numToBool :: PrecisionNum -> [Bool] numToBool i = map (testBit i) [0..topmostBit] where topmostBit = fromIntegral $ precision i -1 -- Given a list of n integers: [1, 2, 3], their binary representation is -- > | 0 0 1 | -- > | 0 1 0 | -- > | 0 1 1 | convertInteger :: PrecisionNum -> Int -> Int -> Maybe [PrecisionNum] convertInteger i bitWidth chunks = sequence $ convertInteger' intAsBits bitWidth where targetLength = bitWidth * chunks correctedValue = fromJust $ mkPrecisionNum (value i) targetLength intAsBits = numToBool correctedValue :: [Bool] convertInteger' :: (Integral b) => [Bool] -> b -> [Maybe PrecisionNum] convertInteger' [] _ = [] convertInteger' bitList stride = let (this, rest) = splitAt (fromIntegral stride) bitList in convertInteger' rest stride ++ [boolToNum this] checkOrder :: (Integral a) => Int -> Int -> [a] -> Maybe PrecisionNum checkOrder o _ _ | o <= 0 = Nothing | otherwise = Just (minPrecision o) checkDimension :: (Integral a) => Int -> Int -> [a] -> Maybe PrecisionNum checkDimension _ d _ | d <= 0 = Nothing | otherwise = Just (minPrecision d) checkPoints :: (Integral a) => Int -> Int -> [a] -> Maybe [PrecisionNum] checkPoints o d p = assert(fromIntegral d == length p) mapM (`mkPrecisionNum` o) p toParameters :: (Ord a, Num a, Integral a) => Int -> Int -> [a] -> Maybe (PrecisionNum, PrecisionNum, [PrecisionNum]) toParameters order dimension points = do o <- checkOrder order dimension points d <- checkDimension order dimension points p <- checkPoints order dimension points return (o, d, p)
cje/hilbert
src/Data/Algorithm/Hilbert/Utility.hs
bsd-3-clause
8,561
0
13
2,549
1,346
751
595
77
1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} -- | The event mode lets you manage your own input. -- Pressing ESC will still closes the window, but you don't get automatic -- pan and zoom controls like with 'graphicsout'. Should only be called once -- during the execution of a program! module FPPrac.Events ( FileType (..) , Input (..) , Output (..) , PanelItemType (..) , PromptInfo , PanelContent , PanelItem , installEventHandler ) where import Data.List (mapAccumL) import FPPrac.Graphics import FPPrac.GUI.Panel import FPPrac.GUI.Prompt import Graphics.Gloss.Interface.Pure.Game hiding (play) import Graphics.Gloss.Interface.IO.Game (playIO) import Data.Time (getCurrentTime,utctDayTime) import Control.Exception as X type PromptInfo = (String,String) -- | Possible filetypes data FileType -- | Text file = TXTFile String -- | Bitmap file | BMPFile Picture deriving (Eq,Show) -- | Possible input events data Input -- | No input -- -- Generated every refresh of the eventhandler = NoInput -- | Keyboard key x is pressed down; ' ' for space, \\t for tab, \\n for enter | KeyIn Char -- | Left mouse button is pressed at location (x,y) | MouseDown (Float,Float) -- | Left mouse button is released at location (x,y) | MouseUp (Float,Float) -- | Mouse pointer is moved to location (x,y) | MouseMotion (Float,Float) -- | Mouse is double-clicked at location (x,y) | MouseDoubleClick (Float,Float) -- | Prompt (windowname,textbox content) -- -- Content returned from textbox in promptwindow with 'windowname' | Prompt PromptInfo -- | Panel buttonId [(controlId, value)] -- -- Event indicating that in the panel, the button with buttonId is -- pressed and that at the time the controls had the given value -- -- Note: the list is ordered by controlId -- -- - For checkboxes a value \"Y\" indicates that they are checked and -- a value of \"N\" indicates they are unchecked -- -- - Buttons have no controlstate | Panel Int [(Int,String)] -- | File name content -- -- The found file with given name, and found content | File FilePath FileType -- | Indicates if saving of file at filepath succeeded | Save FilePath Bool -- | Response to GetTime -- -- The time from midnight, 0 <= t < 86401s (because of leap-seconds) -- It has a precision of 10^-12 s. Leap second is only added if day -- has leap seconds | Time Float -- | Invalid / Unknown input | Invalid deriving (Eq,Show) data Output -- | Command to change the drawing mode -- -- Pictures returned from the eventhandler will normally be drawn -- on the screen and in a buffer, so that the window can be quickly -- redrawn. -- -- A DrawOnBuffer command can change this default behavior, If the -- parameter is False, pictures are only drawn on the screen. If the -- parameter is True, drawing will be down on both the buffer and the -- screen. This can be useful in response to MouseMotion Events. -- -- Example of rubber banding in line drawing program: -- -- @ -- handler (p1:ps) (MouseDown p2) -- = (p1:ps, [DrawOnBuffer False, DrawPicture (Color black $ Line [p1,p2])]) -- handler (p1:ps) (MouseMotion p2) -- = (p1:ps, [DrawOnBuffer False, DrawPicture (Color black $ Line [p1,p2])]) -- handler (p1:ps) (MouseUp p2) -- = (p2:p1:ps, [DrawOnBuffer True, DrawPicture (Color black $ Line [p1,p2])]) -- @ = DrawOnBuffer Bool -- | Draw the picture | DrawPicture Picture -- | GraphPrompt (windowName,info) -- -- Create a graphical prompt window which asks the user to enter -- a string in a textbox. The user can be informed about valid -- entries through the 'info' field. -- -- Note: the entered string is recorded as the following input event: -- 'Prompt (windowName,enteredText)' | GraphPrompt PromptInfo -- | Command to create a panel with the given panel content, must be -- actived with the 'PanelUpdate' command | PanelCreate PanelContent -- | PanelUpdate visible [(identifier, value)] -- -- Command to change visibility and the content of a panel. -- -- Note: not all controls need to be listed, the order can be -- arbitrary -- -- - For checkboxes, a value \"Y\" checks them, a value \"N\" unchecks them -- -- - Buttons can not be altered | PanelUpdate Bool [(Int,String)] -- | Clear the screen and buffer | ScreenClear -- | ReadFile fileName default -- -- Read the file of the given filetype at the filename, if it fails -- The default content is returned -- -- Note: the read file command generates following input event: -- 'File fileName content' | ReadFile FilePath FileType -- | SaveFile fileName content -- -- Save the file of the given filetype at the filename location -- -- Note: the save file command generates following input event: -- Save fileName success (True/False) | SaveFile FilePath FileType -- | Request the current time of day in seconds -- -- Note: the gettime command generates the following input event: -- 'Time timeOfDay' | GetTime deriving (Eq,Show) data GUIMode = PanelMode | PromptMode PromptInfo String | FreeMode | PerformIO deriving (Eq,Show) data EventState a = EventState { screen :: Picture , buffer :: Picture , drawOnBuffer :: Bool , storedInputs :: [Input] , storedOutputs :: [Output] , doubleClickT :: Int , guiMode :: GUIMode , panel :: Maybe (PanelContent,[(Int,String)]) , userState :: a } eventToInput :: Event -> Input eventToInput (EventKey (Char x) Down _ _) = KeyIn x eventToInput (EventKey (SpecialKey KeySpace) Down _ _) = KeyIn ' ' eventToInput (EventKey (SpecialKey KeyTab) Down _ _) = KeyIn '\t' eventToInput (EventKey (SpecialKey KeyEnter) Down _ _) = KeyIn '\n' eventToInput (EventKey (SpecialKey KeyBackspace) Down _ _) = KeyIn '\b' eventToInput (EventKey (MouseButton LeftButton) Down _ p) = MouseDown p eventToInput (EventKey (MouseButton LeftButton) Up _ p) = MouseUp p eventToInput (EventMotion p) = MouseMotion p eventToInput _ = Invalid -- | The event mode lets you manage your own input. -- Pressing ESC will still abort the program, but you don't get automatic -- pan and zoom controls like with graphicsout. Should only be called once -- during the execution of a program! installEventHandler :: forall userState . String -- ^ Name of the window -> (userState -> Input -> (userState, [Output])) -- ^ Event handler that takes current state, input, and returns new state and maybe an updated picture -> userState -- ^ Initial state of the program -> Picture -- ^ Initial Picture -> Int -- ^ doubleclick speed -> IO () installEventHandler name handler initState p dcTime = playIO (InWindow name (800,600) (20,20)) white 50 (EventState p p True [] [] 0 FreeMode Nothing initState) (return . screen) (\e s -> handleInputIO handler dcTime s (eventToInput e)) (\_ s -> handleInputIO handler dcTime s NoInput) handleInputIO :: forall userState . (userState -> Input -> (userState, [Output])) -> Int -> EventState userState -> Input -> IO (EventState userState) handleInputIO handler dcTime s@(EventState {guiMode = PerformIO,..}) i = do inps <- fmap (filter (/= Invalid)) $ mapM handleIO storedOutputs let s' = s {guiMode = FreeMode, storedOutputs = [], storedInputs = storedInputs ++ inps} return $ handleInput handler dcTime s' i handleInputIO handler dcTime s i = return $ handleInput handler dcTime s i handleInput :: forall userState . (userState -> Input -> (userState, [Output])) -> Int -> EventState userState -> Input -> EventState userState handleInput handler dcTime s@(EventState {guiMode = FreeMode, ..}) i = s' {userState = userState', doubleClickT = doubleClickT', storedInputs = []} where (doubleClickT',dc) = registerDoubleClick dcTime doubleClickT i remainingInputs = storedInputs ++ (if null dc then [i] else dc) (userState',outps) = mapAccumL handler userState remainingInputs s' = foldl handleOutput s $ concat outps handleInput handler _ s@(EventState {guiMode = PanelMode, panel = Just (panelContents,itemState), ..}) (MouseDown (x,y)) | isClicked /= Nothing = s'' | otherwise = s where isClicked = onItem panelContents (x,y) (Just itemClicked) = isClicked itemState' = toggleItem itemState itemClicked (userState',outps) = handler userState (Panel (fst itemClicked) $ filter ((/= "") . snd) itemState') s' = s {screen = Pictures [buffer,drawPanel panelContents itemState'], panel = Just (panelContents,itemState'), userState = userState'} s'' = foldl handleOutput s' outps handleInput _ _ s@(EventState {guiMode = PromptMode pInfo pContent, ..}) (KeyIn '\b') | pContent /= [] = s' | otherwise = s where pContent' = init pContent screen' = Pictures [buffer,drawPrompt pInfo pContent'] s' = s {guiMode = PromptMode pInfo pContent', screen = screen'} handleInput handler _ s@(EventState {guiMode = PromptMode (pName,_) pContent, ..}) (KeyIn '\n') = s'' where (userState',outps) = handler userState (Prompt (pName,pContent)) s' = s {guiMode = FreeMode, screen = buffer, userState = userState'} s'' = foldl handleOutput s' outps handleInput _ _ s@(EventState {guiMode = PromptMode pInfo pContent, ..}) (KeyIn x) = s' where pContent' = pContent ++ [x] screen' = Pictures [buffer,drawPrompt pInfo pContent'] s' = s {guiMode = PromptMode pInfo pContent', screen = screen'} handleInput _ _ s _ = s registerDoubleClick :: Int -> Int -> Input -> (Int,[Input]) registerDoubleClick d 0 (MouseDown _) = (d ,[]) registerDoubleClick _ _ (MouseDown (x,y)) = (0 ,[MouseDoubleClick (x,y)]) registerDoubleClick _ 0 NoInput = (0 ,[]) registerDoubleClick _ n NoInput = (n-1,[]) registerDoubleClick _ n _ = (n ,[]) handleOutput :: EventState a -> Output -> EventState a handleOutput s (DrawOnBuffer b) = s {drawOnBuffer = b} handleOutput s ScreenClear = s {buffer = Blank, screen = Blank} handleOutput s@(EventState {..}) (DrawPicture p) = s { buffer = if drawOnBuffer then Pictures [buffer, p] else buffer , screen = Pictures [buffer, p] } handleOutput s@(EventState {guiMode = FreeMode, ..}) i@(ReadFile _ _) = s {guiMode = PerformIO, storedOutputs = storedOutputs ++ [i]} handleOutput s@(EventState {guiMode = FreeMode, ..}) i@(SaveFile _ _) = s {guiMode = PerformIO, storedOutputs = storedOutputs ++ [i]} handleOutput s@(EventState {guiMode = FreeMode, ..}) i@(GetTime) = s {guiMode = PerformIO, storedOutputs = storedOutputs ++ [i]} handleOutput s@(EventState {..}) (PanelCreate panelContent) = s {panel = Just (panelContent,defItemState)} where defItemState = createDefState panelContent handleOutput s@(EventState {panel = Just (panelContents,itemState), ..}) (PanelUpdate True _) = s {guiMode = PanelMode, screen = Pictures [buffer,drawPanel panelContents itemState]} handleOutput s@(EventState {panel = Nothing}) (PanelUpdate True _) = s handleOutput s@(EventState {panel = Just (panelContents,_), ..}) (PanelUpdate False _) = s {guiMode = FreeMode, screen = buffer, panel = Just (panelContents,defItemState)} where defItemState = createDefState panelContents handleOutput s@(EventState {panel = Nothing, ..}) (PanelUpdate False _) = s {guiMode = FreeMode, screen = buffer} handleOutput s@(EventState {..}) (GraphPrompt promptInfo) = s {guiMode = PromptMode promptInfo "", screen = Pictures [buffer,drawPrompt promptInfo ""]} handleOutput s _ = s handleIO :: Output -> IO Input handleIO (ReadFile filePath (TXTFile defContents)) = (do f <- readFile filePath return $ File filePath $ TXTFile f ) `X.catch` (\(_ :: IOException) -> return (File filePath $ TXTFile defContents)) handleIO (ReadFile filePath (BMPFile defContents)) = (do f <- loadBMP filePath return $ File filePath $ BMPFile f ) `X.catch` (\(_ :: IOException) -> return (File filePath $ BMPFile defContents)) handleIO (SaveFile filePath (TXTFile content)) = ( do writeFile filePath content return $ Save filePath True ) `X.catch` (\(_ :: IOException) -> return $ Save filePath False) handleIO (SaveFile filePath (BMPFile _)) = return $ Save filePath False handleIO GetTime = do t <- fmap utctDayTime $ getCurrentTime return $ Time (fromRational $ toRational t) handleIO _ = return Invalid
christiaanb/fpprac
src/FPPrac/Events.hs
bsd-3-clause
14,107
0
13
4,143
3,143
1,776
1,367
203
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ViewPatterns #-} -- | The Employee-Department schema used in the "Query Shredding" paper. module Schema.Shredding where import Data.List.NonEmpty(NonEmpty((:|))) import Data.Text import Database.DSH data Department = Department { d_id :: Integer , d_dpt :: Text } deriveDSH ''Department deriveTA ''Department generateTableSelectors ''Department departments :: Q [Department] departments = table "departments" ("id" :| ["dpt"]) (defaultHints $ pure $ Key (pure "id") ) data Employee = Employee { e_id :: Integer , e_dpt :: Text , e_emp :: Text , e_salary :: Integer } deriveDSH ''Employee deriveTA ''Employee generateTableSelectors ''Employee employees :: Q [Employee] employees = table "employees" ("id" :| ["dpt", "emp", "salary"]) (defaultHints $ pure $ Key (pure "id")) data Task = Task { t_emp :: Text , t_id :: Integer , t_tsk :: Text } deriveDSH ''Task deriveTA ''Task generateTableSelectors ''Task tasks :: Q [Task] tasks = table "tasks" ("emp" :| ["id", "tsk"]) (defaultHints $ pure $ Key $ "emp" :| ["tsk"]) data Contact = Contact { c_client :: Bool , c_dpt :: Text , c_id :: Integer , c_name :: Text } deriveDSH ''Contact deriveTA ''Contact generateTableSelectors ''Contact contacts :: Q [Contact] contacts = table "contacts" ("client" :| ["dpt", "id", "name"]) (defaultHints $ pure $ Key $ pure "id")
ulricha/dsh-tpc-h
Schema/Shredding.hs
bsd-3-clause
1,842
0
10
544
478
261
217
56
1
-- | A queue of passive critical pairs, using a memory-efficient representation. {-# LANGUAGE TypeFamilies, RecordWildCards, FlexibleContexts, ScopedTypeVariables, StandaloneDeriving #-} module Twee.PassiveQueue( Params(..), Queue, Passive(..), empty, insert, removeMin, mapMaybe, toList, queueSize) where import qualified Data.Heap as Heap import qualified Data.Vector.Unboxed as Vector import Data.Int import Data.List hiding (insert) import qualified Data.Maybe import Data.Ord import Data.Proxy import Twee.Utils -- | A datatype representing all the type parameters of the queue. class (Eq (Id params), Integral (Id params), Ord (Score params), Vector.Unbox (PackedScore params), Vector.Unbox (PackedId params)) => Params params where -- | The score assigned to critical pairs. Smaller scores are better. type Score params -- | The type of ID numbers used to name rules. type Id params -- | A 'Score' packed for storage into a 'Vector.Vector'. Must be an instance of 'Vector.Unbox'. type PackedScore params -- | An 'Id' packed for storage into a 'Vector.Vector'. Must be an instance of 'Vector.Unbox'. type PackedId params -- | Pack a 'Score'. packScore :: proxy params -> Score params -> PackedScore params -- | Unpack a 'PackedScore'. unpackScore :: proxy params -> PackedScore params -> Score params -- | Pack an 'Id'. packId :: proxy params -> Id params -> PackedId params -- | Unpack a 'PackedId'. unpackId :: proxy params -> PackedId params -> Id params -- | A critical pair queue. newtype Queue params = Queue (Heap.Heap (PassiveSet params)) -- All passive CPs generated from one given rule. data PassiveSet params = PassiveSet { passiveset_best :: {-# UNPACK #-} !(Passive params), passiveset_rule :: !(Id params), -- CPs where the rule is the left-hand rule passiveset_left :: {-# UNPACK #-} !(Vector.Vector (PackedScore params, PackedId params, Int32)), -- CPs where the rule is the right-hand rule passiveset_right :: {-# UNPACK #-} !(Vector.Vector (PackedScore params, PackedId params, Int32)) } instance Params params => Eq (PassiveSet params) where x == y = compare x y == EQ instance Params params => Ord (PassiveSet params) where compare = comparing passiveset_best -- A smart-ish constructor. {-# INLINEABLE mkPassiveSet #-} mkPassiveSet :: Params params => Proxy params -> Id params -> Vector.Vector (PackedScore params, PackedId params, Int32) -> Vector.Vector (PackedScore params, PackedId params, Int32) -> Maybe (PassiveSet params) mkPassiveSet proxy rule left right | Vector.null left && Vector.null right = Nothing | not (Vector.null left) && (Vector.null right || l <= r) = Just PassiveSet { passiveset_best = l, passiveset_rule = rule, passiveset_left = Vector.tail left, passiveset_right = right } -- In this case we must have not (Vector.null right). | otherwise = Just PassiveSet { passiveset_best = r, passiveset_rule = rule, passiveset_left = left, passiveset_right = Vector.tail right } where l = unpack proxy rule True (Vector.head left) r = unpack proxy rule False (Vector.head right) -- Unpack a triple into a Passive. {-# INLINEABLE unpack #-} unpack :: Params params => Proxy params -> Id params -> Bool -> (PackedScore params, PackedId params, Int32) -> Passive params unpack proxy rule isLeft (score, id, pos) = Passive { passive_score = unpackScore proxy score, passive_rule1 = if isLeft then rule else rule', passive_rule2 = if isLeft then rule' else rule, passive_pos = fromIntegral pos } where rule' = unpackId proxy id -- Make a PassiveSet from a list of Passives. {-# INLINEABLE makePassiveSet #-} makePassiveSet :: forall params. Params params => Id params -> [Passive params] -> Maybe (PassiveSet params) makePassiveSet _ [] = Nothing makePassiveSet rule ps | and [passive_rule2 p == rule | p <- right] = mkPassiveSet proxy rule (Vector.fromList (map (pack True) (sort left))) (Vector.fromList (map (pack False) (sort right))) | otherwise = error "rule id does not occur in passive" where proxy :: Proxy params proxy = Proxy (left, right) = partition (\p -> passive_rule1 p == rule) ps pack isLeft Passive{..} = (packScore proxy passive_score, packId proxy (if isLeft then passive_rule2 else passive_rule1), fromIntegral passive_pos) -- Convert a PassiveSet back into a list of Passives. {-# INLINEABLE unpackPassiveSet #-} unpackPassiveSet :: forall params.Params params => PassiveSet params -> (Int, [Passive params]) unpackPassiveSet PassiveSet{..} = (1 + Vector.length passiveset_left + Vector.length passiveset_right, passiveset_best: map (unpack proxy passiveset_rule True) (Vector.toList passiveset_left) ++ map (unpack proxy passiveset_rule False) (Vector.toList passiveset_right)) where proxy :: Proxy params proxy = Proxy -- Find and remove the best element from a PassiveSet. {-# INLINEABLE unconsPassiveSet #-} unconsPassiveSet :: forall params. Params params => PassiveSet params -> (Passive params, Maybe (PassiveSet params)) unconsPassiveSet PassiveSet{..} = (passiveset_best, mkPassiveSet (Proxy :: Proxy params) passiveset_rule passiveset_left passiveset_right) -- | A queued critical pair. data Passive params = Passive { -- | The score of this critical pair. passive_score :: !(Score params), -- | The rule which does the outermost rewrite in this critical pair. passive_rule1 :: !(Id params), -- | The rule which does the innermost rewrite in this critical pair. passive_rule2 :: !(Id params), -- | The position of the overlap. See 'Twee.CP.overlap_pos'. passive_pos :: {-# UNPACK #-} !Int } instance Params params => Eq (Passive params) where x == y = compare x y == EQ instance Params params => Ord (Passive params) where compare = comparing f where f Passive{..} = (passive_score, intMax (fromIntegral passive_rule1) (fromIntegral passive_rule2), intMin (fromIntegral passive_rule1) (fromIntegral passive_rule2), passive_pos) -- | The empty queue. empty :: Queue params empty = Queue Heap.empty -- | Add a set of 'Passive's to the queue. {-# INLINEABLE insert #-} insert :: Params params => Id params -> [Passive params] -> Queue params -> Queue params insert rule passives (Queue q) = Queue $ case makePassiveSet rule passives of Nothing -> q Just p -> Heap.insert p q -- | Remove the minimum 'Passive' from the queue. {-# INLINEABLE removeMin #-} removeMin :: Params params => Queue params -> Maybe (Passive params, Queue params) removeMin (Queue q) = do (passiveset, q) <- Heap.removeMin q case unconsPassiveSet passiveset of (passive, Just passiveset') -> Just (passive, Queue (Heap.insert passiveset' q)) (passive, Nothing) -> Just (passive, Queue q) -- | Map a function over all 'Passive's. {-# INLINEABLE mapMaybe #-} mapMaybe :: Params params => (Passive params -> Maybe (Passive params)) -> Queue params -> Queue params mapMaybe f (Queue q) = Queue (Heap.mapMaybe g q) where g passiveSet@PassiveSet{..} = makePassiveSet passiveset_rule $ Data.Maybe.mapMaybe f $ snd (unpackPassiveSet passiveSet) -- | Convert a queue into a list of 'Passive's. -- The 'Passive's are produced in batches, with each batch labelled -- with its size. {-# INLINEABLE toList #-} toList :: Params params => Queue params -> [(Int, [Passive params])] toList (Queue h) = map unpackPassiveSet (Heap.toList h) queueSize :: Params params => Queue params -> Int queueSize = sum . map fst . toList
nick8325/kbc
src/Twee/PassiveQueue.hs
bsd-3-clause
7,693
15
18
1,537
2,062
1,078
984
141
3
{-# LANGUAGE LambdaCase #-} -- | -- Module : Game.Simulation.Input -- Description : Contains input related functions and signals -- for the game simulation -- Copyright : (c) 2016 Caitlin Wilks -- License : BSD3 -- Maintainer : Caitlin Wilks <[email protected]> -- -- module Game.Simulation.Input ( keyDown , keyPressed , keyReleased , mouseButtonDown , mouseButtonPressed , mouseButtonReleased , mouseMoved , mouseWheelMoved , RetType(..) ) where import Framework import Reactive.Banana import Reactive.Banana.Frameworks import Linear.Affine (Point(..)) import Linear.V2 import qualified SDL.Event as SDL import qualified SDL.Input.Keyboard as SDL -- | Predicate to determine whether the given SDL event is a keyboard event isKeyEvent :: SDL.Event -> Bool isKeyEvent e = case SDL.eventPayload e of SDL.KeyboardEvent _ -> True _ -> False -- | Filters input events down to just keyboard events keyEvents :: InputEvent -> Event SDL.KeyboardEventData keyEvents eInput = let keyEvents = filterE isKeyEvent eInput getKeyEventData = (\x -> let SDL.KeyboardEvent d = SDL.eventPayload x in d) eventData = getKeyEventData <$> keyEvents in eventData -- | Predicate to determine whether a keyboard event is a key change isKeyChange :: SDL.Scancode -> SDL.InputMotion -> Bool -> SDL.KeyboardEventData -> Bool isKeyChange expectedScancode expectedMotion allowRepeat keyEventData = let SDL.KeyboardEventData _ motion repeat sym = keyEventData SDL.Keysym scancode _ _ = sym in motion == expectedMotion && allowRepeat == repeat && scancode == expectedScancode -- | An event that fires when a key's state changes keyChanged :: SDL.InputMotion -> InputEvent -> SDL.Scancode -> Event () keyChanged inputMotion eInput scancode = let keyEvent = keyEvents eInput isKeyPressed = isKeyChange scancode inputMotion False scanEvent = filterE isKeyPressed keyEvent in () <$ scanEvent -- | An event that fires when a key is pressed keyPressed :: InputEvent -> SDL.Scancode -> Event () keyPressed = keyChanged SDL.Pressed -- | An event that fires when a key is released keyReleased :: InputEvent -> SDL.Scancode -> Event () keyReleased = keyChanged SDL.Released -- | A behavior describing whether a given key is currently held down keyDown :: InputEvent -> SDL.Scancode -> MomentIO (Behavior Bool) keyDown eInput scan = let press = True <$ keyPressed eInput scan release = False <$ keyReleased eInput scan keyOnOff = unionWith (\_ _ -> False) press release in stepper False keyOnOff -- | Predicate to determine whether the given SDL event is a mouse button event isMouseButtonEvent :: SDL.Event -> Bool isMouseButtonEvent e = case SDL.eventPayload e of SDL.MouseButtonEvent _ -> True _ -> False -- | Filters input events down to just mouse button events mouseButtonEvents :: InputEvent -> Event SDL.MouseButtonEventData mouseButtonEvents eInput = let mbEvents = filterE isMouseButtonEvent eInput getMbEventData = (\x -> let SDL.MouseButtonEvent d = SDL.eventPayload x in d) eventData = getMbEventData <$> mbEvents in eventData -- | Predicate to determine whether a mouse button event is a button change isMouseButtonChange :: SDL.MouseButton -> SDL.InputMotion -> SDL.MouseButtonEventData -> Bool isMouseButtonChange expectedButton expectedMotion mbEventData = let SDL.MouseButtonEventData _ motion _ button _ _ = mbEventData in motion == expectedMotion && button == expectedButton -- | An event that fires when a key's state changes mouseButtonChanged :: SDL.InputMotion -> InputEvent -> SDL.MouseButton -> Event () mouseButtonChanged inputMotion eInput button = let mbEvent = mouseButtonEvents eInput isButtonPressed = isMouseButtonChange button inputMotion scanEvent = filterE isButtonPressed mbEvent in () <$ scanEvent -- | An event that fires when a mouse button is pressed mouseButtonPressed :: InputEvent -> SDL.MouseButton -> Event () mouseButtonPressed = mouseButtonChanged SDL.Pressed -- | An event that fires when a mouse button is released mouseButtonReleased :: InputEvent -> SDL.MouseButton -> Event () mouseButtonReleased = mouseButtonChanged SDL.Released -- | A behavior describing whether a given mouse button is currently held down mouseButtonDown :: InputEvent -> SDL.MouseButton -> MomentIO (Behavior Bool) mouseButtonDown eInput button = let press = True <$ mouseButtonPressed eInput button release = False <$ mouseButtonReleased eInput button eButtonDown = unionWith (\_ _ -> False) press release in stepper False eButtonDown -- | Predicate to determine whether the given SDL event is a mouse motion event isMouseMotionEvent :: SDL.Event -> Bool isMouseMotionEvent e = case SDL.eventPayload e of SDL.MouseMotionEvent _ -> True _ -> False -- | Filters input events down to just mouse motion events mouseMotionEvents :: InputEvent -> Event SDL.MouseMotionEventData mouseMotionEvents eInput = let mbEvents = filterE isMouseMotionEvent eInput getMbEventData = (\x -> let SDL.MouseMotionEvent d = SDL.eventPayload x in d) eventData = getMbEventData <$> mbEvents in eventData -- | A sum type for specifying whether the mouse movement event should -- report a difference or an absolute position data RetType = Delta | Absolute -- | Gets either the difference in position or the absolute position of the mouse -- from an SDL.MouseMotionEventData mouseMoveValue :: RetType -> SDL.MouseMotionEventData -> V2 Float mouseMoveValue Delta (SDL.MouseMotionEventData _ _ _ _ (V2 x y)) = V2 (fromIntegral x) (fromIntegral y) mouseMoveValue Absolute (SDL.MouseMotionEventData _ _ _ (P (V2 x y)) _) = V2 (fromIntegral x) (fromIntegral y) -- | An event that fires when the mouse moves and reports either the -- difference in position or the new position mouseMoved :: InputEvent -> RetType -> Event (V2 Float) mouseMoved eInput retType = let events = mouseMotionEvents eInput in mouseMoveValue retType <$> events -- | Predicate to determine whether the given SDL event is a mouse wheel event isMouseWheelEvent :: SDL.Event -> Bool isMouseWheelEvent e = case SDL.eventPayload e of SDL.MouseWheelEvent _ -> True _ -> False -- | Filters input events down to just mouse wheel events mouseWheelEvents :: InputEvent -> Event SDL.MouseWheelEventData mouseWheelEvents eInput = let mwEvents = filterE isMouseWheelEvent eInput getMwEventData = (\x -> let SDL.MouseWheelEvent d = SDL.eventPayload x in d) eventData = getMwEventData <$> mwEvents in eventData -- | Mouse wheel changed value mouseWheelValue :: SDL.MouseWheelEventData -> Float mouseWheelValue (SDL.MouseWheelEventData _ _ (V2 _ y) _) = fromIntegral y -- | An event that fires when the mouse wheel moves mouseWheelMoved :: InputEvent -> Event Float mouseWheelMoved eInput = let events = mouseWheelEvents eInput in mouseWheelValue <$> events
Catchouli/tyke
src/Game/Simulation/Input.hs
bsd-3-clause
7,874
0
16
2,187
1,546
793
753
114
2
{-# LANGUAGE ViewPatterns #-} -- | The endpoints on the cloud server module Development.Shake.Internal.History.Bloom( Bloom, bloomTest, bloomCreate ) where import Data.Word import Data.Bits import Data.Hashable import Data.Semigroup import Foreign.Storable import Foreign.Ptr import Prelude -- | Given an Int hash we store data Bloom a = Bloom {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64 deriving (Eq,Show) instance Storable (Bloom a) where sizeOf _ = 4 * sizeOf (0 :: Word64) alignment _ = alignment (0 :: Word64) peek (castPtr -> ptr) = Bloom <$> peekElemOff ptr 0 <*> peekElemOff ptr 1 <*> peekElemOff ptr 2 <*> peekElemOff ptr 3 poke (castPtr -> ptr) (Bloom x1 x2 x3 x4) = do pokeElemOff ptr 0 x1 pokeElemOff ptr 1 x2 pokeElemOff ptr 2 x3 pokeElemOff ptr 3 x4 instance Semigroup (Bloom a) where Bloom x1 x2 x3 x4 <> Bloom y1 y2 y3 y4 = Bloom (x1 .|. y1) (x2 .|. y2) (x3 .|. y3) (x4 .|. y4) instance Monoid (Bloom a) where mempty = Bloom 0 0 0 0 mappend = (<>) -- Should the cloud need to know about Key's? It only needs to do Eq on them... -- If you Key has a smart Eq your build tree might be more diverse -- Have the Id resolved in Server. bloomTest :: Hashable a => Bloom a -> a -> Bool bloomTest bloom x = bloomCreate x <> bloom == bloom bloomCreate :: Hashable a => a -> Bloom a bloomCreate (fromIntegral . hash -> x) = Bloom (f 1) (f 2) (f 3) (f 4) where f i = x `xor` rotate x i
ndmitchell/shake
src/Development/Shake/Internal/History/Bloom.hs
bsd-3-clause
1,552
0
10
387
517
267
250
37
1
module Main where putHello :: String -> IO () putHello x = putStrLn ("Hello " ++ x) main :: IO () main = putHello "Fragnix!"
phischu/fragnix
tests/quick/HiFragnix/HiFragnix.hs
bsd-3-clause
126
0
7
26
54
28
26
5
1
{- | Module : Camfort.Specification.Units.Parser.Types Description : Defines the representation of unit specifications resulting from parsing. Copyright : (c) 2017, Dominic Orchard, Andrew Rice, Mistral Contrastin, Matthew Danish License : Apache-2.0 Maintainer : [email protected] Stability : experimental -} {-# LANGUAGE DeriveDataTypeable #-} module Camfort.Specification.Units.Parser.Types ( UnitStatement(..) , UnitOfMeasure(..) , UnitPower(..) ) where import Data.Data (Data) import Data.List (intercalate) data UnitStatement = UnitAssignment (Maybe [String]) UnitOfMeasure | UnitAlias String UnitOfMeasure deriving (Eq, Data) instance Show UnitStatement where show (UnitAssignment (Just ss) uom) = "= unit (" ++ show uom ++ ") :: " ++ intercalate "," ss show (UnitAssignment Nothing uom) = "= unit (" ++ show uom ++ ")" show (UnitAlias s uom) = "= unit :: " ++ s ++ " = " ++ show uom data UnitOfMeasure = Unitless | UnitBasic String | UnitProduct UnitOfMeasure UnitOfMeasure | UnitQuotient UnitOfMeasure UnitOfMeasure | UnitExponentiation UnitOfMeasure UnitPower | UnitRecord [(String, UnitOfMeasure)] deriving (Data, Eq) instance Show UnitOfMeasure where show Unitless = "1" show (UnitBasic s) = s show (UnitProduct uom1 uom2) = show uom1 ++ " " ++ show uom2 show (UnitQuotient uom1 uom2) = show uom1 ++ " / " ++ show uom2 show (UnitExponentiation uom expt) = show uom ++ "** (" ++ show expt ++ ")" show (UnitRecord recs) = "record (" ++ intercalate ", " (map (\ (n, u) -> n ++ " :: " ++ show u) recs) ++ ")" data UnitPower = UnitPowerInteger Integer | UnitPowerRational Integer Integer deriving (Data, Eq) instance Show UnitPower where show (UnitPowerInteger i) = show i show (UnitPowerRational i1 i2) = show i1 ++ "/" ++ show i2
dorchard/camfort
src/Camfort/Specification/Units/Parser/Types.hs
apache-2.0
1,869
0
14
394
524
275
249
45
0
{-# LANGUAGE TemplateHaskell #-} {-| Unittests for the static lock declaration. -} {- Copyright (C) 2016 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.JQueue.LockDecls (testLockDecls) where import Test.QuickCheck import Test.HUnit import Data.List import Data.Maybe import Prelude () import Ganeti.Prelude import Test.Ganeti.TestHelper import Test.Ganeti.Objects import Test.Ganeti.OpCodes (genOpCodeFromId) import Test.Ganeti.TestCommon import qualified Ganeti.Constants as C import Ganeti.JQueue.LockDecls import Ganeti.OpCodes import Ganeti.Objects prop_staticWeight :: ConfigData -> Maybe OpCode -> [OpCode] -> Property prop_staticWeight cfg op ops = let weight = staticWeight cfg op ops maxWeight = C.staticLockSureBlockWeight * 5 in (weight >= 0 && weight <= (maxWeight+ C.staticLockBaseWeight)) ==? True genExclusiveInstanceOp :: ConfigData -> Gen OpCode genExclusiveInstanceOp cfg = do let list = [ "OP_INSTANCE_STARTUP" , "OP_INSTANCE_SHUTDOWN" , "OP_INSTANCE_REBOOT" , "OP_INSTANCE_RENAME" ] op_id <- elements list genOpCodeFromId op_id (Just cfg) prop_instNameConflictCheck :: Property prop_instNameConflictCheck = do forAll (genConfigDataWithValues 10 50) $ \ cfg -> forAll (genExclusiveInstanceOp cfg) $ \ op1 -> forAll (genExclusiveInstanceOp cfg) $ \ op2 -> forAll (genExclusiveInstanceOp cfg) $ \ op3 -> let w1 = staticWeight cfg (Just op1) [op3] w2 = staticWeight cfg (Just op2) [op3] iName1 = opInstanceName op1 iName2 = opInstanceName op2 iName3 = opInstanceName op3 testResult | iName1 == iName2 = True | iName1 == iName3 = (w2 <= w1) | iName2 == iName3 = (w1 <= w2) | otherwise = True in testResult genExclusiveNodeOp :: ConfigData -> Gen OpCode genExclusiveNodeOp cfg = do let list = [ "OP_REPAIR_COMMAND" , "OP_NODE_MODIFY_STORAGE" , "OP_REPAIR_NODE_STORAGE" ] op_id <- elements list genOpCodeFromId op_id (Just cfg) prop_nodeNameConflictCheck :: Property prop_nodeNameConflictCheck = do forAll (genConfigDataWithValues 10 50) $ \ cfg -> forAll (genExclusiveNodeOp cfg) $ \ op1 -> forAll (genExclusiveNodeOp cfg) $ \ op2 -> forAll (genExclusiveNodeOp cfg) $ \ op3 -> let w1 = staticWeight cfg (Just op1) [op3] w2 = staticWeight cfg (Just op2) [op3] nName1 = opNodeName op1 nName2 = opNodeName op2 nName3 = opNodeName op3 testResult | nName1 == nName2 = True | nName1 == nName3 = (w2 <= w1) | nName2 == nName3 = (w1 <= w2) | otherwise = True in testResult case_queueLockOpOrder :: Assertion case_queueLockOpOrder = do cfg <- generate $ genConfigDataWithValues 10 50 diagnoseOp <- generate $ genOpCodeFromId "OP_OS_DIAGNOSE" (Just cfg) networkAddOp <- generate $ genOpCodeFromId "OP_NETWORK_ADD" (Just cfg) groupVerifyOp <- generate $ genOpCodeFromId "OP_GROUP_VERIFY_DISKS" (Just cfg) nodeAddOp <- generate $ genOpCodeFromId "OP_NODE_ADD" (Just cfg) currentOp <- generate $ genExclusiveInstanceOp cfg let w1 = staticWeight cfg (Just diagnoseOp) [currentOp] w2 = staticWeight cfg (Just networkAddOp) [currentOp] w3 = staticWeight cfg (Just groupVerifyOp) [currentOp] w4 = staticWeight cfg (Just nodeAddOp) [currentOp] weights = [w1, w2, w3, w4] assertEqual "weights should be sorted" weights (sort weights) testSuite "LockDecls" [ 'prop_staticWeight , 'prop_instNameConflictCheck , 'prop_nodeNameConflictCheck , 'case_queueLockOpOrder ]
onponomarev/ganeti
test/hs/Test/Ganeti/JQueue/LockDecls.hs
bsd-2-clause
5,098
0
22
1,225
1,038
534
504
90
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Stack.Dot (dot ,listDependencies ,DotOpts(..) ,DotPayload(..) ,ListDepsOpts(..) ,ListDepsFormat(..) ,ListDepsFormatOpts(..) ,resolveDependencies ,printGraph ,pruneGraph ) where import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as LBC8 import qualified Data.Foldable as F import qualified Data.Sequence as Seq import qualified Data.Set as Set import qualified Data.Map as Map import qualified Data.Text as Text import qualified Data.Text.IO as Text import qualified Data.Traversable as T import Distribution.Text (display) import qualified Distribution.PackageDescription as PD import qualified Distribution.SPDX.License as SPDX import Distribution.License (License(BSD3), licenseFromSPDX) import Distribution.Types.PackageName (mkPackageName) import qualified Path import RIO.PrettyPrint (HasTerm (..), HasStylesUpdate (..)) import RIO.Process (HasProcessContext (..)) import Stack.Build (loadPackage) import Stack.Build.Installed (getInstalled, toInstallMap) import Stack.Build.Source import Stack.Constants import Stack.Package import Stack.Prelude hiding (Display (..), pkgName, loadPackage) import qualified Stack.Prelude (pkgName) import Stack.Runners import Stack.SourceMap import Stack.Types.Build import Stack.Types.Compiler (wantedToActual) import Stack.Types.Config import Stack.Types.GhcPkgId import Stack.Types.SourceMap import Stack.Build.Target(NeedTargets(..), parseTargets) -- | Options record for @stack dot@ data DotOpts = DotOpts { dotIncludeExternal :: !Bool -- ^ Include external dependencies , dotIncludeBase :: !Bool -- ^ Include dependencies on base , dotDependencyDepth :: !(Maybe Int) -- ^ Limit the depth of dependency resolution to (Just n) or continue until fixpoint , dotPrune :: !(Set PackageName) -- ^ Package names to prune from the graph , dotTargets :: [Text] -- ^ stack TARGETs to trace dependencies for , dotFlags :: !(Map ApplyCLIFlag (Map FlagName Bool)) -- ^ Flags to apply when calculating dependencies , dotTestTargets :: Bool -- ^ Like the "--test" flag for build, affects the meaning of 'dotTargets'. , dotBenchTargets :: Bool -- ^ Like the "--bench" flag for build, affects the meaning of 'dotTargets'. , dotGlobalHints :: Bool -- ^ Use global hints instead of relying on an actual GHC installation. } data ListDepsFormatOpts = ListDepsFormatOpts { listDepsSep :: !Text -- ^ Separator between the package name and details. , listDepsLicense :: !Bool -- ^ Print dependency licenses instead of versions. } data ListDepsFormat = ListDepsText ListDepsFormatOpts | ListDepsTree ListDepsFormatOpts | ListDepsJSON data ListDepsOpts = ListDepsOpts { listDepsFormat :: !ListDepsFormat -- ^ Format of printing dependencies , listDepsDotOpts :: !DotOpts -- ^ The normal dot options. } -- | Visualize the project's dependencies as a graphviz graph dot :: DotOpts -> RIO Runner () dot dotOpts = do (localNames, prunedGraph) <- createPrunedDependencyGraph dotOpts printGraph dotOpts localNames prunedGraph -- | Information about a package in the dependency graph, when available. data DotPayload = DotPayload { payloadVersion :: Maybe Version -- ^ The package version. , payloadLicense :: Maybe (Either SPDX.License License) -- ^ The license the package was released under. , payloadLocation :: Maybe PackageLocation -- ^ The location of the package. } deriving (Eq, Show) -- | Create the dependency graph and also prune it as specified in the dot -- options. Returns a set of local names and and a map from package names to -- dependencies. createPrunedDependencyGraph :: DotOpts -> RIO Runner (Set PackageName, Map PackageName (Set PackageName, DotPayload)) createPrunedDependencyGraph dotOpts = withDotConfig dotOpts $ do localNames <- view $ buildConfigL.to (Map.keysSet . smwProject . bcSMWanted) logDebug "Creating dependency graph" resultGraph <- createDependencyGraph dotOpts let pkgsToPrune = if dotIncludeBase dotOpts then dotPrune dotOpts else Set.insert "base" (dotPrune dotOpts) prunedGraph = pruneGraph localNames pkgsToPrune resultGraph logDebug "Returning prouned dependency graph" return (localNames, prunedGraph) -- | Create the dependency graph, the result is a map from a package -- name to a tuple of dependencies and payload if available. This -- function mainly gathers the required arguments for -- @resolveDependencies@. createDependencyGraph :: DotOpts -> RIO DotConfig (Map PackageName (Set PackageName, DotPayload)) createDependencyGraph dotOpts = do sourceMap <- view sourceMapL locals <- for (toList $ smProject sourceMap) loadLocalPackage let graph = Map.fromList $ projectPackageDependencies dotOpts (filter lpWanted locals) globalDump <- view $ to dcGlobalDump -- TODO: Can there be multiple entries for wired-in-packages? If so, -- this will choose one arbitrarily.. let globalDumpMap = Map.fromList $ map (\dp -> (Stack.Prelude.pkgName (dpPackageIdent dp), dp)) globalDump globalIdMap = Map.fromList $ map (\dp -> (dpGhcPkgId dp, dpPackageIdent dp)) globalDump let depLoader = createDepLoader sourceMap globalDumpMap globalIdMap loadPackageDeps loadPackageDeps name version loc flags ghcOptions cabalConfigOpts -- Skip packages that can't be loaded - see -- https://github.com/commercialhaskell/stack/issues/2967 | name `elem` [mkPackageName "rts", mkPackageName "ghc"] = return (Set.empty, DotPayload (Just version) (Just $ Right BSD3) Nothing) | otherwise = fmap (packageAllDeps &&& makePayload loc) (loadPackage loc flags ghcOptions cabalConfigOpts) resolveDependencies (dotDependencyDepth dotOpts) graph depLoader where makePayload loc pkg = DotPayload (Just $ packageVersion pkg) (Just $ packageLicense pkg) (Just $ PLImmutable loc) listDependencies :: ListDepsOpts -> RIO Runner () listDependencies opts = do let dotOpts = listDepsDotOpts opts (pkgs, resultGraph) <- createPrunedDependencyGraph dotOpts liftIO $ case listDepsFormat opts of ListDepsTree treeOpts -> Text.putStrLn "Packages" >> printTree treeOpts dotOpts 0 [] (treeRoots opts pkgs) resultGraph ListDepsJSON -> printJSON pkgs resultGraph ListDepsText textOpts -> void (Map.traverseWithKey go (snd <$> resultGraph)) where go name payload = Text.putStrLn $ listDepsLine textOpts name payload data DependencyTree = DependencyTree (Set PackageName) (Map PackageName (Set PackageName, DotPayload)) instance ToJSON DependencyTree where toJSON (DependencyTree _ dependencyMap) = toJSON $ foldToList dependencyToJSON dependencyMap foldToList :: (k -> a -> b) -> Map k a -> [b] foldToList f = Map.foldrWithKey (\k a bs -> bs ++ [f k a]) [] dependencyToJSON :: PackageName -> (Set PackageName, DotPayload) -> Value dependencyToJSON pkg (deps, payload) = let fieldsAlwaysPresent = [ "name" .= packageNameString pkg , "license" .= licenseText payload , "version" .= versionText payload , "dependencies" .= Set.map packageNameString deps ] loc = catMaybes [("location" .=) . pkgLocToJSON <$> payloadLocation payload] in object $ fieldsAlwaysPresent ++ loc pkgLocToJSON :: PackageLocation -> Value pkgLocToJSON (PLMutable (ResolvedPath _ dir)) = object [ "type" .= ("project package" :: Text) , "url" .= ("file://" ++ Path.toFilePath dir)] pkgLocToJSON (PLImmutable (PLIHackage pkgid _ _)) = object [ "type" .= ("hackage" :: Text) , "url" .= ("https://hackage.haskell.org/package/" ++ display pkgid)] pkgLocToJSON (PLImmutable (PLIArchive archive _)) = let url = case archiveLocation archive of ALUrl u -> u ALFilePath (ResolvedPath _ path) -> Text.pack $ "file://" ++ Path.toFilePath path in object [ "type" .= ("archive" :: Text) , "url" .= url , "sha256" .= archiveHash archive , "size" .= archiveSize archive ] pkgLocToJSON (PLImmutable (PLIRepo repo _)) = object [ "type" .= case repoType repo of RepoGit -> "git" :: Text RepoHg -> "hg" :: Text , "url" .= repoUrl repo , "commit" .= repoCommit repo , "subdir" .= repoSubdir repo ] printJSON :: Set PackageName -> Map PackageName (Set PackageName, DotPayload) -> IO () printJSON pkgs dependencyMap = LBC8.putStrLn $ encode $ DependencyTree pkgs dependencyMap treeRoots :: ListDepsOpts -> Set PackageName -> Set PackageName treeRoots opts projectPackages' = let targets = dotTargets $ listDepsDotOpts opts in if null targets then projectPackages' else Set.fromList $ map (mkPackageName . Text.unpack) targets printTree :: ListDepsFormatOpts -> DotOpts -> Int -> [Int] -> Set PackageName -> Map PackageName (Set PackageName, DotPayload) -> IO () printTree opts dotOpts depth remainingDepsCounts packages dependencyMap = F.sequence_ $ Seq.mapWithIndex go (toSeq packages) where toSeq = Seq.fromList . Set.toList go index name = let newDepsCounts = remainingDepsCounts ++ [Set.size packages - index - 1] in case Map.lookup name dependencyMap of Just (deps, payload) -> do printTreeNode opts dotOpts depth newDepsCounts deps payload name if Just depth == dotDependencyDepth dotOpts then return () else printTree opts dotOpts (depth + 1) newDepsCounts deps dependencyMap -- TODO: Define this behaviour, maybe return an error? Nothing -> return () printTreeNode :: ListDepsFormatOpts -> DotOpts -> Int -> [Int] -> Set PackageName -> DotPayload -> PackageName -> IO () printTreeNode opts dotOpts depth remainingDepsCounts deps payload name = let remainingDepth = fromMaybe 999 (dotDependencyDepth dotOpts) - depth hasDeps = not $ null deps in Text.putStrLn $ treeNodePrefix "" remainingDepsCounts hasDeps remainingDepth <> " " <> listDepsLine opts name payload treeNodePrefix :: Text -> [Int] -> Bool -> Int -> Text treeNodePrefix t [] _ _ = t treeNodePrefix t [0] True 0 = t <> "└──" treeNodePrefix t [_] True 0 = t <> "├──" treeNodePrefix t [0] True _ = t <> "└─┬" treeNodePrefix t [_] True _ = t <> "├─┬" treeNodePrefix t [0] False _ = t <> "└──" treeNodePrefix t [_] False _ = t <> "├──" treeNodePrefix t (0:ns) d remainingDepth = treeNodePrefix (t <> " ") ns d remainingDepth treeNodePrefix t (_:ns) d remainingDepth = treeNodePrefix (t <> "│ ") ns d remainingDepth listDepsLine :: ListDepsFormatOpts -> PackageName -> DotPayload -> Text listDepsLine opts name payload = Text.pack (packageNameString name) <> listDepsSep opts <> payloadText opts payload payloadText :: ListDepsFormatOpts -> DotPayload -> Text payloadText opts payload = if listDepsLicense opts then licenseText payload else versionText payload licenseText :: DotPayload -> Text licenseText payload = maybe "<unknown>" (Text.pack . display . either licenseFromSPDX id) (payloadLicense payload) versionText :: DotPayload -> Text versionText payload = maybe "<unknown>" (Text.pack . display) (payloadVersion payload) -- | @pruneGraph dontPrune toPrune graph@ prunes all packages in -- @graph@ with a name in @toPrune@ and removes resulting orphans -- unless they are in @dontPrune@ pruneGraph :: (F.Foldable f, F.Foldable g, Eq a) => f PackageName -> g PackageName -> Map PackageName (Set PackageName, a) -> Map PackageName (Set PackageName, a) pruneGraph dontPrune names = pruneUnreachable dontPrune . Map.mapMaybeWithKey (\pkg (pkgDeps,x) -> if pkg `F.elem` names then Nothing else let filtered = Set.filter (\n -> n `F.notElem` names) pkgDeps in if Set.null filtered && not (Set.null pkgDeps) then Nothing else Just (filtered,x)) -- | Make sure that all unreachable nodes (orphans) are pruned pruneUnreachable :: (Eq a, F.Foldable f) => f PackageName -> Map PackageName (Set PackageName, a) -> Map PackageName (Set PackageName, a) pruneUnreachable dontPrune = fixpoint prune where fixpoint :: Eq a => (a -> a) -> a -> a fixpoint f v = if f v == v then v else fixpoint f (f v) prune graph' = Map.filterWithKey (\k _ -> reachable k) graph' where reachable k = k `F.elem` dontPrune || k `Set.member` reachables reachables = F.fold (fst <$> graph') -- | Resolve the dependency graph up to (Just depth) or until fixpoint is reached resolveDependencies :: (Applicative m, Monad m) => Maybe Int -> Map PackageName (Set PackageName, DotPayload) -> (PackageName -> m (Set PackageName, DotPayload)) -> m (Map PackageName (Set PackageName, DotPayload)) resolveDependencies (Just 0) graph _ = return graph resolveDependencies limit graph loadPackageDeps = do let values = Set.unions (fst <$> Map.elems graph) keys = Map.keysSet graph next = Set.difference values keys if Set.null next then return graph else do x <- T.traverse (\name -> (name,) <$> loadPackageDeps name) (F.toList next) resolveDependencies (subtract 1 <$> limit) (Map.unionWith unifier graph (Map.fromList x)) loadPackageDeps where unifier (pkgs1,v1) (pkgs2,_) = (Set.union pkgs1 pkgs2, v1) -- | Given a SourceMap and a dependency loader, load the set of dependencies for a package createDepLoader :: SourceMap -> Map PackageName DumpPackage -> Map GhcPkgId PackageIdentifier -> (PackageName -> Version -> PackageLocationImmutable -> Map FlagName Bool -> [Text] -> [Text] -> RIO DotConfig (Set PackageName, DotPayload)) -> PackageName -> RIO DotConfig (Set PackageName, DotPayload) createDepLoader sourceMap globalDumpMap globalIdMap loadPackageDeps pkgName = do fromMaybe noDepsErr (projectPackageDeps <|> dependencyDeps <|> globalDeps) where projectPackageDeps = loadDeps <$> Map.lookup pkgName (smProject sourceMap) where loadDeps pp = do pkg <- loadCommonPackage (ppCommon pp) pure (packageAllDeps pkg, payloadFromLocal pkg Nothing) dependencyDeps = loadDeps <$> Map.lookup pkgName (smDeps sourceMap) where loadDeps DepPackage{dpLocation=PLMutable dir} = do pp <- mkProjectPackage YesPrintWarnings dir False pkg <- loadCommonPackage (ppCommon pp) pure (packageAllDeps pkg, payloadFromLocal pkg (Just $ PLMutable dir)) loadDeps dp@DepPackage{dpLocation=PLImmutable loc} = do let common = dpCommon dp gpd <- liftIO $ cpGPD common let PackageIdentifier name version = PD.package $ PD.packageDescription gpd flags = cpFlags common ghcOptions = cpGhcOptions common cabalConfigOpts = cpCabalConfigOpts common assert (pkgName == name) (loadPackageDeps pkgName version loc flags ghcOptions cabalConfigOpts) -- If package is a global package, use info from ghc-pkg (#4324, #3084) globalDeps = pure . getDepsFromDump <$> Map.lookup pkgName globalDumpMap where getDepsFromDump dump = (Set.fromList deps, payloadFromDump dump) where deps = map ghcIdToPackageName (dpDepends dump) ghcIdToPackageName depId = let errText = "Invariant violated: Expected to find " in maybe (error (errText ++ ghcPkgIdString depId ++ " in global DB")) Stack.Prelude.pkgName (Map.lookup depId globalIdMap) noDepsErr = error ("Invariant violated: The '" ++ packageNameString pkgName ++ "' package was not found in any of the dependency sources") payloadFromLocal pkg loc = DotPayload (Just $ packageVersion pkg) (Just $ packageLicense pkg) loc payloadFromDump dp = DotPayload (Just $ pkgVersion $ dpPackageIdent dp) (Right <$> dpLicense dp) Nothing -- | Resolve the direct (depth 0) external dependencies of the given local packages (assumed to come from project packages) projectPackageDependencies :: DotOpts -> [LocalPackage] -> [(PackageName, (Set PackageName, DotPayload))] projectPackageDependencies dotOpts locals = map (\lp -> let pkg = localPackageToPackage lp pkgDir = Path.parent $ lpCabalFile lp loc = PLMutable $ ResolvedPath (RelFilePath "N/A") pkgDir in (packageName pkg, (deps pkg, lpPayload pkg loc))) locals where deps pkg = if dotIncludeExternal dotOpts then Set.delete (packageName pkg) (packageAllDeps pkg) else Set.intersection localNames (packageAllDeps pkg) localNames = Set.fromList $ map (packageName . lpPackage) locals lpPayload pkg loc = DotPayload (Just $ packageVersion pkg) (Just $ packageLicense pkg) (Just loc) -- | Print a graphviz graph of the edges in the Map and highlight the given local packages printGraph :: (Applicative m, MonadIO m) => DotOpts -> Set PackageName -- ^ all locals -> Map PackageName (Set PackageName, DotPayload) -> m () printGraph dotOpts locals graph = do liftIO $ Text.putStrLn "strict digraph deps {" printLocalNodes dotOpts filteredLocals printLeaves graph void (Map.traverseWithKey printEdges (fst <$> graph)) liftIO $ Text.putStrLn "}" where filteredLocals = Set.filter (\local' -> local' `Set.notMember` dotPrune dotOpts) locals -- | Print the local nodes with a different style depending on options printLocalNodes :: (F.Foldable t, MonadIO m) => DotOpts -> t PackageName -> m () printLocalNodes dotOpts locals = liftIO $ Text.putStrLn (Text.intercalate "\n" lpNodes) where applyStyle :: Text -> Text applyStyle n = if dotIncludeExternal dotOpts then n <> " [style=dashed];" else n <> " [style=solid];" lpNodes :: [Text] lpNodes = map (applyStyle . nodeName) (F.toList locals) -- | Print nodes without dependencies printLeaves :: MonadIO m => Map PackageName (Set PackageName, DotPayload) -> m () printLeaves = F.mapM_ printLeaf . Map.keysSet . Map.filter Set.null . fmap fst -- | @printDedges p ps@ prints an edge from p to every ps printEdges :: MonadIO m => PackageName -> Set PackageName -> m () printEdges package deps = F.forM_ deps (printEdge package) -- | Print an edge between the two package names printEdge :: MonadIO m => PackageName -> PackageName -> m () printEdge from to' = liftIO $ Text.putStrLn (Text.concat [ nodeName from, " -> ", nodeName to', ";"]) -- | Convert a package name to a graph node name. nodeName :: PackageName -> Text nodeName name = "\"" <> Text.pack (packageNameString name) <> "\"" -- | Print a node with no dependencies printLeaf :: MonadIO m => PackageName -> m () printLeaf package = liftIO . Text.putStrLn . Text.concat $ if isWiredIn package then ["{rank=max; ", nodeName package, " [shape=box]; };"] else ["{rank=max; ", nodeName package, "; };"] -- | Check if the package is wired in (shipped with) ghc isWiredIn :: PackageName -> Bool isWiredIn = (`Set.member` wiredInPackages) localPackageToPackage :: LocalPackage -> Package localPackageToPackage lp = fromMaybe (lpPackage lp) (lpTestBench lp) -- Plumbing for --test and --bench flags withDotConfig :: DotOpts -> RIO DotConfig a -> RIO Runner a withDotConfig opts inner = local (over globalOptsL modifyGO) $ if dotGlobalHints opts then withConfig NoReexec $ withBuildConfig withGlobalHints else withConfig YesReexec withReal where withGlobalHints = do bconfig <- view buildConfigL globals <- globalsFromHints $ smwCompiler $ bcSMWanted bconfig fakeGhcPkgId <- parseGhcPkgId "ignored" actual <- either throwIO pure $ wantedToActual $ smwCompiler $ bcSMWanted bconfig let smActual = SMActual { smaCompiler = actual , smaProject = smwProject $ bcSMWanted bconfig , smaDeps = smwDeps $ bcSMWanted bconfig , smaGlobal = Map.mapWithKey toDump globals } toDump :: PackageName -> Version -> DumpPackage toDump name version = DumpPackage { dpGhcPkgId = fakeGhcPkgId , dpPackageIdent = PackageIdentifier name version , dpParentLibIdent = Nothing , dpLicense = Nothing , dpLibDirs = [] , dpLibraries = [] , dpHasExposedModules = True , dpExposedModules = mempty , dpDepends = [] , dpHaddockInterfaces = [] , dpHaddockHtml = Nothing , dpIsExposed = True } actualPkgs = Map.keysSet (smaDeps smActual) <> Map.keysSet (smaProject smActual) prunedActual = smActual { smaGlobal = pruneGlobals (smaGlobal smActual) actualPkgs } targets <- parseTargets NeedTargets False boptsCLI prunedActual logDebug "Loading source map" sourceMap <- loadSourceMap targets boptsCLI smActual let dc = DotConfig { dcBuildConfig = bconfig , dcSourceMap = sourceMap , dcGlobalDump = toList $ smaGlobal smActual } logDebug "DotConfig fully loaded" runRIO dc inner withReal = withEnvConfig NeedTargets boptsCLI $ do envConfig <- ask let sourceMap = envConfigSourceMap envConfig installMap <- toInstallMap sourceMap (_, globalDump, _, _) <- getInstalled installMap let dc = DotConfig { dcBuildConfig = envConfigBuildConfig envConfig , dcSourceMap = sourceMap , dcGlobalDump = globalDump } runRIO dc inner boptsCLI = defaultBuildOptsCLI { boptsCLITargets = dotTargets opts , boptsCLIFlags = dotFlags opts } modifyGO = (if dotTestTargets opts then set (globalOptsBuildOptsMonoidL.buildOptsMonoidTestsL) (Just True) else id) . (if dotBenchTargets opts then set (globalOptsBuildOptsMonoidL.buildOptsMonoidBenchmarksL) (Just True) else id) data DotConfig = DotConfig { dcBuildConfig :: !BuildConfig , dcSourceMap :: !SourceMap , dcGlobalDump :: ![DumpPackage] } instance HasLogFunc DotConfig where logFuncL = runnerL.logFuncL instance HasPantryConfig DotConfig where pantryConfigL = configL.pantryConfigL instance HasTerm DotConfig where useColorL = runnerL.useColorL termWidthL = runnerL.termWidthL instance HasStylesUpdate DotConfig where stylesUpdateL = runnerL.stylesUpdateL instance HasGHCVariant DotConfig instance HasPlatform DotConfig instance HasRunner DotConfig where runnerL = configL.runnerL instance HasProcessContext DotConfig where processContextL = runnerL.processContextL instance HasConfig DotConfig instance HasBuildConfig DotConfig where buildConfigL = lens dcBuildConfig (\x y -> x { dcBuildConfig = y }) instance HasSourceMap DotConfig where sourceMapL = lens dcSourceMap (\x y -> x { dcSourceMap = y })
juhp/stack
src/Stack/Dot.hs
bsd-3-clause
25,549
7
20
7,452
6,107
3,167
2,940
461
4
module Sql.Utils where import Database.HDBC import Database.HDBC.Sqlite3 import Data.Maybe import Types conn :: IO Connection conn = connectSqlite3 "hunter.db" fetch :: Connection -> String -> [SqlValue] -> IO (Maybe [SqlValue]) fetch c s vs = do com <- prepare c s execute com vs fetchRow com lastRowId :: Connection -> IO (Maybe Int) lastRowId c = do res <- fetch c "SELECT last_insert_rowid()" [] return $ fromSql <$> (listToMaybe =<< res)
hherman1/CatanServ
src/Sql/Utils.hs
bsd-3-clause
467
0
11
95
171
86
85
16
1
-- | Item and treasure definitions. module Content.ItemKind ( cdefs ) where import qualified Data.EnumMap.Strict as EM import Data.List import Content.ItemKindActor import Content.ItemKindBlast import Content.ItemKindOrgan import Content.ItemKindTemporary import Game.LambdaHack.Common.Ability import Game.LambdaHack.Common.Color import Game.LambdaHack.Common.ContentDef import Game.LambdaHack.Common.Dice import Game.LambdaHack.Common.Flavour import Game.LambdaHack.Common.Misc import Game.LambdaHack.Content.ItemKind cdefs :: ContentDef ItemKind cdefs = ContentDef { getSymbol = isymbol , getName = iname , getFreq = ifreq , validateSingle = validateSingleItemKind , validateAll = validateAllItemKind , content = items ++ organs ++ blasts ++ actors ++ temporaries } items :: [ItemKind] items = [dart, dart200, paralizingProj, harpoon, net, jumpingPole, sharpeningTool, seeingItem, light1, light2, light3, gorget, necklace1, necklace2, necklace3, necklace4, necklace5, necklace6, necklace7, necklace8, necklace9, sightSharpening, ring1, ring2, ring3, ring4, ring5, ring6, ring7, ring8, potion1, potion2, potion3, potion4, potion5, potion6, potion7, potion8, potion9, flask1, flask2, flask3, flask4, flask5, flask6, flask7, flask8, flask9, flask10, flask11, flask12, flask13, flask14, scroll1, scroll2, scroll3, scroll4, scroll5, scroll6, scroll7, scroll8, scroll9, scroll10, scroll11, armorLeather, armorMail, gloveFencing, gloveGauntlet, gloveJousting, buckler, shield, dagger, daggerDropBestWeapon, hammer, hammerParalyze, hammerSpark, sword, swordImpress, swordNullify, halberd, halberdPushActor, wand1, wand2, gem1, gem2, gem3, gem4, currency] dart, dart200, paralizingProj, harpoon, net, jumpingPole, sharpeningTool, seeingItem, light1, light2, light3, gorget, necklace1, necklace2, necklace3, necklace4, necklace5, necklace6, necklace7, necklace8, necklace9, sightSharpening, ring1, ring2, ring3, ring4, ring5, ring6, ring7, ring8, potion1, potion2, potion3, potion4, potion5, potion6, potion7, potion8, potion9, flask1, flask2, flask3, flask4, flask5, flask6, flask7, flask8, flask9, flask10, flask11, flask12, flask13, flask14, scroll1, scroll2, scroll3, scroll4, scroll5, scroll6, scroll7, scroll8, scroll9, scroll10, scroll11, armorLeather, armorMail, gloveFencing, gloveGauntlet, gloveJousting, buckler, shield, dagger, daggerDropBestWeapon, hammer, hammerParalyze, hammerSpark, sword, swordImpress, swordNullify, halberd, halberdPushActor, wand1, wand2, gem1, gem2, gem3, gem4, currency :: ItemKind necklace, ring, potion, flask, scroll, wand, gem :: ItemKind -- generic templates -- * Item group symbols, partially from Nethack symbolProjectile, _symbolLauncher, symbolLight, symbolTool, symbolGem, symbolGold, symbolNecklace, symbolRing, symbolPotion, symbolFlask, symbolScroll, symbolTorsoArmor, symbolMiscArmor, _symbolClothes, symbolShield, symbolPolearm, symbolEdged, symbolHafted, symbolWand, _symbolStaff, _symbolFood :: Char symbolProjectile = '|' _symbolLauncher = '}' symbolLight = '(' symbolTool = '(' symbolGem = '*' symbolGold = '$' symbolNecklace = '"' symbolRing = '=' symbolPotion = '!' -- concoction, bottle, jar, vial, canister symbolFlask = '!' symbolScroll = '?' -- book, note, tablet, remote symbolTorsoArmor = '[' symbolMiscArmor = '[' _symbolClothes = '(' symbolShield = '[' symbolPolearm = ')' symbolEdged = ')' symbolHafted = ')' symbolWand = '/' -- magical rod, transmitter, pistol, rifle _symbolStaff = '_' -- scanner _symbolFood = ',' -- too easy to miss? -- * Thrown weapons dart = ItemKind { isymbol = symbolProjectile , iname = "dart" , ifreq = [("useful", 100), ("any arrow", 100)] , iflavour = zipPlain [Cyan] , icount = 4 * d 3 , irarity = [(1, 10), (10, 20)] , iverbHit = "nick" , iweight = 50 , iaspects = [AddHurtRanged (d 3 + dl 6 |*| 20)] , ieffects = [Hurt (2 * d 1)] , ifeature = [Identified] , idesc = "Little, but sharp and sturdy." -- "Much inferior to arrows though, especially given the contravariance problems." --- funny, but destroy the suspension of disbelief; this is supposed to be a Lovecraftian horror and any hilarity must ensue from the failures in making it so and not from actively trying to be funny; also, mundane objects are not supposed to be scary or transcendental; the scare is in horrors from the abstract dimension visiting our ordinary reality; without the contrast there's no horror and no wonder, so also the magical items must be contrasted with ordinary XIX century and antique items , ikit = [] } dart200 = ItemKind { isymbol = symbolProjectile , iname = "fine dart" , ifreq = [("useful", 100), ("any arrow", 50)] -- TODO: until arrows added , iflavour = zipPlain [BrRed] , icount = 4 * d 3 , irarity = [(1, 20), (10, 10)] , iverbHit = "prick" , iweight = 50 , iaspects = [AddHurtRanged (d 3 + dl 6 |*| 20)] , ieffects = [Hurt (1 * d 1)] , ifeature = [toVelocity 200, Identified] , idesc = "Finely balanced for throws of great speed." , ikit = [] } -- * Exotic thrown weapons paralizingProj = ItemKind { isymbol = symbolProjectile , iname = "bolas set" , ifreq = [("useful", 100)] , iflavour = zipPlain [BrYellow] , icount = dl 4 , irarity = [(5, 5), (10, 5)] , iverbHit = "entangle" , iweight = 500 , iaspects = [] , ieffects = [Hurt (2 * d 1), Paralyze (5 + d 5), DropBestWeapon] , ifeature = [Identified] , idesc = "Wood balls tied with hemp rope. The target enemy is tripped and bound to drop the main weapon, while fighting for balance." , ikit = [] } harpoon = ItemKind { isymbol = symbolProjectile , iname = "harpoon" , ifreq = [("useful", 100)] , iflavour = zipPlain [Brown] , icount = dl 5 , irarity = [(10, 10)] , iverbHit = "hook" , iweight = 4000 , iaspects = [AddHurtRanged (d 2 + dl 5 |*| 20)] , ieffects = [Hurt (4 * d 1), PullActor (ThrowMod 200 50)] , ifeature = [Identified] , idesc = "The cruel, barbed head lodges in its victim so painfully that the weakest tug of the thin line sends the victim flying." , ikit = [] } net = ItemKind { isymbol = symbolProjectile , iname = "net" , ifreq = [("useful", 100)] , iflavour = zipPlain [White] , icount = dl 3 , irarity = [(3, 5), (10, 4)] , iverbHit = "entangle" , iweight = 1000 , iaspects = [] , ieffects = [ toOrganGameTurn "slow 10" (3 + d 3) , DropItem CEqp "torso armor" False ] , ifeature = [Identified] , idesc = "A wide net with weights along the edges. Entangles armor and restricts movement." , ikit = [] } -- * Assorted tools jumpingPole = ItemKind { isymbol = symbolTool , iname = "jumping pole" , ifreq = [("useful", 100)] , iflavour = zipPlain [White] , icount = 1 , irarity = [(1, 2)] , iverbHit = "prod" , iweight = 10000 , iaspects = [Timeout $ d 2 + 2 - dl 2 |*| 10] , ieffects = [Recharging (toOrganActorTurn "fast 20" 1)] , ifeature = [Durable, Applicable, Identified] , idesc = "Makes you vulnerable at take-off, but then you are free like a bird." , ikit = [] } sharpeningTool = ItemKind { isymbol = symbolTool , iname = "whetstone" , ifreq = [("useful", 100)] , iflavour = zipPlain [Blue] , icount = 1 , irarity = [(10, 10)] , iverbHit = "smack" , iweight = 400 , iaspects = [AddHurtMelee $ d 10 |*| 3] , ieffects = [] , ifeature = [EqpSlot EqpSlotAddHurtMelee "", Identified] , idesc = "A portable sharpening stone that lets you fix your weapons between or even during fights, without the need to set up camp, fish out tools and assemble a proper sharpening workshop." , ikit = [] } seeingItem = ItemKind { isymbol = '%' , iname = "pupil" , ifreq = [("useful", 100)] , iflavour = zipPlain [Red] , icount = 1 , irarity = [(1, 1)] , iverbHit = "gaze at" , iweight = 100 , iaspects = [ AddSight 10, AddMaxCalm 60, AddLight 2 , Periodic, Timeout $ 1 + d 2 ] , ieffects = [ Recharging (toOrganNone "poisoned") , Recharging (Summon [("mobile monster", 1)] 1) ] , ifeature = [Identified] , idesc = "A slimy, dilated green pupil torn out from some giant eye. Clear and focused, as if still alive." , ikit = [] } -- * Lights light1 = ItemKind { isymbol = symbolLight , iname = "wooden torch" , ifreq = [("useful", 100), ("light source", 100)] , iflavour = zipPlain [Brown] , icount = d 2 , irarity = [(1, 10)] , iverbHit = "scorch" , iweight = 1200 , iaspects = [ AddLight 3 -- not only flashes, but also sparks , AddSight (-2) ] -- unused by AI due to the mixed blessing , ieffects = [Burn 2] , ifeature = [EqpSlot EqpSlotAddLight "", Identified] , idesc = "A smoking, heavy wooden torch, burning in an unsteady glow." , ikit = [] } light2 = ItemKind { isymbol = symbolLight , iname = "oil lamp" , ifreq = [("useful", 100), ("light source", 100)] , iflavour = zipPlain [BrYellow] , icount = 1 , irarity = [(6, 7)] , iverbHit = "burn" , iweight = 1000 , iaspects = [AddLight 3, AddSight (-1)] , ieffects = [Burn 3, Paralyze 3, OnSmash (Explode "burning oil 3")] , ifeature = [ toVelocity 70 -- hard not to spill the oil while throwing , Fragile, EqpSlot EqpSlotAddLight "", Identified ] , idesc = "A clay lamp filled with plant oil feeding a tiny wick." , ikit = [] } light3 = ItemKind { isymbol = symbolLight , iname = "brass lantern" , ifreq = [("useful", 100), ("light source", 100)] , iflavour = zipPlain [BrWhite] , icount = 1 , irarity = [(10, 5)] , iverbHit = "burn" , iweight = 2400 , iaspects = [AddLight 4, AddSight (-1)] , ieffects = [Burn 4, Paralyze 4, OnSmash (Explode "burning oil 4")] , ifeature = [ toVelocity 70 -- hard to throw so that it opens and burns , Fragile, EqpSlot EqpSlotAddLight "", Identified ] , idesc = "Very bright and very heavy brass lantern." , ikit = [] } -- * Periodic jewelry gorget = ItemKind { isymbol = symbolNecklace , iname = "Old Gorget" , ifreq = [("useful", 100)] , iflavour = zipFancy [BrCyan] , icount = 1 , irarity = [(4, 3), (10, 3)] -- weak, shallow , iverbHit = "whip" , iweight = 30 , iaspects = [ Unique , Periodic , Timeout $ 1 + d 2 , AddArmorMelee $ 2 + d 3 , AddArmorRanged $ 2 + d 3 ] , ieffects = [Recharging (RefillCalm 1)] , ifeature = [ Durable, Precious, EqpSlot EqpSlotPeriodic "" , Identified, toVelocity 50 ] -- not dense enough , idesc = "Highly ornamental, cold, large, steel medallion on a chain. Unlikely to offer much protection as an armor piece, but the old, worn engraving reassures you." , ikit = [] } necklace = ItemKind { isymbol = symbolNecklace , iname = "necklace" , ifreq = [("useful", 100)] , iflavour = zipFancy stdCol ++ zipPlain brightCol , icount = 1 , irarity = [(10, 2)] , iverbHit = "whip" , iweight = 30 , iaspects = [Periodic] , ieffects = [] , ifeature = [ Precious, EqpSlot EqpSlotPeriodic "" , toVelocity 50 ] -- not dense enough , idesc = "Menacing Greek symbols shimmer with increasing speeds along a chain of fine encrusted links. After a tense build-up, a prismatic arc shoots towards the ground and the iridescence subdues, becomes ordered and resembles a harmless ornament again, for a time." , ikit = [] } necklace1 = necklace { ifreq = [("treasure", 100)] , iaspects = [Unique, Timeout $ d 3 + 4 - dl 3 |*| 10] ++ iaspects necklace , ieffects = [NoEffect "of Aromata", Recharging (RefillHP 1)] , ifeature = Durable : ifeature necklace , idesc = "A cord of freshly dried herbs and healing berries." } necklace2 = necklace { ifreq = [("treasure", 100)] -- just too nasty to call it useful , irarity = [(1, 1)] , iaspects = (Timeout $ d 3 + 3 - dl 3 |*| 10) : iaspects necklace , ieffects = [ Recharging Impress , Recharging (DropItem COrgan "temporary conditions" True) , Recharging (Summon [("mobile animal", 1)] $ 1 + dl 2) , Recharging (Explode "waste") ] } necklace3 = necklace { iaspects = (Timeout $ d 3 + 3 - dl 3 |*| 10) : iaspects necklace , ieffects = [Recharging (Paralyze $ 5 + d 5 + dl 5)] } necklace4 = necklace { iaspects = (Timeout $ d 4 + 4 - dl 4 |*| 2) : iaspects necklace , ieffects = [Recharging (Teleport $ d 2 * 3)] } necklace5 = necklace { iaspects = (Timeout $ d 3 + 4 - dl 3 |*| 10) : iaspects necklace , ieffects = [Recharging (Teleport $ 14 + d 3 * 3)] } necklace6 = necklace { iaspects = (Timeout $ d 4 |*| 10) : iaspects necklace , ieffects = [Recharging (PushActor (ThrowMod 100 50))] } necklace7 = necklace -- TODO: teach AI to wear only for fight { ifreq = [("treasure", 100)] , iaspects = [ Unique, AddMaxHP $ 10 + d 10 , AddArmorMelee 20, AddArmorRanged 20 , Timeout $ d 2 + 5 - dl 3 ] ++ iaspects necklace , ieffects = [ NoEffect "of Overdrive" , Recharging (InsertMove $ 1 + d 2) , Recharging (RefillHP (-1)) , Recharging (RefillCalm (-1)) ] , ifeature = Durable : ifeature necklace } necklace8 = necklace { iaspects = (Timeout $ d 3 + 3 - dl 3 |*| 5) : iaspects necklace , ieffects = [Recharging $ Explode "spark"] } necklace9 = necklace { iaspects = (Timeout $ d 3 + 3 - dl 3 |*| 5) : iaspects necklace , ieffects = [Recharging $ Explode "fragrance"] } -- * Non-periodic jewelry sightSharpening = ItemKind { isymbol = symbolRing , iname = "Sharp Monocle" , ifreq = [("treasure", 100)] , iflavour = zipPlain [White] , icount = 1 , irarity = [(7, 3), (10, 3)] -- medium weak, medium shallow , iverbHit = "rap" , iweight = 50 , iaspects = [Unique, AddSight $ 1 + d 2, AddHurtMelee $ d 2 |*| 3] , ieffects = [] , ifeature = [ Precious, Identified, Durable , EqpSlot EqpSlotAddSight "" ] , idesc = "Let's you better focus your weaker eye." , ikit = [] } -- Don't add standard effects to rings, because they go in and out -- of eqp and so activating them would require UI tedium: looking for -- them in eqp and inv or even activating a wrong item via letter by mistake. ring = ItemKind { isymbol = symbolRing , iname = "ring" , ifreq = [("useful", 100)] , iflavour = zipPlain stdCol ++ zipFancy darkCol , icount = 1 , irarity = [(10, 3)] , iverbHit = "knock" , iweight = 15 , iaspects = [] , ieffects = [Explode "blast 20"] , ifeature = [Precious, Identified] , idesc = "It looks like an ordinary object, but it's in fact a generator of exceptional effects: adding to some of your natural abilities and subtracting from others. You'd profit enormously if you could find a way to multiply such generators." , ikit = [] } ring1 = ring { irarity = [(10, 2)] , iaspects = [AddSpeed $ 1 + d 2, AddMaxHP $ dl 7 - 7 - d 7] , ieffects = [Explode "distortion"] -- strong magic , ifeature = ifeature ring ++ [EqpSlot EqpSlotAddSpeed ""] } ring2 = ring { irarity = [(10, 5)] , iaspects = [AddMaxHP $ 10 + dl 10, AddMaxCalm $ dl 5 - 20 - d 5] , ifeature = ifeature ring ++ [EqpSlot EqpSlotAddMaxHP ""] } ring3 = ring { irarity = [(10, 5)] , iaspects = [AddMaxCalm $ 29 + dl 10] , ifeature = ifeature ring ++ [EqpSlot EqpSlotAddMaxCalm ""] , idesc = "Cold, solid to the touch, perfectly round, engraved with solemn, strangely comforting, worn out words." } ring4 = ring { irarity = [(3, 3), (10, 5)] , iaspects = [AddHurtMelee $ d 5 + dl 5 |*| 3, AddMaxHP $ dl 3 - 5 - d 3] , ifeature = ifeature ring ++ [EqpSlot EqpSlotAddHurtMelee ""] } ring5 = ring -- by the time it's found, probably no space in eqp { irarity = [(5, 0), (10, 2)] , iaspects = [AddLight $ d 2] , ieffects = [Explode "distortion"] -- strong magic , ifeature = ifeature ring ++ [EqpSlot EqpSlotAddLight ""] , idesc = "A sturdy ring with a large, shining stone." } ring6 = ring { ifreq = [("treasure", 100)] , irarity = [(10, 2)] , iaspects = [ Unique, AddSpeed $ 3 + d 4 , AddMaxCalm $ - 20 - d 20, AddMaxHP $ - 20 - d 20 ] , ieffects = [NoEffect "of Rush"] -- no explosion, because Durable , ifeature = ifeature ring ++ [Durable, EqpSlot EqpSlotAddSpeed ""] } ring7 = ring { ifreq = [("useful", 100), ("ring of opportunity sniper", 1) ] , irarity = [(1, 1)] , iaspects = [AddSkills $ EM.fromList [(AbProject, 8)]] , ieffects = [ NoEffect "of opportunity sniper" , Explode "distortion" ] -- strong magic , ifeature = ifeature ring ++ [EqpSlot (EqpSlotAddSkills AbProject) ""] } ring8 = ring { ifreq = [("useful", 1), ("ring of opportunity grenadier", 1) ] , irarity = [(1, 1)] , iaspects = [AddSkills $ EM.fromList [(AbProject, 11)]] , ieffects = [ NoEffect "of opportunity grenadier" , Explode "distortion" ] -- strong magic , ifeature = ifeature ring ++ [EqpSlot (EqpSlotAddSkills AbProject) ""] } -- * Ordinary exploding consumables, often intended to be thrown potion = ItemKind { isymbol = symbolPotion , iname = "potion" , ifreq = [("useful", 100)] , iflavour = zipLiquid brightCol ++ zipPlain brightCol ++ zipFancy brightCol , icount = 1 , irarity = [(1, 12), (10, 9)] , iverbHit = "splash" , iweight = 200 , iaspects = [] , ieffects = [] , ifeature = [ toVelocity 50 -- oily, bad grip , Applicable, Fragile ] , idesc = "A vial of bright, frothing concoction." -- purely natural; no maths, no magic , ikit = [] } potion1 = potion { ieffects = [ NoEffect "of rose water", Impress, RefillCalm (-3) , OnSmash ApplyPerfume, OnSmash (Explode "fragrance") ] } potion2 = potion { ifreq = [("treasure", 100)] , irarity = [(6, 10), (10, 10)] , iaspects = [Unique] , ieffects = [ NoEffect "of Attraction", Impress, OverfillCalm (-20) , OnSmash (Explode "pheromone") ] } potion3 = potion { irarity = [(1, 10)] , ieffects = [ RefillHP 5, DropItem COrgan "poisoned" True , OnSmash (Explode "healing mist") ] } potion4 = potion { irarity = [(10, 10)] , ieffects = [ RefillHP 10, DropItem COrgan "poisoned" True , OnSmash (Explode "healing mist 2") ] } potion5 = potion { ieffects = [ OneOf [ OverfillHP 10, OverfillHP 5, Burn 5 , toOrganActorTurn "strengthened" (20 + d 5) ] , OnSmash (OneOf [ Explode "healing mist" , Explode "wounding mist" , Explode "fragrance" , Explode "smelly droplet" , Explode "blast 10" ]) ] } potion6 = potion { irarity = [(3, 3), (10, 6)] , ieffects = [ Impress , OneOf [ OverfillCalm (-60) , OverfillHP 20, OverfillHP 10, Burn 10 , toOrganActorTurn "fast 20" (20 + d 5) ] , OnSmash (OneOf [ Explode "healing mist 2" , Explode "calming mist" , Explode "distressing odor" , Explode "eye drop" , Explode "blast 20" ]) ] } potion7 = potion { irarity = [(1, 15), (10, 5)] , ieffects = [ DropItem COrgan "poisoned" True , OnSmash (Explode "antidote mist") ] } potion8 = potion { irarity = [(1, 5), (10, 15)] , ieffects = [ DropItem COrgan "temporary conditions" True , OnSmash (Explode "blast 10") ] } potion9 = potion { ifreq = [("treasure", 100)] , irarity = [(10, 5)] , iaspects = [Unique] , ieffects = [ NoEffect "of Love", OverfillHP 60 , Impress, OverfillCalm (-60) , OnSmash (Explode "healing mist 2") , OnSmash (Explode "pheromone") ] } -- * Exploding consumables with temporary aspects, can be thrown -- TODO: dip projectiles in those -- TODO: add flavour and realism as in, e.g., "flask of whiskey", -- which is more flavourful and believable than "flask of strength" flask = ItemKind { isymbol = symbolFlask , iname = "flask" , ifreq = [("useful", 100), ("flask", 100)] , iflavour = zipLiquid darkCol ++ zipPlain darkCol ++ zipFancy darkCol , icount = 1 , irarity = [(1, 9), (10, 6)] , iverbHit = "splash" , iweight = 500 , iaspects = [] , ieffects = [] , ifeature = [ toVelocity 50 -- oily, bad grip , Applicable, Fragile ] , idesc = "A flask of oily liquid of a suspect color." , ikit = [] } flask1 = flask { irarity = [(10, 5)] , ieffects = [ NoEffect "of strength brew" , toOrganActorTurn "strengthened" (20 + d 5) , toOrganNone "regenerating" , OnSmash (Explode "strength mist") ] } flask2 = flask { ieffects = [ NoEffect "of weakness brew" , toOrganGameTurn "weakened" (20 + d 5) , OnSmash (Explode "weakness mist") ] } flask3 = flask { ieffects = [ NoEffect "of protecting balm" , toOrganActorTurn "protected" (20 + d 5) , OnSmash (Explode "protecting balm") ] } flask4 = flask { ieffects = [ NoEffect "of PhD defense questions" , toOrganGameTurn "defenseless" (20 + d 5) , OnSmash (Explode "PhD defense question") ] } flask5 = flask { irarity = [(10, 5)] , ieffects = [ NoEffect "of haste brew" , toOrganActorTurn "fast 20" (20 + d 5) , OnSmash (Explode "haste spray") ] } flask6 = flask { ieffects = [ NoEffect "of lethargy brew" , toOrganGameTurn "slow 10" (20 + d 5) , toOrganNone "regenerating" , RefillCalm 3 , OnSmash (Explode "slowness spray") ] } flask7 = flask -- sight can be reduced from Calm, drunk, etc. { irarity = [(10, 7)] , ieffects = [ NoEffect "of eye drops" , toOrganActorTurn "far-sighted" (20 + d 5) , OnSmash (Explode "blast 10") ] } flask8 = flask { irarity = [(10, 3)] , ieffects = [ NoEffect "of smelly concoction" , toOrganActorTurn "keen-smelling" (20 + d 5) , OnSmash (Explode "blast 10") ] } flask9 = flask { ieffects = [ NoEffect "of bait cocktail" , toOrganActorTurn "drunk" (5 + d 5) , OnSmash (Summon [("mobile animal", 1)] $ 1 + dl 2) , OnSmash (Explode "waste") ] } flask10 = flask { ieffects = [ NoEffect "of whiskey" , toOrganActorTurn "drunk" (20 + d 5) , Impress, Burn 2, RefillHP 4 , OnSmash (Explode "whiskey spray") ] } flask11 = flask { irarity = [(1, 20), (10, 10)] , ieffects = [ NoEffect "of regeneration brew" , toOrganNone "regenerating" , OnSmash (Explode "healing mist") ] } flask12 = flask -- but not flask of Calm depletion, since Calm reduced often { ieffects = [ NoEffect "of poison" , toOrganNone "poisoned" , OnSmash (Explode "wounding mist") ] } flask13 = flask { irarity = [(10, 5)] , ieffects = [ NoEffect "of slow resistance" , toOrganNone "slow resistant" , OnSmash (Explode "anti-slow mist") ] } flask14 = flask { irarity = [(10, 5)] , ieffects = [ NoEffect "of poison resistance" , toOrganNone "poison resistant" , OnSmash (Explode "antidote mist") ] } -- * Non-exploding consumables, not specifically designed for throwing scroll = ItemKind { isymbol = symbolScroll , iname = "scroll" , ifreq = [("useful", 100), ("any scroll", 100)] , iflavour = zipFancy stdCol ++ zipPlain darkCol -- arcane and old , icount = 1 , irarity = [(1, 15), (10, 12)] , iverbHit = "thump" , iweight = 50 , iaspects = [] , ieffects = [] , ifeature = [ toVelocity 25 -- bad shape, even rolled up , Applicable ] , idesc = "Scraps of haphazardly scribbled mysteries from beyond. Is this equation an alchemical recipe? Is this diagram an extradimensional map? Is this formula a secret call sign?" , ikit = [] } scroll1 = scroll { ifreq = [("treasure", 100)] , irarity = [(5, 10), (10, 10)] -- mixed blessing, so available early , iaspects = [Unique] , ieffects = [ NoEffect "of Reckless Beacon" , CallFriend 1, Summon standardSummon (2 + d 2) ] } scroll2 = scroll { irarity = [] , ieffects = [] } scroll3 = scroll { irarity = [(1, 5), (10, 3)] , ieffects = [Ascend (-1)] } scroll4 = scroll { ieffects = [OneOf [ Teleport 5, RefillCalm 5, RefillCalm (-5) , InsertMove 5, Paralyze 10 ]] } scroll5 = scroll { irarity = [(10, 15)] , ieffects = [ Impress , OneOf [ Teleport 20, Ascend (-1), Ascend 1 , Summon standardSummon 2, CallFriend 1 , RefillCalm 5, OverfillCalm (-60) , CreateItem CGround "useful" TimerNone ] ] } scroll6 = scroll { ieffects = [Teleport 5] } scroll7 = scroll { ieffects = [Teleport 20] } scroll8 = scroll { irarity = [(10, 3)] , ieffects = [InsertMove $ 1 + d 2 + dl 2] } scroll9 = scroll -- TODO: remove Calm when server can tell if anything IDed { irarity = [(1, 15), (10, 10)] , ieffects = [ NoEffect "of scientific explanation" , Identify, OverfillCalm 3 ] } scroll10 = scroll -- TODO: firecracker only if an item really polymorphed? -- But currently server can't tell. { irarity = [(10, 10)] , ieffects = [ NoEffect "transfiguration" , PolyItem, Explode "firecracker 7" ] } scroll11 = scroll { ifreq = [("treasure", 100)] , irarity = [(6, 10), (10, 10)] , iaspects = [Unique] , ieffects = [NoEffect "of Prisoner Release", CallFriend 1] } standardSummon :: Freqs ItemKind standardSummon = [("mobile monster", 30), ("mobile animal", 70)] -- * Armor armorLeather = ItemKind { isymbol = symbolTorsoArmor , iname = "leather armor" , ifreq = [("useful", 100), ("torso armor", 1)] , iflavour = zipPlain [Brown] , icount = 1 , irarity = [(1, 9), (10, 3)] , iverbHit = "thud" , iweight = 7000 , iaspects = [ AddHurtMelee (-3) , AddArmorMelee $ 1 + d 2 + dl 2 |*| 5 , AddArmorRanged $ 1 + d 2 + dl 2 |*| 5 ] , ieffects = [] , ifeature = [ toVelocity 30 -- unwieldy to throw and blunt , Durable, EqpSlot EqpSlotAddArmorMelee "", Identified ] , idesc = "A stiff jacket formed from leather boiled in bee wax. Smells much better than the rest of your garment." , ikit = [] } armorMail = armorLeather { iname = "mail armor" , iflavour = zipPlain [Cyan] , irarity = [(6, 9), (10, 3)] , iweight = 12000 , iaspects = [ AddHurtMelee (-3) , AddArmorMelee $ 2 + d 2 + dl 3 |*| 5 , AddArmorRanged $ 2 + d 2 + dl 3 |*| 5 ] , idesc = "A long shirt woven from iron rings. Discourages foes from attacking your torso, making it harder for them to land a blow." } gloveFencing = ItemKind { isymbol = symbolMiscArmor , iname = "leather gauntlet" , ifreq = [("useful", 100)] , iflavour = zipPlain [BrYellow] , icount = 1 , irarity = [(5, 9), (10, 9)] , iverbHit = "flap" , iweight = 100 , iaspects = [ AddHurtMelee $ (d 2 + dl 10) |*| 3 , AddArmorRanged $ d 2 |*| 5 ] , ieffects = [] , ifeature = [ toVelocity 30 -- flaps and flutters , Durable, EqpSlot EqpSlotAddArmorRanged "", Identified ] , idesc = "A fencing glove from rough leather ensuring a good grip. Also quite effective in deflecting or even catching slow projectiles." , ikit = [] } gloveGauntlet = gloveFencing { iname = "steel gauntlet" , iflavour = zipPlain [BrCyan] , irarity = [(1, 9), (10, 3)] , iweight = 300 , iaspects = [ AddArmorMelee $ 1 + dl 2 |*| 5 , AddArmorRanged $ 1 + dl 2 |*| 5 ] , idesc = "Long leather gauntlet covered in overlapping steel plates." } gloveJousting = gloveFencing { iname = "Tournament Gauntlet" , iflavour = zipFancy [BrRed] , irarity = [(1, 3), (10, 3)] , iweight = 500 , iaspects = [ Unique , AddHurtMelee $ dl 4 - 6 |*| 3 , AddArmorMelee $ 2 + dl 2 |*| 5 , AddArmorRanged $ 2 + dl 2 |*| 5 ] , idesc = "Rigid, steel, jousting handgear. If only you had a lance. And a horse." } -- * Shields -- Shield doesn't protect against ranged attacks to prevent -- micromanagement: walking with shield, melee without. buckler = ItemKind { isymbol = symbolShield , iname = "buckler" , ifreq = [("useful", 100)] , iflavour = zipPlain [Blue] , icount = 1 , irarity = [(4, 6)] , iverbHit = "bash" , iweight = 2000 , iaspects = [ AddArmorMelee 40 , AddHurtMelee (-30) , Timeout $ d 3 + 3 - dl 3 |*| 2 ] , ieffects = [ Hurt (1 * d 1) -- to display xdy everywhre in Hurt , Recharging (PushActor (ThrowMod 200 50)) ] , ifeature = [ toVelocity 40 -- unwieldy to throw , Durable, EqpSlot EqpSlotAddArmorMelee "", Identified ] , idesc = "Heavy and unwieldy. Absorbs a percentage of melee damage, both dealt and sustained. Too small to intercept projectiles with." , ikit = [] } shield = buckler { iname = "shield" , irarity = [(8, 3)] , iflavour = zipPlain [Green] , iweight = 3000 , iaspects = [ AddArmorMelee 80 , AddHurtMelee (-70) , Timeout $ d 6 + 6 - dl 6 |*| 2 ] , ieffects = [Hurt (1 * d 1), Recharging (PushActor (ThrowMod 400 50))] , ifeature = [ toVelocity 30 -- unwieldy to throw , Durable, EqpSlot EqpSlotAddArmorMelee "", Identified ] , idesc = "Large and unwieldy. Absorbs a percentage of melee damage, both dealt and sustained. Too heavy to intercept projectiles with." } -- * Weapons dagger = ItemKind { isymbol = symbolEdged , iname = "dagger" , ifreq = [("useful", 100), ("starting weapon", 100)] , iflavour = zipPlain [BrCyan] , icount = 1 , irarity = [(1, 20)] , iverbHit = "stab" , iweight = 1000 , iaspects = [ AddHurtMelee $ d 3 + dl 3 |*| 3 , AddArmorMelee $ d 2 |*| 5 , AddHurtRanged (-60) ] -- as powerful as a dart , ieffects = [Hurt (6 * d 1)] , ifeature = [ toVelocity 40 -- ensuring it hits with the tip costs speed , Durable, EqpSlot EqpSlotWeapon "", Identified ] , idesc = "A short dagger for thrusting and parrying blows. Does not penetrate deeply, but is hard to block. Especially useful in conjunction with a larger weapon." , ikit = [] } daggerDropBestWeapon = dagger { iname = "Double Dagger" , ifreq = [("treasure", 20)] , irarity = [(1, 2), (10, 4)] -- The timeout has to be small, so that the player can count on the effect -- occuring consistently in any longer fight. Otherwise, the effect will be -- absent in some important fights, leading to the feeling of bad luck, -- but will manifest sometimes in fights where it doesn't matter, -- leading to the feeling of wasted power. -- If the effect is very powerful and so the timeout has to be significant, -- let's make it really large, for the effect to occur only once in a fight: -- as soon as the item is equipped, or just on the first strike. , iaspects = [Unique, Timeout $ d 3 + 4 - dl 3 |*| 2] , ieffects = ieffects dagger ++ [Recharging DropBestWeapon, Recharging $ RefillCalm (-3)] , idesc = "A double dagger that a focused fencer can use to catch and twist an opponent's blade occasionally." } hammer = ItemKind { isymbol = symbolHafted , iname = "war hammer" , ifreq = [("useful", 100), ("starting weapon", 100)] , iflavour = zipPlain [BrMagenta] , icount = 1 , irarity = [(5, 15)] , iverbHit = "club" , iweight = 1500 , iaspects = [ AddHurtMelee $ d 2 + dl 2 |*| 3 , AddHurtRanged (-80) ] -- as powerful as a dart , ieffects = [Hurt (8 * d 1)] , ifeature = [ toVelocity 20 -- ensuring it hits with the sharp tip costs , Durable, EqpSlot EqpSlotWeapon "", Identified ] , idesc = "It may not cause grave wounds, but neither does it glance off nor ricochet. Great sidearm for opportunistic blows against armored foes." , ikit = [] } hammerParalyze = hammer { iname = "Concussion Hammer" , ifreq = [("treasure", 20)] , irarity = [(5, 2), (10, 4)] , iaspects = [Unique, Timeout $ d 2 + 3 - dl 2 |*| 2] , ieffects = ieffects hammer ++ [Recharging $ Paralyze 5] } hammerSpark = hammer { iname = "Grand Smithhammer" , ifreq = [("treasure", 20)] , irarity = [(5, 2), (10, 4)] , iaspects = [Unique, Timeout $ d 4 + 4 - dl 4 |*| 2] , ieffects = ieffects hammer ++ [Recharging $ Explode "spark"] } sword = ItemKind { isymbol = symbolEdged , iname = "sword" , ifreq = [("useful", 100), ("starting weapon", 100)] , iflavour = zipPlain [BrBlue] , icount = 1 , irarity = [(4, 1), (5, 15)] , iverbHit = "slash" , iweight = 2000 , iaspects = [] , ieffects = [Hurt (10 * d 1)] , ifeature = [ toVelocity 5 -- ensuring it hits with the tip costs speed , Durable, EqpSlot EqpSlotWeapon "", Identified ] , idesc = "Difficult to master; deadly when used effectively. The steel is particularly hard and keen, but rusts quickly without regular maintenance." , ikit = [] } swordImpress = sword { iname = "Master's Sword" , ifreq = [("treasure", 20)] , irarity = [(5, 1), (10, 4)] , iaspects = [Unique, Timeout $ d 4 + 5 - dl 4 |*| 2] , ieffects = ieffects sword ++ [Recharging Impress] , idesc = "A particularly well-balance blade, lending itself to impressive shows of fencing skill." } swordNullify = sword { iname = "Gutting Sword" , ifreq = [("treasure", 20)] , irarity = [(5, 1), (10, 4)] , iaspects = [Unique, Timeout $ d 4 + 5 - dl 4 |*| 2] , ieffects = ieffects sword ++ [ Recharging $ DropItem COrgan "temporary conditions" True , Recharging $ RefillHP (-2) ] , idesc = "Cold, thin blade that pierces deeply and sends its victim into abrupt, sobering shock." } halberd = ItemKind { isymbol = symbolPolearm , iname = "war scythe" , ifreq = [("useful", 100), ("starting weapon", 1)] , iflavour = zipPlain [BrYellow] , icount = 1 , irarity = [(7, 1), (10, 10)] , iverbHit = "impale" , iweight = 3000 , iaspects = [AddArmorMelee $ 1 + dl 3 |*| 5] , ieffects = [Hurt (12 * d 1)] , ifeature = [ toVelocity 5 -- not balanced , Durable, EqpSlot EqpSlotWeapon "", Identified ] , idesc = "An improvised but deadly weapon made of a blade from a scythe attached to a long pole." , ikit = [] } halberdPushActor = halberd { iname = "Swiss Halberd" , ifreq = [("treasure", 20)] , irarity = [(7, 1), (10, 4)] , iaspects = [Unique, Timeout $ d 5 + 5 - dl 5 |*| 2] , ieffects = ieffects halberd ++ [Recharging (PushActor (ThrowMod 400 25))] , idesc = "A versatile polearm, with great reach and leverage. Foes are held at a distance." } -- * Wands wand = ItemKind { isymbol = symbolWand , iname = "wand" , ifreq = [("useful", 100)] , iflavour = zipFancy brightCol , icount = 1 , irarity = [] -- TODO: add charges, etc. , iverbHit = "club" , iweight = 300 , iaspects = [AddLight 1, AddSpeed (-1)] -- pulsing with power, distracts , ieffects = [] , ifeature = [ toVelocity 125 -- magic , Applicable, Durable ] , idesc = "Buzzing with dazzling light that shines even through appendages that handle it." -- TODO: add math flavour , ikit = [] } wand1 = wand { ieffects = [] -- TODO: emit a cone of sound shrapnel that makes enemy cover his ears and so drop '|' and '{' } wand2 = wand { ieffects = [] } -- * Treasure gem = ItemKind { isymbol = symbolGem , iname = "gem" , ifreq = [("treasure", 100), ("gem", 100)] , iflavour = zipPlain $ delete BrYellow brightCol -- natural, so not fancy , icount = 1 , irarity = [] , iverbHit = "tap" , iweight = 50 , iaspects = [AddLight 1, AddSpeed (-1)] -- reflects strongly, distracts; so it glows in the dark, -- is visible on dark floor, but not too tempting to wear , ieffects = [] , ifeature = [Precious] , idesc = "Useless, and still worth around 100 gold each. Would gems of thought and pearls of artful design be valued that much in our age of Science and Progress!" , ikit = [] } gem1 = gem { irarity = [(2, 0), (10, 12)] } gem2 = gem { irarity = [(4, 0), (10, 14)] } gem3 = gem { irarity = [(6, 0), (10, 16)] } gem4 = gem { iname = "elixir" , iflavour = zipPlain [BrYellow] , irarity = [(1, 40), (10, 40)] , iaspects = [] , ieffects = [NoEffect "of youth", OverfillCalm 5, OverfillHP 15] , ifeature = [Identified, Applicable, Precious] -- TODO: only heal humans , idesc = "A crystal vial of amber liquid, supposedly granting eternal youth and fetching 100 gold per piece. The main effect seems to be mild euphoria, but it admittedly heals minor ailments rather well." } currency = ItemKind { isymbol = symbolGold , iname = "gold piece" , ifreq = [("treasure", 100), ("currency", 100)] , iflavour = zipPlain [BrYellow] , icount = 10 + d 20 + dl 20 , irarity = [(1, 25), (10, 10)] , iverbHit = "tap" , iweight = 31 , iaspects = [] , ieffects = [] , ifeature = [Identified, Precious] , idesc = "Reliably valuable in every civilized plane of existence." , ikit = [] }
Concomitant/LambdaHack
GameDefinition/Content/ItemKind.hs
bsd-3-clause
38,245
0
14
10,503
10,786
6,512
4,274
827
1
module Nullable where import FFI data R = R (Nullable Double) main :: Fay () main = do printD $ Nullable (1 :: Double) printNS $ Nullable "Hello, World!" printSS $ Defined ["Hello,","World!"] printD $ (Null :: Nullable Double) print' $ R (Nullable 1) print' $ R Null print' $ r1 print' $ r2 print' $ parseInt "3" print' $ parseInt "x" return () printD :: Nullable Double -> Fay () printD = ffi "console.log(%1)" printNS :: Nullable String -> Fay () printNS = ffi "console.log(%1)" printS :: Defined String -> Fay () printS = ffi "console.log(%1)" printSS :: Defined [String] -> Fay () printSS = ffi "console.log(%1)" print' :: Automatic f -> Fay () print' = ffi "console.log(%1)" r1 :: R r1 = ffi "{ instance: 'R', slot1 : 1 }" r2 :: R r2 = ffi "{ instance : 'R', slot1 : null }" parseInt :: String -> Nullable Int parseInt = ffi "(function () { var n = global.parseInt(%1, 10); if (isNaN(n)) return null; return n; })()"
beni55/fay
tests/Nullable.hs
bsd-3-clause
965
0
10
213
337
163
174
32
1
{-# LANGUAGE Haskell98, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-} {-# LINE 1 "Control/Monad/List.hs" #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.List -- Copyright : (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology, 2001 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- The List monad. -- ----------------------------------------------------------------------------- module Control.Monad.List ( ListT(..), mapListT, module Control.Monad, module Control.Monad.Trans, ) where import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.List
phischu/fragnix
tests/packages/scotty/Control.Monad.List.hs
bsd-3-clause
832
0
5
136
67
51
16
10
0
{-# Language PatternGuards #-} module Blub ( blub , foo , bar ) where import Control.Applicative (r, t, z) import Control.Foo (foo) import Ugah.Blub ( a , b , c ) f :: Int -> Int f = (+ 3) r :: Int -> Int r =
jystic/hsimport
tests/goldenFiles/SymbolTest32.hs
bsd-3-clause
237
1
6
75
88
55
33
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} -- | Extra functions for optparse-applicative. module Options.Applicative.Builder.Extra (boolFlags ,boolFlagsNoDefault ,firstBoolFlagsNoDefault ,firstBoolFlagsTrue ,firstBoolFlagsFalse ,enableDisableFlags ,enableDisableFlagsNoDefault ,extraHelpOption ,execExtraHelp ,textOption ,textArgument ,optionalFirst ,optionalFirstTrue ,optionalFirstFalse ,absFileOption ,relFileOption ,absDirOption ,relDirOption ,eitherReader' ,fileCompleter ,fileExtCompleter ,dirCompleter ,PathCompleterOpts(..) ,defaultPathCompleterOpts ,pathCompleterWith ,unescapeBashArg ) where import Data.List (isPrefixOf) import Data.Maybe import Data.Monoid hiding ((<>)) import qualified Data.Text as T import Options.Applicative import Options.Applicative.Types (readerAsk) import Path hiding ((</>)) import Stack.Prelude import System.Directory (getCurrentDirectory, getDirectoryContents, doesDirectoryExist) import System.Environment (withArgs) import System.FilePath (takeBaseName, (</>), splitFileName, isRelative, takeExtension) -- | Enable/disable flags for a 'Bool'. boolFlags :: Bool -- ^ Default value -> String -- ^ Flag name -> String -- ^ Help suffix -> Mod FlagFields Bool -> Parser Bool boolFlags defaultValue name helpSuffix = enableDisableFlags defaultValue True False name $ concat [ helpSuffix , " (default: " , if defaultValue then "enabled" else "disabled" , ")" ] -- | Enable/disable flags for a 'Bool', without a default case (to allow chaining with '<|>'). boolFlagsNoDefault :: String -- ^ Flag name -> String -- ^ Help suffix -> Mod FlagFields Bool -> Parser Bool boolFlagsNoDefault = enableDisableFlagsNoDefault True False -- | Flag with no default of True or False firstBoolFlagsNoDefault :: String -> String -> Mod FlagFields (Maybe Bool) -> Parser (First Bool) firstBoolFlagsNoDefault name helpSuffix mod' = First <$> enableDisableFlags Nothing (Just True) (Just False) name helpSuffix mod' -- | Flag with a Semigroup instance and a default of True firstBoolFlagsTrue :: String -> String -> Mod FlagFields FirstTrue -> Parser FirstTrue firstBoolFlagsTrue name helpSuffix = enableDisableFlags mempty (FirstTrue (Just True)) (FirstTrue (Just False)) name $ helpSuffix ++ " (default: enabled)" -- | Flag with a Semigroup instance and a default of False firstBoolFlagsFalse :: String -> String -> Mod FlagFields FirstFalse -> Parser FirstFalse firstBoolFlagsFalse name helpSuffix = enableDisableFlags mempty (FirstFalse (Just True)) (FirstFalse (Just False)) name $ helpSuffix ++ " (default: disabled)" -- | Enable/disable flags for any type. enableDisableFlags :: a -- ^ Default value -> a -- ^ Enabled value -> a -- ^ Disabled value -> String -- ^ Name -> String -- ^ Help suffix -> Mod FlagFields a -> Parser a enableDisableFlags defaultValue enabledValue disabledValue name helpSuffix mods = enableDisableFlagsNoDefault enabledValue disabledValue name helpSuffix mods <|> pure defaultValue -- | Enable/disable flags for any type, without a default (to allow chaining with '<|>') enableDisableFlagsNoDefault :: a -- ^ Enabled value -> a -- ^ Disabled value -> String -- ^ Name -> String -- ^ Help suffix -> Mod FlagFields a -> Parser a enableDisableFlagsNoDefault enabledValue disabledValue name helpSuffix mods = last <$> some ((flag' enabledValue (hidden <> internal <> long name <> help helpSuffix <> mods) <|> flag' disabledValue (hidden <> internal <> long ("no-" ++ name) <> help helpSuffix <> mods)) <|> flag' disabledValue (long ("[no-]" ++ name) <> help ("Enable/disable " ++ helpSuffix) <> mods)) where last xs = case reverse xs of [] -> impureThrow $ stringException "enableDisableFlagsNoDefault.last" x:_ -> x -- | Show an extra help option (e.g. @--docker-help@ shows help for all @--docker*@ args). -- -- To actually have that help appear, use 'execExtraHelp' before executing the main parser. extraHelpOption :: Bool -- ^ Hide from the brief description? -> String -- ^ Program name, e.g. @"stack"@ -> String -- ^ Option glob expression, e.g. @"docker*"@ -> String -- ^ Help option name, e.g. @"docker-help"@ -> Parser (a -> a) extraHelpOption hide progName fakeName helpName = infoOption (optDesc' ++ ".") (long helpName <> hidden <> internal) <*> infoOption (optDesc' ++ ".") (long fakeName <> help optDesc' <> (if hide then hidden <> internal else idm)) where optDesc' = concat ["Run '", takeBaseName progName, " --", helpName, "' for details"] -- | Display extra help if extra help option passed in arguments. -- -- Since optparse-applicative doesn't allow an arbitrary IO action for an 'abortOption', this -- was the best way I found that doesn't require manually formatting the help. execExtraHelp :: [String] -- ^ Command line arguments -> String -- ^ Extra help option name, e.g. @"docker-help"@ -> Parser a -- ^ Option parser for the relevant command -> String -- ^ Option description -> IO () execExtraHelp args helpOpt parser pd = when (args == ["--" ++ helpOpt]) $ withArgs ["--help"] $ do _ <- execParser (info (hiddenHelper <*> ((,) <$> parser <*> some (strArgument (metavar "OTHER ARGUMENTS") :: Parser String))) (fullDesc <> progDesc pd)) return () where hiddenHelper = abortOption ShowHelpText (long "help" <> hidden <> internal) -- | 'option', specialized to 'Text'. textOption :: Mod OptionFields Text -> Parser Text textOption = option (T.pack <$> readerAsk) -- | 'argument', specialized to 'Text'. textArgument :: Mod ArgumentFields Text -> Parser Text textArgument = argument (T.pack <$> readerAsk) -- | Like 'optional', but returning a 'First'. optionalFirst :: Alternative f => f a -> f (First a) optionalFirst = fmap First . optional -- | Like 'optional', but returning a 'FirstTrue'. optionalFirstTrue :: Alternative f => f Bool -> f FirstTrue optionalFirstTrue = fmap FirstTrue . optional -- | Like 'optional', but returning a 'FirstFalse'. optionalFirstFalse :: Alternative f => f Bool -> f FirstFalse optionalFirstFalse = fmap FirstFalse . optional absFileOption :: Mod OptionFields (Path Abs File) -> Parser (Path Abs File) absFileOption mods = option (eitherReader' parseAbsFile) $ completer (pathCompleterWith defaultPathCompleterOpts { pcoRelative = False }) <> mods relFileOption :: Mod OptionFields (Path Rel File) -> Parser (Path Rel File) relFileOption mods = option (eitherReader' parseRelFile) $ completer (pathCompleterWith defaultPathCompleterOpts { pcoAbsolute = False }) <> mods absDirOption :: Mod OptionFields (Path Abs Dir) -> Parser (Path Abs Dir) absDirOption mods = option (eitherReader' parseAbsDir) $ completer (pathCompleterWith defaultPathCompleterOpts { pcoRelative = False, pcoFileFilter = const False }) <> mods relDirOption :: Mod OptionFields (Path Rel Dir) -> Parser (Path Rel Dir) relDirOption mods = option (eitherReader' parseRelDir) $ completer (pathCompleterWith defaultPathCompleterOpts { pcoAbsolute = False, pcoFileFilter = const False }) <> mods -- | Like 'eitherReader', but accepting any @'Show' e@ on the 'Left'. eitherReader' :: Show e => (String -> Either e a) -> ReadM a eitherReader' f = eitherReader (mapLeft show . f) data PathCompleterOpts = PathCompleterOpts { pcoAbsolute :: Bool , pcoRelative :: Bool , pcoRootDir :: Maybe FilePath , pcoFileFilter :: FilePath -> Bool , pcoDirFilter :: FilePath -> Bool } defaultPathCompleterOpts :: PathCompleterOpts defaultPathCompleterOpts = PathCompleterOpts { pcoAbsolute = True , pcoRelative = True , pcoRootDir = Nothing , pcoFileFilter = const True , pcoDirFilter = const True } fileCompleter :: Completer fileCompleter = pathCompleterWith defaultPathCompleterOpts fileExtCompleter :: [String] -> Completer fileExtCompleter exts = pathCompleterWith defaultPathCompleterOpts { pcoFileFilter = (`elem` exts) . takeExtension } dirCompleter :: Completer dirCompleter = pathCompleterWith defaultPathCompleterOpts { pcoFileFilter = const False } pathCompleterWith :: PathCompleterOpts -> Completer pathCompleterWith PathCompleterOpts {..} = mkCompleter $ \inputRaw -> do -- Unescape input, to handle single and double quotes. Note that the -- results do not need to be re-escaped, due to some fiddly bash -- magic. let input = unescapeBashArg inputRaw let (inputSearchDir0, searchPrefix) = splitFileName input inputSearchDir = if inputSearchDir0 == "./" then "" else inputSearchDir0 msearchDir <- case (isRelative inputSearchDir, pcoAbsolute, pcoRelative) of (True, _, True) -> do rootDir <- maybe getCurrentDirectory return pcoRootDir return $ Just (rootDir </> inputSearchDir) (False, True, _) -> return $ Just inputSearchDir _ -> return Nothing case msearchDir of Nothing | input == "" && pcoAbsolute -> return ["/"] | otherwise -> return [] Just searchDir -> do entries <- getDirectoryContents searchDir `catch` \(_ :: IOException) -> return [] fmap catMaybes $ forM entries $ \entry -> -- Skip . and .. unless user is typing . or .. if entry `elem` ["..", "."] && searchPrefix `notElem` ["..", "."] then return Nothing else if searchPrefix `isPrefixOf` entry then do let path = searchDir </> entry case (pcoFileFilter path, pcoDirFilter path) of (True, True) -> return $ Just (inputSearchDir </> entry) (fileAllowed, dirAllowed) -> do isDir <- doesDirectoryExist path if (if isDir then dirAllowed else fileAllowed) then return $ Just (inputSearchDir </> entry) else return Nothing else return Nothing unescapeBashArg :: String -> String unescapeBashArg ('\'' : rest) = rest unescapeBashArg ('\"' : rest) = go rest where pattern = "$`\"\\\n" :: String go [] = [] go ('\\' : x : xs) | x `elem` pattern = x : xs | otherwise = '\\' : x : go xs go (x : xs) = x : go xs unescapeBashArg input = go input where go [] = [] go ('\\' : x : xs) = x : go xs go (x : xs) = x : go xs
juhp/stack
src/Options/Applicative/Builder/Extra.hs
bsd-3-clause
11,661
0
29
3,375
2,620
1,383
1,237
224
10
-- | -- Copyright : (c) 2010 Simon Meier -- License : GPL v3 (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- Portability : portable -- -- Type-class abstracting computations that need a fresh name supply. module Control.Monad.Fresh.Class ( MonadFresh(..) ) where -- import Control.Basics import Control.Monad.Trans import Control.Monad.Trans.Maybe import Control.Monad.State import Control.Monad.Reader import Control.Monad.Writer import qualified Control.Monad.Trans.FastFresh as Fast import qualified Control.Monad.Trans.PreciseFresh as Precise -- Added 'Applicative' until base states this hierarchy class (Applicative m, Monad m) => MonadFresh m where -- | Get the integer of the next fresh identifier of this name. freshIdent :: String -- ^ Desired name -> m Integer -- | Get a number of fresh identifiers. This reserves the required number -- of identifiers on all names. freshIdents :: Integer -- ^ Number of desired fresh identifiers. -> m Integer -- ^ The first Fresh identifier. -- | Scope the 'freshIdent' and 'freshIdents' requests such that these -- variables are not marked as used once the scope is left. scopeFreshness :: m a -> m a instance Monad m => MonadFresh (Fast.FreshT m) where freshIdent _name = Fast.freshIdents 1 freshIdents = Fast.freshIdents scopeFreshness = Fast.scopeFreshness instance Monad m => MonadFresh (Precise.FreshT m) where freshIdent = Precise.freshIdent freshIdents = Precise.freshIdents scopeFreshness = Precise.scopeFreshness ---------------------------------------------------------------------------- -- instances for other mtl transformers -- -- TODO: Add remaining ones instance MonadFresh m => MonadFresh (MaybeT m) where freshIdent = lift . freshIdent freshIdents = lift . freshIdents scopeFreshness m = MaybeT $ scopeFreshness (runMaybeT m) instance MonadFresh m => MonadFresh (StateT s m) where freshIdent = lift . freshIdent freshIdents = lift . freshIdents scopeFreshness m = StateT $ \s -> scopeFreshness (runStateT m s) instance MonadFresh m => MonadFresh (ReaderT r m) where freshIdent = lift . freshIdent freshIdents = lift . freshIdents scopeFreshness m = ReaderT $ \r -> scopeFreshness (runReaderT m r) instance (Monoid w, MonadFresh m) => MonadFresh (WriterT w m) where freshIdent = lift . freshIdent freshIdents = lift . freshIdents scopeFreshness m = WriterT $ scopeFreshness (runWriterT m)
tamarin-prover/tamarin-prover
lib/utils/src/Control/Monad/Fresh/Class.hs
gpl-3.0
2,592
0
10
556
515
286
229
39
0
module Hint.Type(module Hint.Type, module Idea, module HSE.All, module Refact) where import Data.Monoid import HSE.All import Idea import Prelude import Refact type DeclHint = Scope -> Module_ -> Decl_ -> [Idea] type ModuHint = Scope -> Module_ -> [Idea] type CrossHint = [(Scope, Module_)] -> [Idea] -- | Functions to generate hints, combined using the 'Monoid' instance. data Hint = Hint {hintModules :: [(Scope, Module SrcSpanInfo)] -> [Idea] -- ^ Given a list of modules (and their scope information) generate some 'Idea's. ,hintModule :: Scope -> Module SrcSpanInfo -> [Idea] -- ^ Given a single module and its scope information generate some 'Idea's. ,hintDecl :: Scope -> Module SrcSpanInfo -> Decl SrcSpanInfo -> [Idea] -- ^ Given a declaration (with a module and scope) generate some 'Idea's. -- This function will be partially applied with one module/scope, then used on multiple 'Decl' values. ,hintComment :: Comment -> [Idea] -- ^ Given a comment generate some 'Idea's. } instance Monoid Hint where mempty = Hint (const []) (\_ _ -> []) (\_ _ _ -> []) (const []) mappend (Hint x1 x2 x3 x4) (Hint y1 y2 y3 y4) = Hint (\a -> x1 a ++ y1 a) (\a b -> x2 a b ++ y2 a b) (\a b c -> x3 a b c ++ y3 a b c) (\a -> x4 a ++ y4 a)
mpickering/hlint
src/Hint/Type.hs
bsd-3-clause
1,300
0
12
295
404
226
178
18
0
{-# OPTIONS_GHC -XGADTs -XRankNTypes -O1 #-} -- #2018 module Bug1 where data A a where MkA :: A () class C w where f :: forall a . w a -> Maybe a instance C A where f MkA = Just ()
sdiehl/ghc
testsuite/tests/typecheck/should_compile/tc241.hs
bsd-3-clause
198
0
9
59
71
38
33
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for the 'Ganeti.Common' module. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.Common ( testCommon , checkOpt , passFailOpt , checkEarlyExit ) where import Test.QuickCheck hiding (Result) import Test.HUnit import qualified System.Console.GetOpt as GetOpt import System.Exit import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Ganeti.BasicTypes import Ganeti.Common import Ganeti.HTools.Program.Main (personalities) {-# ANN module "HLint: ignore Use camelCase" #-} -- | Helper to check for correct parsing of an option. checkOpt :: (StandardOptions b) => (a -> Maybe String) -- ^ Converts the value into a cmdline form -> b -- ^ The default options -> (String -> c) -- ^ Fail test function -> (String -> d -> d -> c) -- ^ Check for equality function -> (a -> d) -- ^ Transforms the value to a compare val -> (a, GenericOptType b, b -> d) -- ^ Triple of value, the -- option, function to -- extract the set value -- from the options -> c checkOpt repr defaults failfn eqcheck valfn (val, opt@(GetOpt.Option _ longs _ _, _), fn) = case longs of [] -> failfn "no long options?" cmdarg:_ -> case parseOptsInner defaults ["--" ++ cmdarg ++ maybe "" ("=" ++) (repr val)] "prog" [opt] [] of Left e -> failfn $ "Failed to parse option '" ++ cmdarg ++ ": " ++ show e Right (options, _) -> eqcheck ("Wrong value in option " ++ cmdarg ++ "?") (valfn val) (fn options) -- | Helper to check for correct and incorrect parsing of an option. passFailOpt :: (StandardOptions b) => b -- ^ The default options -> (String -> c) -- ^ Fail test function -> c -- ^ Pass function -> (GenericOptType b, String, String) -- ^ The list of enabled options, fail value and pass value -> c passFailOpt defaults failfn passfn (opt@(GetOpt.Option _ longs _ _, _), bad, good) = let first_opt = case longs of [] -> error "no long options?" x:_ -> x prefix = "--" ++ first_opt ++ "=" good_cmd = prefix ++ good bad_cmd = prefix ++ bad in case (parseOptsInner defaults [bad_cmd] "prog" [opt] [], parseOptsInner defaults [good_cmd] "prog" [opt] []) of (Left _, Right _) -> passfn (Right _, Right _) -> failfn $ "Command line '" ++ bad_cmd ++ "' succeeded when it shouldn't" (Left _, Left _) -> failfn $ "Command line '" ++ good_cmd ++ "' failed when it shouldn't" (Right _, Left _) -> failfn $ "Command line '" ++ bad_cmd ++ "' succeeded when it shouldn't, while command line '" ++ good_cmd ++ "' failed when it shouldn't" -- | Helper to test that a given option is accepted OK with quick exit. checkEarlyExit :: (StandardOptions a) => a -> String -> [GenericOptType a] -> [ArgCompletion] -> Assertion checkEarlyExit defaults name options arguments = mapM_ (\param -> case parseOptsInner defaults [param] name options arguments of Left (code, _) -> assertEqual ("Program " ++ name ++ " returns invalid code " ++ show code ++ " for option " ++ param) ExitSuccess code _ -> assertFailure $ "Program " ++ name ++ " doesn't consider option " ++ param ++ " as early exit one" ) ["-h", "--help", "-V", "--version"] -- | Test parseYesNo. prop_parse_yes_no :: Bool -> Bool -> String -> Property prop_parse_yes_no def testval val = forAll (elements [val, "yes", "no"]) $ \actual_val -> if testval then parseYesNo def Nothing ==? Ok def else let result = parseYesNo def (Just actual_val) in if actual_val `elem` ["yes", "no"] then result ==? Ok (actual_val == "yes") else property $ isBad result -- | Check that formatCmdUsage works similar to Python _FormatUsage. case_formatCommands :: Assertion case_formatCommands = assertEqual "proper wrap for HTools Main" resCmdTest (formatCommands personalities) where resCmdTest :: [String] resCmdTest = [ " hail - Ganeti IAllocator plugin that implements the instance\ \ placement and" , " movement using the same algorithm as hbal(1)" , " harep - auto-repair tool that detects certain kind of problems\ \ with" , " instances and applies the allowed set of solutions" , " hbal - cluster balancer that looks at the current state of\ \ the cluster and" , " computes a series of steps designed to bring the\ \ cluster into a" , " better state" , " hcheck - cluster checker; prints information about cluster's\ \ health and" , " checks whether a rebalance done using hbal would help" , " hinfo - cluster information printer; it prints information\ \ about the current" , " cluster state and its residing nodes/instances" , " hroller - cluster rolling maintenance helper; it helps\ \ scheduling node reboots" , " in a manner that doesn't conflict with the instances'\ \ topology" , " hscan - tool for scanning clusters via RAPI and saving their\ \ data in the" , " input format used by hbal(1) and hspace(1)" , " hspace - computes how many additional instances can be fit on a\ \ cluster," , " while maintaining N+1 status." , " hsqueeze - cluster dynamic power management; it powers up and\ \ down nodes to" , " keep the amount of free online resources in a given\ \ range" ] testSuite "Common" [ 'prop_parse_yes_no , 'case_formatCommands ]
grnet/snf-ganeti
test/hs/Test/Ganeti/Common.hs
bsd-2-clause
7,765
0
17
2,506
1,137
627
510
113
5
{-# LANGUAGE RebindableSyntax, NPlusKPatterns #-} module Main where { -- import Prelude; import qualified Prelude; import Prelude(String,undefined,Maybe(..),IO,putStrLn, Integer,(++),Rational, (==), (>=) ); import Prelude(Monad(..),Applicative(..),Functor(..)); import Control.Monad(ap, liftM); debugFunc :: String -> IO a -> IO a; debugFunc s ioa = (putStrLn ("++ " ++ s)) Prelude.>> (ioa Prelude.>>= (\a -> (putStrLn ("-- " ++ s)) Prelude.>> (Prelude.return a) )); newtype TM a = MkTM {unTM :: IO a}; instance (Functor TM) where { fmap = liftM; }; instance (Applicative TM) where { pure = return; (<*>) = ap; }; instance (Monad TM) where { return a = MkTM (debugFunc "return" (Prelude.return a)); (>>=) ma amb = MkTM (debugFunc ">>=" ((Prelude.>>=) (unTM ma) (\a -> unTM (amb a)))); (>>) ma mb = MkTM (debugFunc ">>" ((Prelude.>>) (unTM ma) (unTM mb))); fail s = MkTM (debugFunc "fail" (Prelude.return undefined)); }; preturn a = MkTM (Prelude.return a); fromInteger :: Integer -> Integer; fromInteger a = a Prelude.+ a Prelude.+ a Prelude.+ a Prelude.+ a; -- five times fromRational :: Rational -> Rational; fromRational a = a Prelude.+ a Prelude.+ a; -- three times negate :: a -> a; negate a = a; -- don't actually negate (-) :: a -> a -> a; (-) x y = y; -- changed function test_do f g = do { f; -- >> Just a <- g; -- >>= (and fail if g returns Nothing) return a; -- return }; test_fromInteger = 27; test_fromRational = 31.5; test_negate a = - a; test_fromInteger_pattern a@1 = "1=" ++ (Prelude.show a); test_fromInteger_pattern a@(-2) = "(-2)=" ++ (Prelude.show a); test_fromInteger_pattern (a + 7) = "(a + 7)=" ++ Prelude.show a; test_fromRational_pattern [email protected] = "0.5=" ++ (Prelude.show a); test_fromRational_pattern a@(-0.7) = "(-0.7)=" ++ (Prelude.show a); test_fromRational_pattern a = "_=" ++ (Prelude.show a); tmPutStrLn s = MkTM (putStrLn s); doTest :: String -> TM a -> IO (); doTest s ioa = (putStrLn ("start test " ++ s)) Prelude.>> (unTM ioa) Prelude.>> (putStrLn ("end test " ++ s)); main :: IO (); main = (doTest "test_do failure" (test_do (preturn ()) (preturn Nothing)) ) Prelude.>> (doTest "test_do success" (test_do (preturn ()) (preturn (Just ()))) ) Prelude.>> (doTest "test_fromInteger" (tmPutStrLn (Prelude.show test_fromInteger)) -- 27 * 5 = 135 ) Prelude.>> (doTest "test_fromRational" (tmPutStrLn (Prelude.show test_fromRational)) -- 31.5 * 3 = 189%2 ) Prelude.>> (doTest "test_negate" (tmPutStrLn (Prelude.show (test_negate 3))) -- 3 * 5 = 15, non-negate ) Prelude.>> (doTest "test_fromInteger_pattern 1" (tmPutStrLn (test_fromInteger_pattern 1)) -- 1 * 5 = 5, matches "1" ) Prelude.>> (doTest "test_fromInteger_pattern (-2)" (tmPutStrLn (test_fromInteger_pattern (-2))) -- "-2" = 2 * 5 = 10 ) Prelude.>> (doTest "test_fromInteger_pattern 9" (tmPutStrLn (test_fromInteger_pattern 9)) -- "9" = 45, 45 "-" "7" = "7" = 35 ) Prelude.>> (doTest "test_fromRational_pattern 0.5" (tmPutStrLn (test_fromRational_pattern 0.5)) -- "0.5" = 3%2 ) Prelude.>> (doTest "test_fromRational_pattern (-0.7)" (tmPutStrLn (test_fromRational_pattern (-0.7))) -- "-0.7" = "0.7" = 21%10 ) Prelude.>> (doTest "test_fromRational_pattern 1.7" (tmPutStrLn (test_fromRational_pattern 1.7)) -- "1.7" = 51%10 ); }
ezyang/ghc
testsuite/tests/rebindable/rebindable2.hs
bsd-3-clause
4,854
15
23
2,121
1,264
695
569
86
1
{-# LANGUAGE DataKinds, KindSignatures, TypeFamilies #-} module T9263a where import T9263b import Data.Proxy data Void instance PEq ('KProxy :: KProxy Void)
urbanslug/ghc
testsuite/tests/polykinds/T9263a.hs
bsd-3-clause
160
1
8
24
35
20
15
-1
-1
module Main where import LambdaPi.Bound import Test.Tasty import Test.Tasty.HUnit assertType :: String -> TestName -> (Expr Int, Expr Int) -> TestTree assertType s n (e, t) = testCase n $ assertBool s (hasType e t) consts :: TestTree consts = testGroup "Constant Tests" [ assertType "ETrue is wrong" "True" (ETrue, Bool) , assertType "EFalse is wrong" "False" (EFalse, Bool) , assertType "Bool is wrong" "Bool" (Bool, Star) ] boolId :: TestTree boolId = assertType "Simple lambdas failed" "Bool identity" (lam 0 (Var 0), pit 0 Bool Bool) app :: TestTree app = assertType "Application fails" "Application" (App (Annot (lam 0 $ Var 0) (pit 0 Bool Bool)) ETrue , Bool) main :: IO () main = defaultMain . testGroup "bound Tests" $ [consts, boolId, app]
jozefg/cooked-pi
test/Bound.hs
mit
838
0
12
214
285
152
133
23
1
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-} module Language.Plover.Simplify (simplify, Expr(..)) where import qualified Data.Map.Strict as M import Control.Monad (foldM) import Data.Maybe (mapMaybe) -- TODO add rebuild to atom data Expr e num = Sum [(Expr e num)] | Mul [(Expr e num)] | Atom e | Prim num | Zero | One deriving (Show, Eq, Ord) -- Monomial expression data Term e n = Term n (M.Map e Integer) | Z deriving (Show, Eq) term1 :: Num n => Term atom n term1 = Term 1 M.empty -- Main simplification function reduce :: (Ord e, Num num) => Term e num -> Expr e num -> [Term e num] reduce Z _ = return Z reduce term x = step x where -- Distribute step (Sum as) = concatMap (reduce term) as -- Sequence step (Mul as) = foldM reduce term as -- Increment step (Atom e) = let Term coefficient m = term in return $ Term coefficient (M.insertWith (+) e 1 m) -- Numeric simplify step (Prim n) = let Term coefficient m = term in return $ Term (n * coefficient) m step Zero = return $ Z step One = return $ term rebuildTerm :: Num expr => [(expr, Integer)] -> expr rebuildTerm [] = 1 rebuildTerm (e : es) = foldl (\acc pair -> acc * fix pair) (fix e) es where fix = uncurry (^) sum' :: (Num a) => [a] -> a sum' [] = 0 sum' xs = foldl1 (+) xs rebuild :: (Num expr, Eq num, Num num) => (num -> expr -> expr) -> Polynomial expr num -> expr rebuild scale poly = sum' $ mapMaybe fixPair (M.toList poly) where fixPair (_, coef) | coef == 0 = Nothing fixPair (term, coef) = Just $ scale coef (rebuildTerm term) type Polynomial expr num = M.Map [(expr, Integer)] num poly0 :: Polynomial expr num poly0 = M.empty addTerm :: (Ord expr, Eq num, Num num) => Term expr num -> Polynomial expr num -> Polynomial expr num addTerm Z p = p addTerm (Term coefficient m) p = M.insertWith (+) (M.toList m) coefficient p (.>) :: (a -> b) -> (b -> c) -> a -> c (.>) = flip (.) simplify :: (Ord expr, Num expr, Eq num, Num num) => (num -> expr -> expr) -> Expr expr num -> expr simplify scale = reduce term1 .> foldr addTerm poly0 .> rebuild scale
swift-nav/plover
src/Language/Plover/Simplify.hs
mit
2,146
0
13
524
975
516
459
58
6
-- | Implementation of an execution environment that uses /systemdNspawn/. module B9.SystemdNspawn ( SystemdNspawn (..), ) where import B9.B9Config ( getB9Config, systemdNspawnConfigs, ) import B9.B9Config.SystemdNspawn as X import B9.B9Error import B9.B9Exec import B9.B9Logging import B9.BuildInfo import B9.Container import B9.DiskImages import B9.ExecEnv import B9.ShellScript import Control.Eff import Control.Lens (view) import Control.Monad (when) import Control.Monad.IO.Class ( liftIO, ) import Data.Foldable (traverse_) import Data.List (intercalate, partition) import Data.Maybe (fromMaybe, maybe) import System.Directory import System.FilePath import Text.Printf (printf) newtype SystemdNspawn = SystemdNspawn SystemdNspawnConfig type SudoPrepender = String -> String instance Backend SystemdNspawn where getBackendConfig _ = fmap SystemdNspawn . view systemdNspawnConfigs <$> getB9Config supportedImageTypes _ = [Raw] runInEnvironment (SystemdNspawn dCfg) env scriptIn = if emptyScript scriptIn then return True else do let sudo = if _systemdNspawnUseSudo dCfg then ("sudo " ++) else id containerBuildDirs <- createContainerBuildRootDir containerMounts <- mountLoopbackImages sudo env containerBuildDirs finallyB9 ( do bootScript <- prepareBootScript containerBuildDirs scriptIn execBuild sudo containerMounts (envSharedDirectories env) bootScript dCfg ) ( do umountLoopbackImages sudo containerMounts removeContainerBuildRootDir sudo containerBuildDirs ) createContainerBuildRootDir :: (Member BuildInfoReader e, Member ExcB9 e, CommandIO e) => Eff e ContainerBuildDirectories createContainerBuildRootDir = do buildD <- getBuildDir let loopbackMountDir = root </> "loopback_mounts" root = buildD </> "container_build_root" liftIO $ do createDirectoryIfMissing True root createDirectoryIfMissing True loopbackMountDir let res = ContainerBuildDirectories {containerBuildRoot = root, containerLoopbackMountRoot = loopbackMountDir} traceL ("Created container build directories: " ++ show res) return res data ContainerBuildDirectories = ContainerBuildDirectories { containerBuildRoot :: FilePath, containerLoopbackMountRoot :: FilePath } deriving (Show) mountLoopbackImages :: (Member BuildInfoReader e, Member ExcB9 e, CommandIO e) => SudoPrepender -> ExecEnv -> ContainerBuildDirectories -> Eff e ContainerMounts mountLoopbackImages sudo e containerDirs = do let imgMounts0 = [(img, mountPoint) | (img, MountPoint mountPoint) <- envImageMounts e] imgMounts = [(imgPath, mountPoint) | (Image imgPath _ _, mountPoint) <- imgMounts0] invalidImages = [x | x@(Image _ t _, _) <- imgMounts0, t /= Raw] when (not (null invalidImages)) (throwB9Error ("Internal Error: Only 'raw' disk images can be used for container builds, and these images were supposed to be automatically converted: " ++ show invalidImages)) case partition ((== "/") . snd) imgMounts of ([rootImg], otherImgs) -> do rootMount <- mountLoopback rootImg otherMounts <- traverse mountLoopback otherImgs return (ContainerMounts (Right rootMount) otherMounts) ([], _) -> throwB9Error "A containerized build requires that a disk image for the root-, i.e. the '/' directory is configured." (rootImgs, _) -> throwB9Error ("A containerized build requires that only one disk image for the root-, i.e. the '/' directory, instead these were given: " ++ show rootImgs) where mountLoopback (imgPath, containerMountPoint) = do let hostMountPoint = containerLoopbackMountRoot containerDirs </> printHash (imgPath, containerMountPoint) liftIO $ createDirectoryIfMissing True hostMountPoint hostCmd (sudo (printf "mount -o loop '%s' '%s'" imgPath hostMountPoint)) timeoutFastCmd return ( LoopbackMount { loopbackHost = hostMountPoint, loopbackContainer = containerMountPoint } ) newtype ContainerRootImage = ContainerRootImage FilePath deriving (Show) data ContainerMounts = ContainerMounts { containerRootImage :: Either ContainerRootImage LoopbackMount, containerLoopbackMounts :: [LoopbackMount] } deriving (Show) data LoopbackMount = LoopbackMount {loopbackHost :: FilePath, loopbackContainer :: FilePath} deriving (Show) prepareBootScript :: (Member ExcB9 e, CommandIO e) => ContainerBuildDirectories -> Script -> Eff e BootScript prepareBootScript containerDirs script = do let bs = BootScript { bootScriptHostDir = containerBuildRoot containerDirs </> "boot_script", bootScriptContainerDir = "/mnt/boot_script", bootScriptContainerCommand = bootScriptContainerDir bs </> scriptFile } scriptFile = "run.sh" scriptEnv = Begin [ Run "export" ["HOME=/root"], Run "export" ["USER=root"], -- IgnoreErrors True [Run "source" ["/etc/profile"]], script ] liftIO $ do createDirectoryIfMissing True (bootScriptHostDir bs) writeSh (bootScriptHostDir bs </> scriptFile) scriptEnv traceL ("wrote script: \n" ++ show scriptEnv) traceL ("created boot-script: " ++ show bs) return bs data BootScript = BootScript { bootScriptHostDir :: FilePath, bootScriptContainerDir :: FilePath, bootScriptContainerCommand :: String } deriving (Show) execBuild :: (Member ExcB9 e, Member BuildInfoReader e, CommandIO e) => SudoPrepender -> ContainerMounts -> [SharedDirectory] -> BootScript -> SystemdNspawnConfig -> Eff e Bool execBuild sudo containerMounts sharedDirs bootScript dCfg = do let systemdCmd = unwords ( systemdNspawnExe ++ consoleOptions ++ rootImageOptions ++ capabilityOptions ++ bindMounts ++ extraArgs ++ execOptions ) systemdNspawnExe = [fromMaybe "systemd-nspawn" (_systemdNspawnExecutable dCfg)] consoleOptions = ["--console=" ++ show (_systemdNspawnConsole dCfg)] rootImageOptions = case containerRootImage containerMounts of Left (ContainerRootImage imgPath) -> ["-i", imgPath] Right loopbackMounted -> ["-D", loopbackHost loopbackMounted] capabilityOptions = case _systemdNspawnCapabilities dCfg of [] -> [] caps -> ["--capability=" ++ intercalate "," (map show caps)] bindMounts = map mkBind loopbackMounts ++ map mkBind sharedDirMounts ++ map mkBindRo sharedDirMountsRo ++ [mkBindRo (bootScriptHostDir bootScript, bootScriptContainerDir bootScript)] where mkBind (hostDir, containerDir) = "--bind=" ++ hostDir ++ ":" ++ containerDir mkBindRo (hostDir, containerDir) = "--bind-ro=" ++ hostDir ++ ":" ++ containerDir loopbackMounts = [ (h, c) | LoopbackMount {loopbackHost = h, loopbackContainer = c} <- containerLoopbackMounts containerMounts ] sharedDirMounts = [(h, c) | SharedDirectory h (MountPoint c) <- sharedDirs] sharedDirMountsRo = [(h, c) | SharedDirectoryRO h (MountPoint c) <- sharedDirs] extraArgs = maybe [] (: []) (_systemdNspawnExtraArgs dCfg) execOptions = ["/bin/sh", bootScriptContainerCommand bootScript] timeout = (TimeoutMicros . (* 1000000)) <$> _systemdNspawnMaxLifetimeSeconds dCfg traceL ("executing systemd-nspawn container build") interactiveAction <- isInteractive let runInteractively = case _systemdNspawnConsole dCfg of SystemdNspawnInteractive -> True _ -> interactiveAction if runInteractively then hostCmdStdIn HostCommandInheritStdin (sudo systemdCmd) Nothing else hostCmd (sudo systemdCmd) timeout umountLoopbackImages :: forall e. (Member ExcB9 e, CommandIO e) => SudoPrepender -> ContainerMounts -> Eff e () umountLoopbackImages sudo c = do case containerRootImage c of Left _ -> return () Right r -> umount r traverse_ umount (containerLoopbackMounts c) where umount :: LoopbackMount -> Eff e () umount l = do traceL $ "unmounting: " ++ show l res <- hostCmd (sudo (printf "umount '%s'" (loopbackHost l))) timeoutFastCmd when (not res) (errorL ("failed to unmount: " ++ show l)) removeContainerBuildRootDir :: forall e. (Member ExcB9 e, CommandIO e) => SudoPrepender -> ContainerBuildDirectories -> Eff e () removeContainerBuildRootDir sudo containerBuildDirs = do let target = containerBuildRoot containerBuildDirs traceL $ "removing: " ++ target res <- hostCmd (sudo (printf "rm -rf '%s'" target)) timeoutFastCmd when (not res) (errorL ("failed to remove: " ++ target)) timeoutFastCmd :: Maybe Timeout timeoutFastCmd = Just (TimeoutMicros 10000000)
sheyll/b9-vm-image-builder
src/lib/B9/SystemdNspawn.hs
mit
9,163
0
17
2,186
2,241
1,158
1,083
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} module IHaskell.Display.Widgets.Bool.ToggleButton ( -- * The ToggleButton Widget ToggleButton, -- * Constructor mkToggleButton) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Control.Monad (when, join, void) import Data.Aeson import Data.HashMap.Strict as HM import Data.IORef (newIORef) import Data.Text (Text) import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common -- | A 'ToggleButton' represents a ToggleButton widget from IPython.html.widgets. type ToggleButton = IPythonWidget ToggleButtonType -- | Create a new output widget mkToggleButton :: IO ToggleButton mkToggleButton = do -- Default properties, with a random uuid uuid <- U.random let boolState = defaultBoolWidget "ToggleButtonView" toggleState = (Tooltip =:: "") :& (Icon =:: "") :& (ButtonStyle =:: DefaultButton) :& RNil widgetState = WidgetState (boolState <+> toggleState) stateIO <- newIORef widgetState let widget = IPythonWidget uuid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen widget $ toJSON widgetState -- Return the image widget return widget instance IHaskellDisplay ToggleButton where display b = do widgetSendView b return $ Display [] instance IHaskellWidget ToggleButton where getCommUUID = uuid comm widget (Object dict1) _ = do let key1 = "sync_data" :: Text key2 = "value" :: Text Just (Object dict2) = HM.lookup key1 dict1 Just (Bool value) = HM.lookup key2 dict2 setField' widget BoolValue value triggerChange widget
beni55/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Bool/ToggleButton.hs
mit
2,085
0
14
540
418
229
189
46
1
{-# OPTIONS_GHC -O0 #-} {-# LANGUAGE TypeOperators, OverloadedStrings, DeriveGeneric #-} {-# LANGUAGE ScopedTypeVariables, GeneralizedNewtypeDeriving, CPP #-} -- | Tests that modify the database. module Tests.Mutable (mutableTests) where import Control.Concurrent import Control.Monad.Catch import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as Lazy (ByteString) import Data.List hiding (groupBy, insert) import Data.Proxy import Data.Time import Database.Selda import Database.Selda.Backend hiding (disableForeignKeys) import Database.Selda.Migrations import Database.Selda.MakeSelectors import Database.Selda.Validation (validateTable) import Database.Selda.Unsafe (unsafeSelector, rawStm) import Test.HUnit import Utils import Tables #if !MIN_VERSION_base(4, 11, 0) import Data.Semigroup #endif mutableTests :: (SeldaM b () -> IO ()) -> Test mutableTests freshEnv = test [ "tryDrop never fails" ~: freshEnv tryDropNeverFails , "tryCreate never fails" ~: freshEnv tryCreateNeverFails , "drop fails on missing" ~: freshEnv dropFailsOnMissing , "create fails on duplicate" ~: freshEnv createFailsOnDuplicate , "auto primary increments" ~: freshEnv (autoPrimaryIncrements comments) , "insert returns number of rows" ~: freshEnv insertReturnsNumRows , "update updates table" ~: freshEnv updateUpdates , "update nothing" ~: freshEnv updateNothing , "insert time values" ~: freshEnv insertTime , "transaction completes" ~: freshEnv transactionCompletes , "transaction rolls back" ~: freshEnv transactionRollsBack , "queries are consistent" ~: freshEnv consistentQueries , "delete deletes" ~: freshEnv deleteDeletes , "delete everything" ~: freshEnv deleteEverything , "override auto-increment" ~: freshEnv (overrideAutoIncrement comments) , "insert all defaults" ~: freshEnv insertAllDefaults , "insert some defaults" ~: freshEnv insertSomeDefaults , "quoted weird names" ~: freshEnv weirdNames , "dupe insert throws SeldaError" ~: freshEnv dupeInsertThrowsSeldaError , "dupe insert 2 throws SeldaError"~: freshEnv dupeInsert2ThrowsSeldaError , "dupe update throws SeldaError" ~: freshEnv dupeUpdateThrowsSeldaError , "nul queries don't fail" ~: freshEnv nulQueries , "fk violation fails" ~: freshEnv fkViolationFails , "table with multiple FKs" ~: freshEnv multipleFKs , "uniqueness violation fails" ~: freshEnv uniqueViolation , "upsert inserts/updates right" ~: freshEnv insertOrUpdate , "tryInsert doesn't fail" ~: freshEnv tryInsertDoesntFail , "isIn list gives right result" ~: freshEnv isInList , "isIn query gives right result" ~: freshEnv isInQuery , "strict blob column" ~: freshEnv blobColumn , "lazy blob column" ~: freshEnv lazyBlobColumn , "insertWhen/Unless" ~: freshEnv whenUnless , "insert >999 parameters" ~: freshEnv manyParameters , "empty insertion" ~: freshEnv emptyInsert , "correct boolean representation" ~: freshEnv boolTable , "optional foreign keys" ~: freshEnv optionalFK , "custom enum type" ~: freshEnv customEnum , "disable foreign key checks" ~: freshEnv disableForeignKeys , "mod fk violation fails" ~: freshEnv genModFkViolationFails , "mod fk insertion ok" ~: freshEnv genModFkInsertSucceeds , "migrate into self" ~: freshEnv (migrationTest migrateIntoSelf) , "drop column migration" ~: freshEnv (migrationTest dropColumn) , "auto-migrate one step" ~: freshEnv (migrationTest autoMigrateOneStep) , "auto-migrate no-op" ~: freshEnv (migrationTest autoMigrateNoOp) , "migrate aggregate" ~: freshEnv (migrationTest migrateAggregate) , "auto-migrate multi-step" ~: freshEnv (migrationTest autoMigrateOneStep) , "multi-unique insert" ~: freshEnv multiUnique , "uuid inserts" ~: freshEnv uuidInserts , "uuid queries" ~: freshEnv uuidQueries , "migrate table with index" ~: freshEnv migrateIndex , "weak auto primary increments" ~: freshEnv (autoPrimaryIncrements weakComments) , "override weak auto-increment" ~: freshEnv (overrideAutoIncrement weakComments) , "disable FKs with rawStm" ~: freshEnv disableFKsWithRawStm , "overwrite row on update" ~: freshEnv overwriteRow ] tryDropNeverFails :: SeldaM b () tryDropNeverFails = teardown tryCreateNeverFails :: SeldaM b () tryCreateNeverFails = tryCreateTable comments >> tryCreateTable comments dropFailsOnMissing = assertFail $ dropTable comments createFailsOnDuplicate = createTable people >> assertFail (createTable people) autoPrimaryIncrements c = do setup k <- untyped <$> insertWithPK c [(def, Just "Kobayashi", "チョロゴン")] k' <- untyped <$> insertWithPK c [(def, Nothing, "more anonymous spam")] [name] <- query $ do t <- select c restrict (t!cId .== literal k) return (t!cName) assEq "inserted key refers to wrong value" name (Just "Kobayashi") let k0 = read (show k) :: Int k1 = read (show k') :: Int ass "primary key doesn't increment properly" (k1 == k0+1) insertReturnsNumRows = do setup rows <- insert comments [ (def, Just "Kobayashi", "チョロゴン") , (def, Nothing, "more anonymous spam") , (def, Nothing, "even more spam") ] assEq "insert returns wrong number of inserted rows" 3 rows updateUpdates = do setup insert_ comments [ (def, Just "Kobayashi", "チョロゴン") , (def, Nothing, "more anonymous spam") , (def, Nothing, "even more spam") ] rows <- update comments (isNull . (!cName)) (`with` [cName := just "anon"]) [upd] <- query $ aggregate $ do t <- select comments restrict (not_ $ isNull (t!cName)) restrict (t!cName .== just "anon") return (count (t!cName)) assEq "update returns wrong number of updated rows" 3 rows assEq "rows were not updated" 3 upd updateNothing = do setup a <- query $ select people n <- update people (const true) id b <- query $ select people assEq "identity update didn't happen" (length a) n assEq "identity update did something weird" a b insertTime = do tryDropTable times createTable times let Just t = parseTimeM True defaultTimeLocale "%F %H:%M:%S%Q" "2011-11-11 11:11:11.11111" Just d = parseTimeM True defaultTimeLocale "%F" "2011-11-11" Just lt = parseTimeM True defaultTimeLocale "%H:%M:%S%Q" "11:11:11.11111" insert_ times [("now", t, d, lt)] [("now", t', d', lt')] <- query $ select times assEq "time not properly inserted" (t, d, lt) (t', d', lt') dropTable times where times :: Table (Text, UTCTime, Day, TimeOfDay) times = table "times" [] transactionCompletes = do setup transaction $ do insert_ comments [(def, Just "Kobayashi", c1)] insert_ comments [ (def, Nothing, "more anonymous spam") , (def, Just "Kobayashi", c2) ] cs <- query $ do t <- select comments restrict (t!cName .== just "Kobayashi") return (t!cComment) ass "some inserts were not performed" (c1 `elem` cs && c2 `elem` cs && length cs == 2) where c1 = "チョロゴン" c2 = "メイド最高!" transactionRollsBack :: SeldaM b () transactionRollsBack = do setup res <- try $ transaction $ do insert_ comments [(def, Just "Kobayashi", c1)] insert_ comments [ (def, Nothing, "more anonymous spam") , (def, Just "Kobayashi", c2) ] fail "nope" case res of Right _ -> liftIO $ assertFailure "exception didn't propagate" Left (SomeException _) -> do cs <- query $ do t <- select comments restrict (t!cName .== just "Kobayashi") return (t!cComment) assEq "commit was not rolled back" [] cs where c1 = "チョロゴン" c2 = "メイド最高!" consistentQueries = do setup a <- query q b <- query q assEq "query result changed on its own" a b where q = do t <- select people restrict (round_ (t!pCash) .> (t!pAge)) return (t!pName) deleteDeletes = do setup a <- query q deleteFrom_ people (\t -> t!pName .== "Velvet") b <- query q ass "rows not deleted" (a /= b && length b < length a) where q = do t <- select people restrict (round_ (t!pCash) .< (t!pAge)) return (t!pName) deleteEverything = do tryDropTable people createTable people insert_ people peopleItems a <- query q deleteFrom_ people (const true) b <- query q ass "table empty before delete" (a /= []) assEq "rows not deleted" [] b where q = do t <- select people restrict (round_ (t!pCash) .> (t!pAge)) return (t!pName) overrideAutoIncrement c = do setup insert_ c [(toRowId 123, Nothing, "hello")] num <- query $ aggregate $ do t <- select c restrict (t!cId .== literal (toRowId 123)) return (count (t!cId)) assEq "failed to override auto-incrementing column" [1] num insertAllDefaults = do setup pk <- untyped <$> insertWithPK comments [(def, def, def)] res <- query $ do comment <- select comments restrict (comment!cId .== literal pk) return comment assEq "wrong default values inserted" [(pk, Nothing, "")] res insertSomeDefaults = do setup insert_ people [Person "Celes" def (Just "chocobo") def] res <- query $ do person <- select people restrict (person!pPet .== just "chocobo") return person assEq "wrong values inserted" [Person "Celes" 0 (Just "chocobo") 0] res weirdNames = do tryDropTable tableWithWeirdNames createTable tableWithWeirdNames i1 <- insert tableWithWeirdNames [(42, Nothing)] assEq "first insert failed" 1 i1 i2 <- insert tableWithWeirdNames [(123, Just 321)] assEq "second insert failed" 1 i2 up <- update tableWithWeirdNames (\c -> c ! weird1 .== 42) (\c -> c `with` [weird2 := just 11]) assEq "update failed" 1 up res <- query $ do t <- select tableWithWeirdNames restrict (t ! weird1 .== 42) return (t ! weird2) assEq "select failed" [Just 11] res dropTable tableWithWeirdNames where tableWithWeirdNames :: Table (Int, Maybe Int) tableWithWeirdNames = tableFieldMod "DROP TABLE comments" [] (<> "one \" quote \1\2\3\DEL\n two \"quotes\"") weird1 :*: weird2 = selectors tableWithWeirdNames dupeInsertThrowsSeldaError = do tryDropTable comments' createTable comments' assertFail $ do insert_ comments' [ (0, Just "Kobayashi", "チョロゴン") , (0, Nothing, "some spam") ] dropTable comments' where comments' :: Table (Int, Maybe Text, Text) comments' = table "comments" [Single cId :- primary] cId :*: cName :*: cComment = selectors comments' dupeInsert2ThrowsSeldaError :: SeldaM b () dupeInsert2ThrowsSeldaError = do setup insert_ comments [(def, Just "Kobayashi", "チョロゴン")] [(ident, _, _)] <- query $ limit 0 1 $ select comments e <- try $ insert_ comments [(ident, Nothing, "Spam, spam, spaaaaaam!")] case e :: Either SeldaError () of Left _ -> return () _ -> liftIO $ assertFailure "SeldaError not thrown" dupeUpdateThrowsSeldaError :: SeldaM b () dupeUpdateThrowsSeldaError = do setup insert_ comments [ (def, Just "Kobayashi", "チョロゴン") , (def, Just "spammer" , "some spam") ] [(ident, _, _)] <- query $ limit 0 1 $ select comments e <- try $ do update_ comments (\c -> c ! cName .== just "spammer") (\c -> c `with` [cId := literal ident]) case e :: Either SeldaError () of Left _ -> return () _ -> liftIO $ assertFailure "SeldaError not thrown" nulQueries = do setup insert_ comments [ (def, Just "Kobayashi", "チョロゴン") , (def, Nothing , "more \0 spam") , (def, Nothing , "even more spam") ] rows <- update comments (isNull . (!cName)) (`with` [cName := just "\0"]) [upd] <- query $ aggregate $ do t <- select comments restrict (not_ $ isNull (t!cName)) restrict (t!cName .== just "\0") return (count (t!cName)) assEq "update returns wrong number of updated rows" 3 rows assEq "rows were not updated" 3 upd fkViolationFails = do -- Note that this is intended to test that FKs are in place and enabled. -- If we get an FK violation here, we assume that the database does the -- right thing in other situations, since FKs behavior is determined by -- the DB, not by Selda, except when creating tables. setup createTable addressesWithFK assertFail $ insert_ addressesWithFK [("Nobody", "Nowhere")] dropTable addressesWithFK where addressesWithFK :: Table (Text, Text) addressesWithFK = table "addressesWithFK" [one :- foreignKey people pName] one :*: two = selectors addressesWithFK data FKAddrs = FKAddrs { fkaName :: Text , fkaCity :: Text } deriving Generic instance SqlRow FKAddrs genModFkViolationFails = do setup createTable addressesWithFK assertFail $ insert_ addressesWithFK [FKAddrs "Nobody" "Nowhere"] dropTable addressesWithFK where addressesWithFK :: Table FKAddrs addressesWithFK = tableFieldMod "addressesWithFK" [aName :- foreignKey people pName] ("test_" <>) aName :*: aCity = selectors addressesWithFK genModFkInsertSucceeds = do setup createTable addressesWithFK insert_ addressesWithFK [FKAddrs "Link" "Nowhere"] res <- query $ do t <- select addressesWithFK person <- select people restrict (t!aName .== "Link" .&& t!aName .== person ! pName) return (person!pName :*: t!aCity) assEq "wrong state after insert" ["Link" :*: "Nowhere"] res dropTable addressesWithFK where addressesWithFK :: Table FKAddrs addressesWithFK = tableFieldMod "addressesWithFK" [aName :- foreignKey people pName] ("test_" <>) aName :*: aCity = selectors addressesWithFK multipleFKs = do setup createTable addressesWithFK assertFail $ insert_ addressesWithFK [("Nobody", "Nowhere")] dropTable addressesWithFK where addressesWithFK :: Table (Text, Text) addressesWithFK = table "addressesWithFK" [ one :- foreignKey people pName , two :- foreignKey people pName ] one :*: two = selectors addressesWithFK uniqueViolation = do tryDropTable uniquePeople createTable uniquePeople assertFail $ insert_ uniquePeople [ ("Link", Nothing) , ("Link", Nothing) ] r1 <- query $ select uniquePeople assertFail $ do insert_ uniquePeople [("Link", Nothing)] insert_ uniquePeople [("Link", Nothing)] r2 <- query $ select uniquePeople assEq "inserted rows despite constraint violation" [] r1 assEq "row disappeared after violation" [("Link", Nothing)] r2 dropTable uniquePeople where uniquePeople :: Table (Text, Maybe Text) (uniquePeople, upName :*: upPet) = tableWithSelectors "uniquePeople" [Single upName :- unique] insertOrUpdate = do tryDropTable counters createTable counters r1 <- fmap untyped <$> upsert counters (\t -> t!c .== 0) (\t -> t `with` [v += 1]) [(0, 1)] assEq "wrong return value from inserting upsert" (Just invalidRowId) r1 r2 <- fmap untyped <$> upsert counters (\t -> t!c .== 0) (\t -> t `with` [v $= (+1)]) [(0, 1)] assEq "wrong return value from updating upsert" Nothing r2 res <- query $ select counters assEq "wrong value for counter" [(0, 2)] res r3 <- fmap untyped <$> upsert counters (\t -> t ! c .== 15) (\t -> t `with` [v := t!v + 1]) [(15, 1)] assEq "wrong return value from second inserting upsert" (Just invalidRowId) r3 dropTable counters where counters :: Table (Int, Int) counters = table "counters" [Single c :- primary] c :*: v = selectors counters tryInsertDoesntFail = do createTable uniquePeople res1 <- tryInsert uniquePeople [("Link", Nothing)] r1 <- query $ select uniquePeople res2 <- tryInsert uniquePeople [("Link", Nothing)] r2 <- query $ select uniquePeople assEq "wrong return value from successful tryInsert" True res1 assEq "row not inserted" [("Link", Nothing)] r1 assEq "wrong return value from failed tryInsert" False res2 assEq "row inserted despite violation" [("Link", Nothing)] r2 dropTable uniquePeople where uniquePeople :: Table (Text, Maybe Text) (uniquePeople, upName :*: upPet) = tableWithSelectors "uniquePeople" [Single upName :- unique] isInList = do setup res <- query $ do p <- select people restrict (p ! pName .== "Link") return ( "Link" `isIn` [p ! pName, "blah"] :*: 0 `isIn` [p ! pAge, 42, 19] :*: 1 `isIn` ([] :: [Col () Int]) ) assEq "wrong result from isIn" [True :*: False :*: False] res isInQuery = do setup res <- query $ do return ( "Link" `isIn` pName `from` select people :*: "Zelda" `isIn` pName `from` select people ) assEq "wrong result from isIn" [True :*: False] res blobColumn = do tryDropTable blobs createTable blobs n <- insert blobs [("b1", someBlob), ("b2", otherBlob)] assEq "wrong number of rows inserted" 2 n [(k, v)] <- query $ do t <- select blobs restrict (t ! ks .== "b1") return t assEq "wrong key for blob" "b1" k assEq "got wrong blob back" someBlob v dropTable blobs where blobs :: Table (Text, ByteString) blobs = table "blobs" [] ks :*: vs = selectors blobs someBlob = "\0\1\2\3hello!漢字" otherBlob = "blah" lazyBlobColumn = do tryDropTable blobs createTable blobs n <- insert blobs [("b1", someBlob), ("b2", otherBlob)] assEq "wrong number of rows inserted" 2 n [(k, v)] <- query $ do t <- select blobs restrict (t ! ks .== "b1") return t assEq "wrong key for blob" "b1" k assEq "got wrong blob back" someBlob v dropTable blobs where blobs :: Table (Text, Lazy.ByteString) blobs = table "blobs" [] ks :*: vs = selectors blobs someBlob = "\0\1\2\3hello!漢字" otherBlob = "blah" whenUnless = do setup insertUnless people (\t -> t ! pName .== "Lord Buckethead") theBucket oneBucket <- query $ select people `suchThat` ((.== "Lord Buckethead") . (! pName)) assEq "Lord Buckethead wasn't inserted" theBucket (oneBucket) insertWhen people (\t -> t ! pName .== "Lord Buckethead") theSara oneSara <- query $ select people `suchThat` ((.== "Sara") . (! pName)) assEq "Sara wasn't inserted" theSara (oneSara) insertUnless people (\t -> t ! pName .== "Lord Buckethead") [Person "Jessie" 16 Nothing (10^6)] noJessie <- query $ select people `suchThat` ((.== "Jessie") . (! pName)) assEq "Jessie was wrongly inserted" [] (noJessie :: [Person]) insertWhen people (\t -> t ! pName .== "Jessie") [Person "Lavinia" 16 Nothing (10^8)] noLavinia <- query $ select people `suchThat` ((.== "Lavinia") . (! pName)) assEq "Lavinia was wrongly inserted" [] (noLavinia :: [Person]) teardown where theBucket = [Person "Lord Buckethead" 30 Nothing 0] theSara = [Person "Sara" 14 Nothing 0] manyParameters = do tryDropTable things createTable things inserted <- insert things [0..1000] actuallyInserted <- query $ aggregate $ count . the <$> select things dropTable things assEq "insert returned wrong insertion count" 1001 inserted assEq "wrong number of items inserted" [1001] actuallyInserted where things :: Table (Only Int) things = table "things" [] emptyInsert = do setup inserted <- insert people [] assEq "wrong insertion count reported" 0 inserted teardown boolTable = do tryDropTable tbl createTable tbl insert tbl [(def, True), (def, False), (def, def)] bs <- query $ (! two) <$> select tbl assEq "wrong values inserted into table" [True, False, False] bs dropTable tbl where tbl :: Table (RowID, Bool) tbl = table "booltable" [one :- untypedAutoPrimary] one :*: two = selectors tbl optionalFK = do tryDropTable tbl createTable tbl pk <- untyped <$> insertWithPK tbl [(def, Nothing)] insert tbl [(def, Just pk)] vs <- query $ (! mrid) <$> select tbl assEq "wrong value for nullable FK" [Nothing, Just pk] vs dropTable tbl where tbl :: Table (RowID, Maybe RowID) tbl = table "booltable" [rid :- untypedAutoPrimary, mrid :- foreignKey tbl rid] (rid :*: mrid) = selectors tbl -- | For genericAutoPrimary. data AutoPrimaryUser = AutoPrimaryUser { uid :: ID AutoPrimaryUser , admin :: Bool , username :: Text , password :: Text , dateCreated :: UTCTime , dateModified :: UTCTime } deriving ( Eq, Show, Generic ) -- | For customEnum data Foo = A | B | C | D deriving (Show, Read, Eq, Ord, Enum, Bounded) instance SqlType Foo customEnum = do tryDropTable tbl createTable tbl inserted <- insert tbl [(def, A), (def, C), (def, C), (def, B)] assEq "wrong # of rows inserted" 4 inserted res <- query $ do t <- select tbl order (t ! two) descending return (t ! two) assEq "wrong pre-delete result list" [C, C, B, A] res deleted <- deleteFrom tbl ((.== literal C) . (! two)) assEq "wrong # of rows deleted" 2 deleted res2 <- query $ do t <- select tbl order (t ! two) ascending return (t ! two) assEq "wrong post-delete result list" [A, B] res2 dropTable tbl where tbl :: Table (RowID, Foo) tbl = table "enums" [one :- untypedAutoPrimary] one :*: two = selectors tbl disableForeignKeys = do -- Run the test twice, to check that FK checking gets turned back on again -- properly. go ; go where go = do tryDropTable tbl2 tryDropTable tbl1 createTable tbl1 createTable tbl2 pk <- untyped <$> insertWithPK tbl1 [Only def] insert tbl2 [(def, pk)] assertFail $ dropTable tbl1 withoutForeignKeyEnforcement $ dropTable tbl1 >> dropTable tbl2 tryDropTable tbl2 tryDropTable tbl1 tbl1 :: Table (Only RowID) tbl1 = table "table1" [id1 :- untypedAutoPrimary] id1 = selectors tbl1 tbl2 :: Table (RowID, RowID) tbl2 = table "table2" [s_fst :- untypedAutoPrimary, s_snd :- foreignKey tbl1 id1] s_fst :*: s_snd = selectors tbl2 migrationTest test = do tryDropTable migrationTable1 createTable migrationTable1 insert_ migrationTable1 [1,2,3] test tryDropTable migrationTable1 tryDropTable migrationTable2 tryDropTable migrationTable3 migrationTable1 :: Table (Only Int) migrationTable1 = table "table1" [Single mt1_1 :- primary] mt1_1 = selectors migrationTable1 migrationTable2 :: Table (Text, Int) migrationTable2 = table "table1" [Single mt2_1 :- primary] mt2_1 :*: mt2_2 = selectors migrationTable2 migrationTable3 :: Table (Only Int) migrationTable3 = table "table3" [Single mt3_1 :- primary] mt3_1 = selectors migrationTable3 steps = [ [Migration migrationTable1 migrationTable1 pure] , [Migration migrationTable1 migrationTable2 $ \foo -> pure $ new [ mt2_1 := toString (the foo) , mt2_2 := the foo ] ] , [Migration migrationTable2 migrationTable3 $ \t -> pure (only (t ! mt2_2))] , [Migration migrationTable3 migrationTable1 pure] ] migrateIntoSelf = do migrate migrationTable1 migrationTable1 id res <- query $ do x <- select migrationTable1 order (the x) ascending return x assEq "migrating into self went wrong" [1,2,3] res addColumn = do migrate migrationTable1 migrationTable2 $ \foo -> new [ mt2_1 := toString (the foo) , mt2_2 := the foo ] res <- query $ do t <- select migrationTable2 order (t ! mt2_1) ascending return t assEq "adding column went wrong" [("1",1),("2",2),("3",3)] res dropColumn = do migrate migrationTable1 migrationTable2 $ \foo -> new [ mt2_1 := toString (the foo) , mt2_2 := the foo ] migrate migrationTable2 migrationTable3 $ \tbl -> only (tbl ! mt2_2) assertFail $ query $ select migrationTable2 res <- query $ do x <- select migrationTable3 order (the x) ascending return x assEq "migrating back went wrong" [1,2,3] res autoMigrateOneStep = do migrate migrationTable1 migrationTable3 id autoMigrate False steps res <- query $ do x <- select migrationTable1 order (the x) ascending return x assEq "automigration failed" [1,2,3] res autoMigrateNoOp = do autoMigrate True steps res <- query $ do x <- select migrationTable1 order (the x) ascending return x assEq "no-op automigration failed" [1,2,3] res migrateAggregate = do setup migrateM migrationTable1 migrationTable2 $ \foo -> do age <- aggregate $ do person <- select people return $ ifNull 0 .<$> min_ (person ! pAge) return $ new [mt2_1 := toString (the foo), mt2_2 := age] res <- query $ do t <- select migrationTable2 order (t ! mt2_2) ascending return t assEq "query migration failed" [("1",10),("2",10),("3",10)] res autoMigrateMultiStep = do autoMigrate True steps res <- query $ do x <- select migrationTable1 order (the x) ascending return x assEq "multi-step automigration failed" [1,2,3] res multiUnique = do tryDropTable uniques createTable uniques insert_ uniques [(1,1), (1,2), (2,1), (2,2)] expectFalse1 <- tryInsert uniques [(1,1)] expectFalse2 <- tryInsert uniques [(1,2)] expectTrue1 <- tryInsert uniques [(1,3)] expectTrue2 <- tryInsert uniques [(3,3)] assEq "uniqueness violation" False expectFalse1 assEq "uniqueness violation" False expectFalse2 assEq "overly strict uniqueness constraint" True expectTrue1 assEq "overly strict uniqueness constraint" True expectTrue2 dropTable uniques where uniques :: Table (Int, Int) (uniques, ua :*: ub) = tableWithSelectors "uniques" [(ua :+ Single ub) :- unique] uuidTable :: Table (UUID, Int) uuidTable = table "uuidTable" [ Single (unsafeSelector 0 :: Selector (UUID, Int) UUID) :- primary ] uuidSetup = do tryDropTable uuidTable createTable uuidTable uuid <- newUuid assertFail $ insert_ uuidTable [(uuid, 1), (uuid, 2)] uuid2 <- newUuid insert_ uuidTable [(uuid, 1), (uuid2, 2)] return (uuid, uuid2) uuidInserts = do _ <- uuidSetup dropTable uuidTable uuidQueries = do (a, b) <- uuidSetup [(a', n)] <- query $ do x <- select uuidTable restrict (x ! unsafeSelector 0 .== literal a) return x dropTable uuidTable assEq "wrong uuid returned" a a' migrateIndex :: SeldaM b () migrateIndex = do tryDropTable tbl1 createTable tbl1 migrate tbl1 tbl2 (\x -> new [a2 := x ! a1, b := 0]) validateTable tbl2 migrate tbl2 tbl1 (\x -> new [a1 := x ! a2]) validateTable tbl1 dropTable tbl1 where tbl1 :: Table (Only Int) (tbl1, a1) = tableWithSelectors "foo" [Single a1 :- index] tbl2 :: Table (Int, Int) (tbl2, a2 :*: b) = tableWithSelectors "foo" [Single a2 :- index] disableFKsWithRawStm :: SeldaM b () disableFKsWithRawStm = do createTable people createTable tbl assertFail $ insert_ tbl [("nonexistent person", "asdas")] #ifdef SQLITE rawStm "PRAGMA foreign_keys = OFF" #endif #ifdef POSTGRES rawStm "ALTER TABLE fkaddrs DISABLE TRIGGER ALL" #endif n <- insert tbl [("nonexistent person", "asdas")] assEq "failed to insert bad person" 1 n dropTable tbl dropTable people #ifdef SQLITE rawStm "PRAGMA foreign_keys = OFF" #endif where tbl = table "fkaddrs" [aName :- foreignKey people pName] overwriteRow :: SeldaM b () overwriteRow = do createTable people insert people [p1] update people (\p -> p!pName .== "Testingway") (const (row p2)) ps <- query $ select people assEq "row not overwritten" [p2] ps where p1 = Person "Testingway" 101 Nothing 0.2 p2 = Person "Changingway" 99 (Just "Pet Rock") 100
valderman/selda
selda-tests/test/Tests/Mutable.hs
mit
28,481
0
19
7,017
9,118
4,517
4,601
711
2
module Icarus.Bezier (Point(..), Despair(..), pointToList, pointToTuple, tupleToPoint, bezier, line1d', cubic, cubicSeq, trange) where import Control.Monad (zipWithM) ------------------------------------------------------------------------------- -- http://mathfaculty.fullerton.edu/mathews/n2003/BezierCurveMod.html ------------------------------------------------------------------------------- newtype Despair a = Despair { getDespair :: (a, a) } deriving (Show, Eq, Ord) -- -- To apply a function per coord the Despair signature should be `Despair a` -- -- where `a` would be a tuple. instance Functor Despair where fmap f (Despair (x, y)) = Despair (f x, f y) -- instance Applicative Despair where -- pure = Despair -- Despair (f, g) <*> Despair (x, y) = Despair ((f x), (g y)) -- TODO: Should be restricted to numbers. data Point a = Point { getCoordX :: a, getCoordY :: a } deriving (Show, Eq, Ord) -- Let's opperate on Points without manual unwrapping. -- -- fmap (* 2) (Point 3 4) -- => Point 6 8 instance Functor Point where fmap f (Point x y) = Point (f x) (f y) -- Applicative functors too -- -- (Point (* 2) (* 3)) <*> (Point 2 4) -- => Point 4 12 -- pure (+) <*> Point 1 1 <*> (Point 1 2) -- => Point 2 3 -- (+) <$> Point 1 1 <*> (Point 1 2) -- => Point 2 3 instance Applicative Point where pure a = Point a a Point f g <*> Point x y = Point (f x) (g y) instance Num a => Monoid (Point a) where mempty = Point 0 0 Point x0 y0 `mappend` Point x1 y1 = Point (x0 + x1) (y0 + y1) -- Notes/Ideas -- -- Is it possible to create a function with `sequenceA` that gathers all points -- and applies the interpolation function? is it idiotic? -- maybe it is a matter of using `map` or `zipWith`. tupleToPoint :: (a, a) -> Point a tupleToPoint (x, y) = Point x y pointToList :: Point a -> [a] pointToList (Point x y) = [x, y] pointToTuple :: Point a -> (a, a) pointToTuple (Point x y) = (x, y) cubicSeq :: Point Float -> Point Float -> Point Float -> Point Float -> Float -> Float -> [Point Float] cubicSeq p0 p1 p2 p3 t0 t1 = map (cubic p0 p1 p2 p3) $ trange t0 t1 -- cubicSeq helper trange :: Float -> Float -> [Float] trange a b = [x | x <- xs, x >= a, x <= b] where xs = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] -- p = P0 B1(t) + P1 B2(t) + P2 B3(t) + P3 B4(t) -- where: -- Pi are the control points -- Bi are the Beziér functions -- t is a percentage of the distance along the curve (between 0 and 1) -- p is the point in 2D space cubic :: Point Float -> Point Float -> Point Float -> Point Float -> Float -> Point Float cubic (Point x0 y0) (Point x1 y1) (Point x2 y2) (Point x3 y3) t = Point (coord x0 x1 x2 x3 t) (coord y0 y1 y2 y3 t) -- parametric equation coord :: Float -> Float -> Float -> Float -> Float -> Float coord x1 x2 x3 x4 t = x1 * b1 t + x2 * b2 t + x3 * b3 t + x4 * b4 t b1 :: Float -> Float b1 t = (1 - t) ** 3 b2 :: Float -> Float b2 t = 3 * (1 - t) ** 2 * t b3 :: Float -> Float b3 t = 3 * (1 - t) * t ** 2 b4 :: Float -> Float b4 t = t ** 3 ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- REVIEW Functors, Applicatives and Monads ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- bezier' :: [Point] -> Point -- bezier' [p] = const p -- bezier' ps = do l <- bezier' (init ps) -- r <- bezier' (tail ps) -- line' l r -- Line between two points: -- line' :: Point -> Point -> Point -- line' (Point x1 y1) -- (Point x2 y2) = toPoint $ zipWithM line1d' [x1, y1] [x2, y2] -- toPoint :: [Float] -> Point -- toPoint [x, y] = Point x y -- Linear interpolation between two numbers line1d' :: Float -> Float -> Float -> Float line1d' x y t = (1 - t) * x + t * y ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- https://github.com/hrldcpr/Bezier.hs/blob/master/Bezier.hs ------------------------------------------------------------------------------- -- bezier of one point is fixed at that point, and bezier of N points is the -- linear interpolation between bezier of first N-1 points and bezier of last -- N-1 points. type BPoint = [Float] type Parametric a = Float -> a bezier :: [BPoint] -> Parametric BPoint bezier [p] = const p bezier ps = do l <- bezier (init ps) r <- bezier (tail ps) line l r -- line between two points: line :: BPoint -> BPoint -> Parametric BPoint line = zipWithM line1d -- linear interpolation between two numbers: line1d :: Float -> Float -> Parametric Float line1d a b t = (1 - t) * a + t * b
arnau/icarus
src/Icarus/Bezier.hs
mit
5,419
0
12
1,332
1,242
676
566
70
1
-- | Upload to Stackage and Hackage {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleContexts #-} module Stackage.Upload (uploadHackageDistro) where import Network.HTTP.Client import Stackage.Prelude import Stackage.ServerBundle (bpAllPackages) uploadHackageDistro :: Text -- ^ distro name -> BuildPlan -> ByteString -- ^ Hackage username -> ByteString -- ^ Hackage password -> Manager -> IO (Response LByteString) uploadHackageDistro name bp username password manager = do req1 <- parseRequest $ concat [ "https://hackage.haskell.org/distro/" , unpack name , "/packages.csv" ] let req2 = req1 { requestHeaders = [("Content-Type", "text/csv")] , requestBody = RequestBodyLBS csv , method = "PUT" } httpLbs (applyBasicAuth username password req2) manager where csv = encodeUtf8 $ builderToLazy $ mconcat $ intersperse "\n" $ map go $ mapToList $ bpAllPackages bp go (name', version) = "\"" ++ (toBuilder $ display name') ++ "\",\"" ++ (toBuilder $ display version) ++ "\",\"https://www.stackage.org/package/" ++ (toBuilder $ display name') ++ "\""
fpco/stackage-curator
src/Stackage/Upload.hs
mit
1,513
0
15
476
285
154
131
42
1
{-# LANGUAGE NoDeriveAnyClass #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module TokenCSFR ( TokenCSFR() , csfrChallenge , correctCSFR ) where import Database.Persist import Lucid import Orphan.UUID import Protolude hiding(show) import Web.HttpApiData import Web.PathPieces import Prelude(Show(..)) import Data.Aeson newtype TokenCSFR = TokenCSFR UUID deriving (Read,Eq,Ord,FromHttpApiData,ToJSON,FromJSON) instance Show TokenCSFR where show (TokenCSFR t) = show t -- TODO: implement csfrChallenge :: Text -> UUID -> TokenCSFR csfrChallenge _ = TokenCSFR correctCSFR :: Text -> UUID -> TokenCSFR -> Bool correctCSFR _ x (TokenCSFR y) = x == y instance ToHtml TokenCSFR where toHtmlRaw = toHtml toHtml (TokenCSFR t) = toHtml (toText t)
mreider/kinda-might-work
src/TokenCSFR.hs
mit
948
0
8
307
226
126
100
27
1
{-# OPTIONS -Wall #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE LambdaCase #-} import Control.Monad (foldM) import Data.Bool (bool) import Data.Functor import qualified Data.List as List import Data.Ord (comparing) import Data.Text (Text) import Data.Vector (Vector, (//)) import qualified Data.Vector as Vector import Helpers.Parse import System.Environment (getArgs) import Text.Parsec hiding (Error, State) import Prelude hiding (lookup) modelNumberLength :: Int modelNumberLength = 14 startingModelNumber :: Input startingModelNumber = Vector.replicate modelNumberLength 1 data Var = W | X | Y | Z deriving (Show) data Value = Var Var | Num Int instance Show Value where show (Var var) = show var show (Num num) = show num data State = State Int Int Int Int deriving (Show) data Instruction = Inp Var | Add Var Value | Mul Var Value | Div Var Value | Mod Var Value | Eql Var Value deriving (Show) type Program = [Instruction] type Input = Vector Int data Error = DivisionByZero | NegativeModulus deriving (Show) data Result a = Done a | NoInputLeft State | Error Error deriving (Functor, Show) instance Applicative Result where pure = Done Error failure <*> _ = Error failure _ <*> Error failure = Error failure NoInputLeft state <*> _ = NoInputLeft state _ <*> NoInputLeft state = NoInputLeft state Done f <*> Done x = Done (f x) instance Monad Result where Error failure >>= _ = Error failure NoInputLeft state >>= _ = NoInputLeft state Done x >>= f = f x main :: IO () main = do program <- parseLinesIO parser argsInput <- Vector.fromList . map read <$> getArgs if null argsInput then putStrLn $ concatMap show $ Vector.toList $ findInput program startingModelNumber else print $ run program argsInput findInput :: Program -> Input -> Input findInput program input = case run program input of Done (State _ _ _ 0) -> input _ -> let attempts = do position <- [0 .. modelNumberLength - 1] value <- [1 .. 9] let trial = input // [(position, value)] return (trial, run program trial) in findInput program $ selectBest attempts selectBest :: [(a, Result State)] -> a selectBest results = fst $ List.minimumBy (comparing (\(_, State _ _ _ z) -> z)) $ results >>= \case (updated, Done state) -> [(updated, state)]; _ -> [] run :: Program -> Input -> Result State run program input = snd <$> foldM eval (input, State 0 0 0 0) program eval :: (Input, State) -> Instruction -> Result (Input, State) eval (input, state) (Inp a) = case Vector.uncons input of Nothing -> NoInputLeft state Just (i, rest) -> Done (rest, update a i state) eval (input, state) (Add a b) = let c = lookup (Var a) state + lookup b state in Done (input, update a c state) eval (input, state) (Mul a b) = let c = lookup (Var a) state * lookup b state in Done (input, update a c state) eval (input, state) (Div a b) = case lookup b state of 0 -> Error DivisionByZero b' -> let c = lookup (Var a) state `quot` b' in Done (input, update a c state) eval (input, state) (Mod a b) = case (lookup (Var a) state, lookup b state) of (_, 0) -> Error DivisionByZero (a', _) | a' < 0 -> Error NegativeModulus (_, b') | b' < 0 -> Error NegativeModulus (a', b') -> let c = a' `mod` b' in Done (input, update a c state) eval (input, state) (Eql a b) = let c = bool 0 1 $ lookup (Var a) state == lookup b state in Done (input, update a c state) update :: Var -> Int -> State -> State update W w (State _ x y z) = State w x y z update X x (State w _ y z) = State w x y z update Y y (State w x _ z) = State w x y z update Z z (State w x y _) = State w x y z lookup :: Value -> State -> Int lookup (Var W) (State w _ _ _) = w lookup (Var X) (State _ x _ _) = x lookup (Var Y) (State _ _ y _) = y lookup (Var Z) (State _ _ _ z) = z lookup (Num n) _ = n parser :: Parsec Text () Instruction parser = choice [ try (string "inp") *> (Inp <$> var), try (string "add") *> (Add <$> var <*> value), try (string "mul") *> (Mul <$> var <*> value), try (string "div") *> (Div <$> var <*> value), try (string "mod") *> (Mod <$> var <*> value), try (string "eql") *> (Eql <$> var <*> value) ] where value = try (Var <$> var) <|> (Num <$> (spaces *> int)) var = spaces *> choice [ char 'w' $> W, char 'x' $> X, char 'y' $> Y, char 'z' $> Z ]
SamirTalwar/advent-of-code
2021/AOC_24_2.hs
mit
4,543
0
19
1,180
2,060
1,057
1,003
-1
-1
{-# htermination (maxOrdering :: Ordering -> Ordering -> Ordering) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Ordering = LT | EQ | GT ; ltEsOrdering :: Ordering -> Ordering -> MyBool ltEsOrdering LT LT = MyTrue; ltEsOrdering LT EQ = MyTrue; ltEsOrdering LT GT = MyTrue; ltEsOrdering EQ LT = MyFalse; ltEsOrdering EQ EQ = MyTrue; ltEsOrdering EQ GT = MyTrue; ltEsOrdering GT LT = MyFalse; ltEsOrdering GT EQ = MyFalse; ltEsOrdering GT GT = MyTrue; max0 x y MyTrue = x; otherwise :: MyBool; otherwise = MyTrue; max1 x y MyTrue = y; max1 x y MyFalse = max0 x y otherwise; max2 x y = max1 x y (ltEsOrdering x y); maxOrdering :: Ordering -> Ordering -> Ordering maxOrdering x y = max2 x y;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/max_6.hs
mit
768
0
8
166
276
152
124
22
1
-- | Evaluators for Language.TaPL.Arith. module Language.TaPL.Arith.Eval (eval, eval') where import Control.Applicative ((<$>)) import Language.TaPL.Arith.Syntax (Term(..), isVal, isNumericVal) -- | Small step evaluator. eval :: Term -> Maybe Term eval t | isVal t = Just t | otherwise = case eval1 t of Nothing -> Nothing Just t' -> eval t' -- | A single step. eval1 :: Term -> Maybe Term eval1 t | isVal t = Just t eval1 (TmIf TmTrue t2 _) = Just t2 eval1 (TmIf TmFalse _ t3) = Just t3 eval1 (TmIf t1 t2 t3) | not $ isVal t1 = (\t1' -> TmIf t1' t2 t3) <$> eval1 t1 eval1 (TmPred TmZero) = Just TmZero eval1 (TmPred (TmSucc t)) | isNumericVal t = Just t eval1 (TmPred t) | not $ isVal t = TmPred <$> eval1 t eval1 (TmIsZero TmZero) = Just TmTrue eval1 (TmIsZero (TmSucc t)) | isNumericVal t = Just TmFalse eval1 (TmIsZero t) | not (isVal t) = TmIsZero <$> eval1 t eval1 (TmSucc t) | not $ isVal t = TmSucc <$> eval1 t eval1 _ = Nothing -- | Big step evaluator. eval' :: Term -> Maybe Term eval' (TmIf t1 t2 t3) = case eval' t1 of Just TmTrue -> eval' t2 Just TmFalse -> eval' t3 _ -> Nothing eval' (TmPred t) = case eval' t of Just TmZero -> Just TmZero Just (TmSucc t') -> Just t' _ -> Nothing eval' (TmSucc t) = case eval' t of Just TmZero -> Just $ TmSucc TmZero Just (TmSucc t) -> Just $ TmSucc $ TmSucc t _ -> Nothing eval' (TmIsZero t) = case eval' t of Just TmZero -> Just TmTrue Just (TmSucc t') -> Just TmFalse _ -> Nothing eval' t | isVal t = Just t | otherwise = Nothing
zeckalpha/TaPL
src/Language/TaPL/Arith/Eval.hs
mit
1,613
0
10
429
736
347
389
45
9
-- TODO: remove mkApp, unsafeUnApp {-# LANGUAGE TemplateHaskell, TypeOperators #-} module Language.CL.C.HOAS.Naming (function, cl) where import Language.CL.C.HOAS.AST import Language.CL.C.Types.Classes import Language.Haskell.TH import Control.Monad (join) import Data.Monoid (mempty) -- | 'function' should be used for user-defined functions. -- UNSAFE! should be used only inside cl splicing! function :: (Parameters a, RetType b) => (a -> Language.CL.C.HOAS.AST.Body b) -> (a -> Expression b) function def = mkApp $ mkFun (error "function") mempty def cl :: Q [Dec] -> Q [Dec] cl quote = join (mapM naming `fmap` quote) naming :: Dec -> Q Dec naming (FunD name [Clause funargs (NormalB expr) []]) = do flist <- mkFunargList funargs let newBody = AppE (AppE (VarE 'mkFunarged) flist) (AppE (mkEntry name) expr) return $ FunD name [Clause funargs (NormalB newBody) []] naming (ValD (VarP name) (NormalB expr) _) = return $ ValD (VarP name) (NormalB (AppE (mkEntry name) expr)) [] naming (FunD name _) = fail (show name ++ " -- clause should be only one!") naming a = return a -- leave other declarations unchanged mkFunargList :: [Pat] -> Q Exp mkFunargList args = do fars <- mapM f args return $ AppE (ConE 'Funargs) (ListE fars) where f (VarP v) = return $ AppE (VarE 'mkFunarg) (VarE v) f _ = fail "Pattern matching is not allowed!" mkFunarged :: (Parameters a, RetType b) => Funargs -> (a -> Expression b) -> (a -> Expression b) mkFunarged funargs fun = mkApp (addFunargs funargs $ unsafeUnApp fun) mkEntry :: Name -> Exp mkEntry identificator = AppE (VarE 'mkNamed) (LitE (StringL (show identificator))) mkNamed :: (Parameters a, RetType b) => String -> (a -> Expression b) -> (a -> Expression b) mkNamed ident fun = mkApp (setName ident $ unsafeUnApp fun)
pxqr/language-cl-c
Language/CL/C/HOAS/Naming.hs
mit
1,848
0
14
371
725
374
351
31
2
module Javelin.Lib.ByteCode.FieldMethod where import qualified Data.Binary.Get as Get import qualified Data.Map.Lazy as Map import qualified Data.Word as Word import qualified Javelin.Lib.ByteCode.Attribute as Attribute import qualified Javelin.Lib.ByteCode.Data as ByteCode import qualified Javelin.Lib.ByteCode.Utils as Utils fieldInfoAF :: Map.Map Word.Word16 ByteCode.FieldInfoAccessFlag fieldInfoAF = Map.fromList [ (0x0001, ByteCode.FieldPublic) , (0x0002, ByteCode.FieldPrivate) , (0x0004, ByteCode.FieldProtected) , (0x0008, ByteCode.FieldStatic) , (0x0010, ByteCode.FieldFinal) , (0x0040, ByteCode.FieldVolatile) , (0x0080, ByteCode.FieldTransient) , (0x1000, ByteCode.FieldSynthetic) , (0x4000, ByteCode.FieldEnum) ] methodInfoAF = Map.fromList [ (0x0001, ByteCode.MethodPublic) , (0x0002, ByteCode.MethodPrivate) , (0x0004, ByteCode.MethodProtected) , (0x0008, ByteCode.MethodStatic) , (0x0010, ByteCode.MethodFinal) , (0x0020, ByteCode.MethodSynchronized) , (0x0040, ByteCode.MethodBridge) , (0x0080, ByteCode.MethodVarargs) , (0x0100, ByteCode.MethodNative) , (0x0400, ByteCode.MethodAbstract) , (0x0800, ByteCode.MethodStrict) , (0x1000, ByteCode.MethodSynthetic) ] getFieldMethod :: Map.Map Word.Word16 flag -> ([flag] -> Word.Word16 -> Word.Word16 -> [ByteCode.AttrInfo] -> x) -> [ByteCode.Constant] -> Get.Get x getFieldMethod accessFlags constr pool = do maskBytes <- Get.getWord16be let mask = Utils.foldMask accessFlags maskBytes nameIndex <- Get.getWord16be descriptorIndex <- Get.getWord16be attrsCount <- Get.getWord16be attributes <- Utils.times (Attribute.getAttr pool) attrsCount return $ constr mask nameIndex descriptorIndex attributes getField :: [ByteCode.Constant] -> Get.Get ByteCode.FieldInfo getField = getFieldMethod fieldInfoAF ByteCode.FieldInfo getMethod :: [ByteCode.Constant] -> Get.Get ByteCode.MethodInfo getMethod = getFieldMethod methodInfoAF ByteCode.MethodInfo
antonlogvinenko/javelin
src/Javelin/Lib/ByteCode/FieldMethod.hs
mit
2,035
0
13
316
566
330
236
50
1
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} module Rushhour.Config where import Rushhour.Data ( Rushhour ) import Autolib.Reader import Autolib.ToDoc import Autolib.Reporter import Data.Typeable import qualified Challenger as C data Config = Config { width :: Int , height :: Int , num_cars :: Int , min_extension :: Int , max_extension :: Int , min_solution :: Int , max_solution :: Int , max_search_width :: Int } $(derives [makeReader, makeToDoc] [''Config]) example :: Config example = Config { width = 3, height = 3, num_cars = 10 , min_extension = 2, max_extension = 2 , min_solution = 10, max_solution = 30 , max_search_width = 30 } instance C.Verify Rushhour Config where verify p c = do assert ( min_extension c > 1 ) $ text "min_extension > 1" assert ( max_extension c > min_extension c ) $ text "max_extension > min_extension" assert ( width c > max_extension c ) $ text "width > max_extension" assert ( height c > max_extension c ) $ text "height > max_extension" assert ( num_cars c > 0 ) $ text "num_cars > 0" assert ( min_solution c > 0) $ text "min_solution > 0" assert ( max_solution c > min_solution c ) $ text "max_solution > min_solution" -- local variables: -- mode: haskell -- end:
Erdwolf/autotool-bonn
src/Rushhour/Config.hs
gpl-2.0
1,348
9
14
342
381
208
173
-1
-1
{-Curves.hs; Mun Hon Cheong ([email protected]) 2005 This modules is used to generate a biquadratic patch used in the Q3Map2 format. The code for this was translated from http://graphics.cs.brown.edu/games/quake/quake3.html it can also be found in the source code for Paul's Quake 3 BSP loader http://www.paulsprojects.net/opengl/q3bsp/q3bsp.html -} module Curves (checkForPatch, BSPPatch(..)) where import Foreign hiding (newArray) import Data.Array.IArray -- import Data.Array.MArray (newArray) import Data.Array.IO import Graphics.UI.GLUT (GLint, GLsizei) import Foreign.Storable data BSPPatch = BSPPatch { patchLOD :: Int, -- the level of tesselation patchPtr :: Ptr Float, -- points to patch vertices indexPtrPtr :: Ptr (Ptr GLint), -- points to indices numIndexPtr :: Ptr GLsizei -- the number of indices } deriving Show -- given a face type return a list of patches if the facetype is 2. -- Otherwise return an empty list. checkForPatch :: Int -> Int -> (Int, Int) -> (Ptr Float, Ptr Float, Ptr Float,Ptr Float, Ptr Word8) -> IO [BSPPatch] checkForPatch faceType startVIndex (width,height) vertData |faceType == 2 = do patches <- createPatches vertData startVIndex width height 4 return patches |otherwise = return [] -- Create control points for each patch. -- Each patch has 9 control points. getControlPointIndices :: Int -> Int -> Int -> [Int] getControlPointIndices i width height = concat [(create3x3ControlPoints x y)| y <-[0..(((height-1) `div` 2)-1)], x <-[0..(((width-1) `div` 2)-1)]] where create3x3ControlPoints x y = [(i+((y*2*width)+(x*2))+(row*width)+point) | row <- [0..2], point <- [0..2]] -- Take a list of control points and split them into lists of 9 splitControlPoints :: [VertTup] -> [[VertTup]] splitControlPoints [] = [] splitControlPoints tups = (take 9 tups):(splitControlPoints $ drop 9 tups) -- gets the control points getControlPoints :: (Ptr Float, Ptr Float, Ptr Float, Ptr Float, Ptr Word8) -> Int -> Int -> Int -> IO [Array Int VertTup] getControlPoints vertexData startIndex width height = do -- get the indices for the control points let indcs = getControlPointIndices startIndex width height -- get the vertices at those indices controlPoints <- mapM (readControlPoints vertexData) indcs -- divide the lists into arrays of 9 control points return $ map (listArray (0,8)) (splitControlPoints controlPoints) -- reads the control point information from the vertex arrays readControlPoints :: (Ptr Float, Ptr Float, Ptr Float,Ptr Float, Ptr Word8) -> Int -> IO VertTup readControlPoints (vert, uv, lmuv, _, _) i = do x <- peekElemOff vert vertIndex -- vertex coord y <- peekElemOff vert (vertIndex+1) z <- peekElemOff vert (vertIndex+2) u <- peekElemOff uv uvIndex -- tex coord v <- peekElemOff uv (uvIndex+1) lmu <- peekElemOff lmuv lmIndex -- lightmap coord lmv <- peekElemOff lmuv (lmIndex+1) return (x,y,z,u,v,lmu,lmv) where vertIndex = i*3 uvIndex = i*2 lmIndex = i*2 -- write the coordinate, texture coordinate and lightmap coordinates -- for the cntrol points writeControlPointData :: [VertTup] -> Int -> Ptr Float -> IO () writeControlPointData [] _ _ = return() writeControlPointData ((a,b,c,d,e,f,g):rest) indx ptr = do let i = (indx*7) pokeElemOff ptr i a pokeElemOff ptr (i+1) b pokeElemOff ptr (i+2) c pokeElemOff ptr (i+3) d pokeElemOff ptr (i+4) e pokeElemOff ptr (i+5) f pokeElemOff ptr (i+6) g writeControlPointData rest (indx+1) ptr type VertTup = (Float,Float,Float,Float,Float,Float,Float) -- multiplies a set of floats by n mul7 :: VertTup -> Float -> VertTup mul7 (a,b,c,d,e,f,g) n = ((n*a),(n*b),(n*c),(n*d),(n*e),(n*f),(n*g)) -- adds to sets of floats together add7 :: VertTup -> VertTup -> VertTup add7 (u1,u2,u3,u4,u5,u6,u7) (v1,v2,v3,v4,v5,v6,v7) = (u1+v1,u2+v2,u3+v3,u4+v4,u5+v5,u6+v6,u7+v7) -- create a set of patches createPatches :: (Ptr Float, Ptr Float, Ptr Float, Ptr Float, Ptr Word8) -> Int -> Int -> Int -> Int -> IO [BSPPatch] createPatches vertData startVert width height tesselation = do controlPoints <- getControlPoints vertData startVert width height patches <- mapM (createPatch tesselation) controlPoints return patches createPatch :: Int -> Array Int VertTup -> IO BSPPatch createPatch tesselation controlPoints = do ptr <- mallocBytes (((tesselation+1)*(tesselation+1))*28) createPatch' tesselation ptr controlPoints createPatch'' tesselation ptr controlPoints (numiptr,iptrptr)<- generateIndices tesselation return (BSPPatch { patchLOD = tesselation, patchPtr = ptr, indexPtrPtr = iptrptr, numIndexPtr = numiptr }) createPatch' ::Int -> Ptr Float -> Array Int VertTup -> IO() createPatch' tess ptr arr = do let patchVerts = map (bezier tess (arr!0) (arr!3) (arr!6)) [0..tess] writeControlPointData patchVerts 0 ptr createPatch'' ::Int -> Ptr Float -> Array Int VertTup -> IO() createPatch'' tess ptr arr = do mapM_ (createPatch''' tess ptr arr) [1..tess] createPatch''' ::Int -> Ptr Float -> Array Int VertTup -> Int -> IO() createPatch''' tess ptr arr u = do let tup1 = bezier tess (arr!0) (arr!1) (arr!2) u let tup2 = bezier tess (arr!3) (arr!4) (arr!5) u let tup3 = bezier tess (arr!6) (arr!7) (arr!8) u let patchVerts = map (bezier tess tup1 tup2 tup3) [0..tess] writeControlPointData patchVerts 0 (plusPtr ptr (((tess+1)*u)*28)) bezier :: Int -> VertTup -> VertTup -> VertTup -> Int -> VertTup bezier tes cp1 cp2 cp3 i = add7 (add7 d1 d2) d3 where d1 = mul7 cp1 ((1-p)*(1-p)) d2 = mul7 cp2 ((1-p)*p*2) d3 = mul7 cp3 (p*p) p = (realToFrac i)/(realToFrac tes) -- generate indices generateIndices :: Int -> IO (Ptr GLsizei, Ptr (Ptr GLint)) generateIndices tess = do indexArray <- newArray (0,((tess*(tess+1)*2)-1)) 0 let pt1 = [ ((((row*(tess+1))+point)*2)+1, fromIntegral ((row*(tess+1))+point)) | row<-[0..(tess-1)], point<-[0..tess]] let pt2 = [ ((((row*(tess+1))+point)*2), fromIntegral (((row+1)*(tess+1))+point)) | row<-[0..(tess-1)], point<-[0..tess]] mapM_ (writeIndices indexArray) pt1 mapM_ (writeIndices indexArray) pt2 indexList <- (getElems indexArray) indexPtr <- mallocBytes ((tess * (tess+1)*2) * (sizeOf (undefined :: GLint))) pokeArray indexPtr indexList numArrayIndicesPtr <- mallocBytes (tess * (sizeOf (undefined :: GLsizei))) pokeArray numArrayIndicesPtr (map (\_->(fromIntegral (2*(tess+1)))) [0..(tess-1)]) indexptrptr <- mallocBytes (tess * (sizeOf (undefined :: Ptr GLint))) let ptrPtr = map (plusPtr indexPtr) [((sizeOf (undefined :: GLint)) * (row*2*(tess+1))) | row <-[0..(tess-1)]] pokeArray indexptrptr ptrPtr return (numArrayIndicesPtr, indexptrptr) -- writes the indices to memory writeIndices :: IOArray Int GLint -> (Int,GLint) -> IO () writeIndices indcs (pos,content) = writeArray indcs pos content
kvelicka/frag
src/Curves.hs
gpl-2.0
7,631
7
20
1,948
2,880
1,520
1,360
129
1
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} {-# language MultiParamTypeClasses #-} {-# language PatternSignatures #-} {-# language OverlappingInstances #-} module Haskell.Blueprint.Central where import Debug ( debug ) import Haskell.Blueprint.Data import Haskell.Blueprint.Match import qualified Language.Haskell.Exts as E import qualified Language.Haskell.Exts.Parser as P -- import qualified Language.Haskell.Syntax as S import qualified Language.Haskell.Exts.SrcLoc as S import Data.Generics.Schemes (gtypecount) import qualified Mueval.ArgsParse as M import qualified Mueval.Interpreter import qualified Language.Haskell.Interpreter as I import qualified Mueval.Context import Challenger.Partial import Autolib.ToDoc import Autolib.Reader import Autolib.Size import Autolib.Reporter.IO.Type import qualified Autolib.Reporter as R import Inter.Types import Inter.Quiz import Data.Typeable import qualified Control.Exception import Control.Monad.IO.Class import Test.SmallCheck import System.IO.Temp -- import System.IO.UTF8 import System.Random ( randomRIO ) -- import qualified System.IO.Strict import qualified System.IO import qualified System.Directory import qualified System.Posix.Directory as SPD data Haskell_Blueprint = Haskell_Blueprint deriving Typeable derives [makeReader, makeToDoc] [''Haskell_Blueprint] instance Show Haskell_Blueprint where show = render . toDoc instance OrderScore Haskell_Blueprint where scoringOrder h = Increasing instance Verify Haskell_Blueprint Code where verify _ ( Code i ) = do Haskell.Blueprint.Central.parse i return () -- we measure the difference in size instance Measure Haskell_Blueprint Code Code where measure p i b = fromIntegral $ size b - size i instance Partial Haskell_Blueprint Code Code where describe p i = vcat [ text "Vervollständigen Sie das Haskell-Programm." , text "Ersetzen Sie jedes 'undefined'," , text "so daß der Ausdruck \'test\' den Wert True hat." , nest 4 $ toDoc i ] initial p i = i partial p ( Code i ) ( Code b ) = do mi <- Haskell.Blueprint.Central.parse i mb <- Haskell.Blueprint.Central.parse b R.inform $ text "paßt Ihr Quelltext zum Muster?" case Haskell.Blueprint.Match.test mi mb of Fail loc -> reject_parse b loc "Nein" Haskell.Blueprint.Match.Ok _ -> R.inform $ text "Ja." totalIO p (Code i) (Code b) = do r <- liftIO $ run_total i b -- liftIO $ debug "outside runInterpreter" case r of Left err -> reject $ text $ show err Right ( e, et, val ) -> do inform $ vcat [ text "expression" </> text e , text "type" </> text et ] assert ( et == "Bool" ) $ text "richtiger Typ?" v <- liftIO ( ( do Control.Exception.evaluate val ; return ( Right val ) ) `Control.Exception.catch` \ ( e :: Control.Exception.SomeException ) -> do return $ Left ( show e ) ) case v of Right val -> assert ( val == "True" ) $ text "richtiger Wert?" Left ex -> reject $ text "Exception" </> text ex run_total_opts f = let Right opts0 = M.interpreterOpts [] in opts0 { M.timeLimit = 10 -- seconds? , M.modules = Just [ ] , M.loadFile = f , M.expression = "Blueprint.test" -- http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#premature-script-headers -- Another cause for the "premature end of script headers" message -- are the RLimitCPU and RLimitMEM directives. -- You may get the message if the CGI script was killed due to a resource limit. , M.rLimits = False } run_total i b = withTempDirectory "/tmp" "Blue" $ \ d -> ( do let f = d ++ "/" ++ "Blueprint.hs" debug $ unwords [ "Blueprint tmpfile is", f ] System.IO.writeFile f b keepCurrentDir $ do System.Directory.setCurrentDirectory d I.runInterpreter $ Mueval.Interpreter.interpreter ( run_total_opts f ) ) `Control.Exception.catch` \ ( e :: Control.Exception.SomeException ) -> do debug $ "interpreter got exception " ++ show e return $ Left $ I.UnknownError ( show e ) -- debug $ "after runInterpreter" -- length ( show r ) `seq` -- return r -- System.Directory.removeFile f -- return r -- | this is necessary because mueval -- changes currentDir without resetting keepCurrentDir action = Control.Exception.bracket System.Directory.getCurrentDirectory System.Directory.setCurrentDirectory $ \ d -> action make_fixed = direct Haskell_Blueprint code_example parse m = case E.readExtensions m of Nothing -> R.reject $ text "cannot parse LANGUAGE pragmas at top of file" Just (lang, exts) -> let pamo = P.defaultParseMode { P.extensions = exts } in case P.parseModuleWithMode pamo m of P.ParseOk a -> return a P.ParseFailed loc msg -> reject_parse m loc msg reject_parse m loc msg = let ( lpre, lpost ) = splitAt ( S.srcLine loc ) $ lines m lpre' = reverse $ take 3 $ reverse lpre tag = replicate ( S.srcColumn loc - 1 ) '.' ++ "^" in R.reject $ vcat ( map text lpre' ++ [ text tag, text msg ] ) -- this is the size of the syntax tree. -- TODO: count just the nodes that are visible. -- otherwise, it's not understandable for the student. instance Size Code where size ( Code cs ) = case R.result $ Haskell.Blueprint.Central.parse cs of Just m -> gtypecount ( undefined :: E.Exp ) m _ -> 0
marcellussiegburg/autotool
collection/src/Haskell/Blueprint/Central.hs
gpl-2.0
6,010
0
23
1,759
1,422
750
672
118
3
{-# OPTIONS -XNoMonoLocalBinds #-} module Grin.DeadCode(deadCode) where import Control.Monad import Data.Monoid import qualified Data.Set as Set import Fixer.Fixer import Fixer.Supply import Grin.Grin import Grin.Noodle import Grin.Whiz import Stats hiding(print, singleton) import StringTable.Atom import Support.CanType import Support.FreeVars import Util.Gen import Util.SetLike hiding(Value) implies :: Value Bool -> Value Bool -> Rule implies x y = y `isSuperSetOf` x -- | Remove dead code from Grin. deadCode :: Stats.Stats -- ^ stats to update with what was done -> [Atom] -- ^ roots -> Grin -- ^ input -> IO Grin -- ^ output deadCode stats roots grin = do fixer <- newFixer usedFuncs <- newSupply fixer usedArgs <- newSupply fixer usedCafs <- newSupply fixer pappFuncs <- newValue fixer bottom suspFuncs <- newValue fixer bottom -- set all roots as used flip mapM_ roots $ \r -> do addRule $ value True `implies` sValue usedFuncs r let postInline = phaseEvalInlined (grinPhase grin) forM_ (grinCafs grin) $ \ (v,NodeC t []) -> do (0,fn) <- tagUnfunction t v' <- supplyValue usedCafs v addRule $ conditionalRule id v' $ (suspFuncs `isSuperSetOf` value (singleton fn)) addRule $ v' `implies` (sValue usedFuncs fn) mapM_ (go fixer pappFuncs suspFuncs usedFuncs usedArgs usedCafs postInline) (grinFuncs grin) findFixpoint Nothing {-"Dead Code"-} fixer ua <- supplyReadValues usedArgs uc <- supplyReadValues usedCafs uf <- supplyReadValues usedFuncs pappFuncs <- readValue pappFuncs suspFuncs <- readValue suspFuncs when False $ do putStrLn "usedArgs" mapM_ print ua putStrLn "usedCafs" mapM_ print uc putStrLn "usedFuncs" mapM_ print uf putStrLn "pappFuncs" print pappFuncs putStrLn "suspFuncs" print suspFuncs let cafSet = fg uc funSet = fg uf argSet = fg ua `union` fromList [ (n,i) | FuncDef n (args :-> _) _ _ <- grinFunctions grin, n `member` grinEntryPoints grin, i <- [0 .. length args] ] directFuncs = funSet \\ suspFuncs \\ pappFuncs fg xs = fromList [ x | (x,True) <- xs ] newCafs <- flip mconcatMapM (grinCafs grin) $ \ (x,y) -> if x `member` cafSet then return [(x,y)] else tick stats "Optimize.dead-code.caf" >> return [] let f ((x,y):xs) rs ws = do if not $ x `member` funSet then tick stats "Optimize.dead-code.func" >> f xs rs ws else do (ws',r) <- runStatIO stats $ removeDeadArgs postInline funSet directFuncs cafSet argSet (x,y) ws f xs (r:rs) ws' f [] rs _ = return rs newFuncs <- f (grinFuncs grin) [] whizState --newFuncs <- flip mconcatMapM (grinFuncs grin) $ \ (x,y) -> do let (TyEnv mp) = grinTypeEnv grin mp' <- flip mconcatMapM (toList mp) $ \ (x,tyty@TyTy { tySlots = ts }) -> case Just x of Just _ | tagIsFunction x, not $ x `member` funSet -> return [] Just fn | fn `member` directFuncs -> do let da (t,i) | member (fn,i) argSet = return [t] | otherwise = tick stats ("Optimize.dead-code.arg-func.{" ++ show x ++ "-" ++ show i) >> return [] ts' <- mconcatMapM da (zip ts naturals) return [(x,tyty { tySlots = ts' })] _ -> return [(x,tyty)] return $ setGrinFunctions newFuncs grin { grinCafs = newCafs, grinPartFunctions = pappFuncs, grinTypeEnv = TyEnv $ fromList mp', --grinArgTags = Map.fromList newArgTags, grinSuspFunctions = suspFuncs } combineArgs fn as = [ ((fn,n),a) | (n,a) <- zip [0 :: Int ..] as] go fixer pappFuncs suspFuncs usedFuncs usedArgs usedCafs postInline (fn,as :-> body) = ans where goAgain = go fixer pappFuncs suspFuncs usedFuncs usedArgs usedCafs postInline ans = do usedVars <- newSupply fixer flip mapM_ (combineArgs fn as) $ \ (ap,Var v _) -> do x <- supplyValue usedArgs ap v <- supplyValue usedVars v addRule $ v `implies` x -- a lot of things are predicated on this so that CAFS are not held on to unnecesarily fn' <- supplyValue usedFuncs fn let varValue v | v < v0 = sValue usedCafs v | otherwise = sValue usedVars v f e = g e >> return e g (BaseOp Eval [e]) = addRule (doNode e) g (BaseOp Apply {} vs) = addRule (mconcatMap doNode vs) g (Case e _) = addRule (doNode e) g Prim { expArgs = as } = addRule (mconcatMap doNode as) g (App a vs _) = do addRule $ conditionalRule id fn' $ mconcat [ mconcatMap (implies (sValue usedArgs fn) . varValue) (freeVars a) | (fn,a) <- combineArgs a vs] addRule $ fn' `implies` sValue usedFuncs a addRule (mconcatMap doNode vs) g (BaseOp Overwrite [Var v _,n]) | v < v0 = do v' <- supplyValue usedCafs v addRule $ conditionalRule id v' $ doNode n g (BaseOp Overwrite [vv,n]) = addRule $ (doNode vv) `mappend` (doNode n) g (BaseOp PokeVal [vv,n]) = addRule $ (doNode vv) `mappend` (doNode n) g (BaseOp PeekVal [vv]) = addRule $ (doNode vv) g (BaseOp Promote [vv]) = addRule $ (doNode vv) g (BaseOp _ xs) = addRule $ mconcatMap doNode xs g Alloc { expValue = v, expCount = c, expRegion = r } = addRule $ doNode v `mappend` doNode c `mappend` doNode r g Let { expDefs = defs, expBody = body } = do mapM_ goAgain [ (name,bod) | FuncDef { funcDefBody = bod, funcDefName = name } <- defs] flip mapM_ (map funcDefName defs) $ \n -> do --n' <- supplyValue usedFuncs n --addRule $ fn' `implies` n' return () g Error {} = return () -- TODO - handle function and case return values smartier. g (Return ns) = mapM_ (addRule . doNode) ns g x = error $ "deadcode.g: " ++ show x h' (p,e) = h (p,e) >> return (Just (p,e)) h (p,BaseOp (StoreNode _) [v]) = addRule $ mconcat $ [ conditionalRule id (varValue pv) (doNode v) | pv <- freeVars p] h (p,BaseOp Demote [v]) = addRule $ mconcat $ [ conditionalRule id (varValue pv) (doNode v) | pv <- freeVars p] h (p,Alloc { expValue = v, expCount = c, expRegion = r }) = addRule $ mconcat $ [ conditionalRule id (varValue pv) (doNode v `mappend` doNode c `mappend` doNode r) | pv <- freeVars p] h (p,Return vs) = mapM_ (h . \v -> (p,BaseOp Promote [v])) vs -- addRule $ mconcat $ [ conditionalRule id (varValue pv) (doNode v) | pv <- freeVars p] h (p,BaseOp Promote [v]) = addRule $ mconcat $ [ conditionalRule id (varValue pv) (doNode v) | pv <- freeVars p] h (p,e) = g e doNode (NodeC n as) | not postInline, Just (x,fn) <- tagUnfunction n = let consts = (mconcatMap doNode as) usedfn = implies fn' (sValue usedFuncs fn) suspfn | x > 0 = conditionalRule id fn' (pappFuncs `isSuperSetOf` value (singleton fn)) | otherwise = conditionalRule id fn' (suspFuncs `isSuperSetOf` value (singleton fn)) in mappend consts $ mconcat (usedfn:suspfn:[ mconcatMap (implies (sValue usedArgs fn) . varValue) (freeVars a) | (fn,a) <- combineArgs fn as]) doNode x = doConst x `mappend` mconcatMap (implies fn' . varValue) (freeVars x) doConst _ | postInline = mempty doConst (Const n) = doNode n doConst (NodeC n as) = mconcatMap doConst as doConst _ = mempty (nl,_) <- whiz (\_ -> id) h' f whizState (as :-> body) return nl removeDeadArgs :: MonadStats m => Bool -> Set.Set Atom -> Set.Set Atom -> (Set.Set Var) -> (Set.Set (Atom,Int)) -> (Atom,Lam) -> WhizState -> m (WhizState,(Atom,Lam)) removeDeadArgs postInline funSet directFuncs usedCafs usedArgs (a,l) whizState = whizExps f (margs a l) >>= \(l,ws) -> return (ws,(a,l)) where whizExps f l = whiz (\_ x -> x) (\(p,e) -> f e >>= \e' -> return (Just (p,e'))) f whizState l margs fn (as :-> e) | a `Set.member` directFuncs = ((removeArgs fn as) :-> e) margs _ x = x f (App fn as ty) = do as <- dff fn as as <- mapM clearCaf as return $ App fn as ty f (Return [NodeC fn as]) | Just fn' <- tagToFunction fn = do as <- dff' fn' as as <- mapM clearCaf as return $ Return [NodeC fn as] f (BaseOp (StoreNode False) [NodeC fn as]) | Just fn' <- tagToFunction fn = do as <- dff' fn' as as <- mapM clearCaf as return $ BaseOp (StoreNode False) [NodeC fn as] f (BaseOp Overwrite [(Var v TyINode),_]) | deadCaf v = do mtick $ toAtom "Optimize.dead-code.caf-update" return $ Return [] f (BaseOp Overwrite [p,NodeC fn as]) | Just fn' <- tagToFunction fn = do as <- dff' fn' as as <- mapM clearCaf as return $ BaseOp Overwrite [p,NodeC fn as] -- f (Update (Var v TyINode) _) | deadCaf v = do -- mtick $ toAtom "Optimize.dead-code.caf-update" -- return $ Return [] -- f (Update p (NodeC fn as)) | Just fn' <- tagToFunction fn = do -- as <- dff' fn' as -- as <- mapM clearCaf as -- return $ Update p (NodeC fn as) f lt@Let { expDefs = defs } = return $ updateLetProps lt { expDefs = defs' } where defs' = [ updateFuncDefProps df { funcDefBody = margs name body } | df@FuncDef { funcDefName = name, funcDefBody = body } <- defs, name `Set.member` funSet ] f x = return x dff' fn as | fn `member` directFuncs = return as dff' fn as = dff'' fn as dff fn as | fn `member` directFuncs = return (removeArgs fn as) dff fn as = dff'' fn as dff'' fn as | not (fn `member` funSet) = return as -- if function was dropped, we don't have argument use information. dff'' fn as = mapM df (zip as naturals) where df (a,i) | not (deadVal a) && not (member (fn,i) usedArgs) = do mtick $ toAtom "Optimize.dead-code.func-arg" return $ properHole (getType a) df (a,_) = return a clearCaf (Var v TyINode) | deadCaf v = do mtick $ toAtom "Optimize.dead-code.caf-arg" return (properHole TyINode) clearCaf (NodeC a xs) = do xs <- mapM clearCaf xs return $ NodeC a xs clearCaf (Index a b) = return Index `ap` clearCaf a `ap` clearCaf b clearCaf (Const a) = Const `liftM` clearCaf a clearCaf x = return x deadCaf v = v < v0 && not (v `member` usedCafs) deadVal (Lit 0 _) = True deadVal x = isHole x removeArgs fn as = concat [ perhapsM ((fn,i) `member` usedArgs) a | a <- as | i <- naturals ]
dec9ue/jhc_copygc
src/Grin/DeadCode.hs
gpl-2.0
11,021
32
32
3,396
4,140
2,101
2,039
-1
-1
{-# LANGUAGE TemplateHaskell #-} module NFA.Property where import Autolib.Reader import Autolib.ToDoc import Data.Typeable import Autolib.Set import Autolib.NFA data NFAC c Int => Property c = Sane | Min_Size Int | Max_Size Int | Alphabet ( Set c ) | Deterministic | Non_Deterministic | Minimal | Complete | Reduced -- no useless states deriving ( Typeable , Eq ) $(derives [makeReader, makeToDoc] [''Property]) example :: [ Property Char ] example = [ Sane , Min_Size 4 , Max_Size 6 , Alphabet $ mkSet "ab" ] -- local variables; -- mode: haskell; -- end;
florianpilz/autotool
src/NFA/Property.hs
gpl-2.0
652
2
9
188
166
96
70
-1
-1