code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module GHCJS.TypeScript.Convert.Types where import Language.TypeScript import Data.Monoid data Config = Config { outputDir :: FilePath } data Decl = InterfaceDecl Interface deriving (Show) data OutputModule = OutputModule { omImports :: [String] , omDecls :: [String] } deriving (Show) instance Monoid OutputModule where mempty = OutputModule [] [] mappend (OutputModule imports1 decls1) (OutputModule imports2 decls2) = OutputModule (imports1 <> imports2) (decls1 <> decls2)
mgsloan/ghcjs-typescript
ghcjs-typescript-convert/GHCJS/TypeScript/Convert/Types.hs
mit
530
0
9
116
150
85
65
18
0
module Interpreter (Val(..), Expr(..), interpret) where import Debug.Trace data Val = IntVal Integer | StringVal String | BooleanVal Bool -- since we are implementing a Functional language, functions are -- first class citizens. | FunVal [String] Expr Env deriving (Show, Eq) ----------------------------------------------------------- data Expr = Const Val -- represents a variable | Var String -- integer multiplication | Expr :*: Expr -- integer addition and string concatenation | Expr :+: Expr -- equality test. Defined for all Val except FunVal | Expr :==: Expr -- semantically equivalent to a Haskell `if` | If Expr Expr Expr -- binds a Var (the first `Expr`) to a value (the second `Expr`), -- and makes that binding available in the third expression | Let Expr Expr Expr -- creates an anonymous function with an arbitrary number of parameters | Lambda [Expr] Expr -- calls a function with an arbitrary number values for parameters | Apply Expr [Expr] deriving (Show, Eq) ----------------------------------------------------------- data Env = EmptyEnv | ExtendEnv String Val Env deriving (Show, Eq) ----------------------------------------------------------- -- the evaluate function takes an environment, which holds variable -- bindings; i.e. it stores information like `x = 42` -- the trace there will print out the values with which the function was called, -- you can easily uncomment it if you don't need it for debugging anymore. evaluate:: Expr -> Env -> Val evaluate expr env = trace("expr= " ++ (show expr) ++ "\n env= " ++ (show env)) $ case expr of Const v -> v lhs :+: rhs -> let valLhs = evaluate lhs env valRhs = evaluate rhs env in (IntVal $ (valToInteger valRhs) + (valToInteger valLhs)) _ -> error $ "unimplemented expression: " ++ (show expr) ----------------------------------------------------------- valError s v = error $ "expected: " ++ s ++ "; got: " ++ (show v) -- helper function to remove some of the clutter in the evaluate function valToInteger:: Val -> Integer valToInteger (IntVal n) = n valToInteger v = valError "IntVal" v ----------------------------------------------------------- -- the function that we test. since we always start out with an EmptyEnv. interpret :: Expr -> Val interpret expr = evaluate expr EmptyEnv --------------------------------------------------------------------- --------------------------------------------------------------------- ---------------------------- Tests ---------------------------------- --------------------------------------------------------------------- --------------------------------------------------------------------- testConstant = assert result (IntVal 2) "testConstant" where result = interpret expr expr = Const (IntVal 2) --------------------------------------------------------------------- testAddition = assert result (IntVal 2) "testAddition" where result = interpret expr expr = (Const (IntVal 1)) :+: (Const (IntVal 1)) --------------------------------------------------------------------- testComplexAddition = assert result (IntVal 9) "testComplexAddition" where result = interpret expr expr = (lhs :+: rhs) lhs = (Const (IntVal 1)) :+: (Const (IntVal 1)) rhs = (Const (IntVal 3)) :+: (Const (IntVal 4)) --------------------------------------------------------------------- testEvenMoreComplexAddition = assert result (IntVal 18) "testEvenMoreComplexAddition" where result = interpret expr expr = (l :+: r) l = lhs :+: rhs r = rhs :+: lhs lhs = (Const (IntVal 1)) :+: (Const (IntVal 1)) rhs = (Const (IntVal 3)) :+: (Const (IntVal 4)) --------------------------------------------------------------------- testMultiplication = assert result (IntVal 42) "testMultiplication" where result = interpret expr expr = (Const (IntVal 7)) :*: (Const (IntVal 6)) --------------------------------------------------------------------- testConcatenation = assert result (StringVal "12") "testConcatenation" where result = interpret expr expr = (Const (StringVal "1")) :+: (Const (StringVal "2")) --------------------------------------------------------------------- testEqualString = assert resultPositive (BooleanVal True) "testEqualStringPos" && assert resultNegative (BooleanVal False) "testEqualStringNeg" where resultPositive = interpret exprPositive exprPositive = (Const (StringVal "1")) :==: (Const (StringVal "1")) resultNegative = interpret exprNegative exprNegative = (Const (StringVal "1")) :==: (Const (StringVal "2")) --------------------------------------------------------------------- testEqualInt = assert resultPositive (BooleanVal True) "testEqualIntPos" && assert resultNegative (BooleanVal False) "testEqualIntNeg" where resultPositive = interpret exprPositive exprPositive = (Const (IntVal 1)) :==: (Const (IntVal 1)) resultNegative = interpret exprNegative exprNegative = (Const (IntVal 1)) :==: (Const (IntVal 2)) --------------------------------------------------------------------- testEqualBool = assert resultPositive (BooleanVal True) "testEqualBoolPos" && assert resultNegative (BooleanVal False) "testEqualBoolNeg" where resultPositive = interpret exprPositive exprPositive = (Const (BooleanVal True)) :==: (Const (BooleanVal True)) resultNegative = interpret exprNegative exprNegative = (Const (BooleanVal True)) :==: (Const (BooleanVal False)) --------------------------------------------------------------------- testIf = assert resultThen (IntVal 42) "testIfThen" && assert resultElse (StringVal "42") "testIfElse" where resultThen = interpret exprThen exprThen = (If (Const (IntVal 1) :==: Const (IntVal 1)) (Const (IntVal 42)) (Const (StringVal "42")) ) resultElse = interpret exprElse exprElse = (If (Const (IntVal 1) :==: Const (IntVal 2)) (Const (IntVal 42)) (Const (StringVal "42"))) --------------------------------------------------------------------- testLet = assert result (IntVal 42) "testLet" && assert resultShadow (IntVal 84) "testLetShadow" where result = interpret expr -- ~(let x=42 in x) expr = Let (Var "x") (Const (IntVal 42)) (Var "x") -- ~ (let x=42 in (let x=84 in x)) -- the second redefinition of x shadows the first one exprShadow = (Let (Var "x") (Const (IntVal 42)) (Let (Var "x") (Const (IntVal 84)) (Var "x")) ) resultShadow = interpret exprShadow --------------------------------------------------------------------- testLambdaAndApply = assert result (IntVal 42) "testLambdaAndApply" where result = interpret expr -- equivalent to: (\x y -> x * y) 6 7 expr = (Apply (Lambda [Var "x", Var "y"] ((Var "x") :*: (Var "y")) ) [Const (IntVal 6), Const (IntVal 7)] ) --------------------------------------------------------------------- testCurrying = assert result (IntVal 42) "testCurrying" where result = interpret expr --equivalent to: ((\x -> \y -> x * y) 6) 7 expr = (Apply (Apply (Lambda [Var "x"] (Lambda [Var "y"] ((Var "x") :*: (Var "y")) ) ) ([Const (IntVal 6)]) ) ([Const (IntVal 7)]) ) --------------------------------------------------------------------- testAll = if (allPassed) then "All tests passed." else error "Failed tests." where allPassed = testConstant && testAddition && testComplexAddition && testEvenMoreComplexAddition && testMultiplication && testConcatenation && testEqualString && testEqualInt && testEqualBool && testIf && testLet && testLambdaAndApply && testCurrying --------------------------------------------------------------------- assert :: Val -> Val -> String -> Bool assert expected received message = if (expected == received) then True else error $ message ++ " -> expected: `" ++ (show expected) ++ "`; received: `" ++ (show received) ++ "`"
2015-Fall-UPT-PLDA/homework
02/your_full_name_here.hs
mit
8,926
0
18
2,338
1,999
1,052
947
145
3
-------------------------------------------------------------------- -- | -- Module : My.Data.Maybe -- Copyright : 2009 (c) Dmitry Antonyuk -- License : MIT -- -- Maintainer: Dmitry Antonyuk <[email protected]> -- Stability : experimental -- Portability: portable -- -- 'Maybe' related utilities. -- -------------------------------------------------------------------- module My.Data.Maybe where import Control.Applicative (Applicative, pure, (<$>)) boolToMaybe, (?) :: Bool -> a -> Maybe a boolToMaybe True x = Just x boolToMaybe _ _ = Nothing (?) = boolToMaybe boolToMaybeM :: (Applicative f) => Bool -> f a -> f (Maybe a) boolToMaybeM True m = Just <$> m boolToMaybeM _ _ = pure Nothing tryMaybe :: IO a -> IO (Maybe a) tryMaybe act = fmap Just act `catch` (\_ -> return Nothing)
lomeo/my
src/My/Data/Maybe.hs
mit
810
0
10
138
200
114
86
11
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module Main where import Test.Tasty import Test.Tasty.QuickCheck as QC import Test.QuickCheck.Monadic (assert, monadicIO, run) import Control.Applicative import qualified Data.ByteString as BR import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Lazy.Char8 as B import Data.Digest.CRC16 import Data.Typeable import Data.Word import Foreign.C.String import Foreign.C.Types import GHC.Generics newtype ITA2String = ITA2String String deriving (Eq, Generic, Ord, Show, Typeable) instance Arbitrary ITA2String where arbitrary = ita2String where ita2Char = oneof (map return "QWERTYUIOPASDFGHJKLZXCVBNM\r\n 1234567890-!&#'()\"/:;?,.") ita2String = ITA2String <$> listOf ita2Char foreign import ccall "crc16.h crc16" c_crc16 :: CString -> CInt -> CInt crcReference :: ITA2String -> IO Word16 crcReference (ITA2String s) = (\x -> fromIntegral $ c_crc16 x (fromIntegral . length $ s)) <$> newCString s crcHaskellF :: Word16 -> Bool -> Word16 -> [Word8] -> Word16 crcHaskellF poly inverse initial = BR.foldl (crc16Update poly inverse) initial . BR.pack crcHaskell :: ITA2String -> IO Word16 crcHaskell (ITA2String s) = return $ crcHaskellF 0x1021 False 0xffff [fromIntegral (fromEnum x) :: Word8 | x <- s] toHex :: Word16 -> B.ByteString toHex n = BB.toLazyByteString . BB.word16Hex $ n prop_hask_c_crc16 :: ITA2String -> Property prop_hask_c_crc16 s = monadicIO $ do c <- run (toHex <$> crcReference s) hask <- run (toHex <$> crcHaskell s) assert $ c == hask main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [properties] properties :: TestTree properties = testGroup "Properties" [qcProps] qcProps :: TestTree qcProps = testGroup "(checked by QuickCheck)" [ QC.testProperty "crcReference === crcHaskell ∀ ita2 strings" prop_hask_c_crc16 ]
noexc/mapview
tests/test.hs
mit
1,907
0
12
300
557
303
254
46
1
module Main where import Control.Arrow (first) import Control.Monad (liftM) import qualified Crypto.Cipher as Cipher import qualified Crypto.Cipher.AES as AES import qualified Crypto.Cipher.Types as CipherTypes import qualified Cryptopals.Set1 as Set1 import Cryptopals.Set2 import Data.Bits (popCount, xor) import qualified Data.ByteString as BS import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString.Base64 as B64 import qualified Data.ByteString.Char8 as C8 import Data.Char (ord) import Data.List (group, sort, transpose, unfoldr) import qualified Data.List.Key as K import Data.List.Split (chunksOf) import qualified Data.Map as M import qualified Data.Set as S import qualified Data.Word8 as W8 main :: IO () main = putStrLn "hi"
charlescharles/cryptopals
src/Main.hs
mit
982
0
6
316
202
138
64
22
1
module ReaderT where newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a } instance Functor m => Functor (ReaderT r m) where fmap f (ReaderT rma) = ReaderT $ fmap f . rma instance Applicative m => Applicative (ReaderT r m) where pure a = ReaderT $ \_ -> pure a -- fab :: r -> m (a -> b) -- a :: r -> m a -- f <*> x :: ReaderT r m b (ReaderT fmab) <*> (ReaderT rma) = ReaderT $ (<*>) <$> fmab <*> rma instance Monad m => Monad (ReaderT r m) where return = pure (ReaderT rma) >>= f = ReaderT $ \r -> (rma r >>= (\a -> runReaderT (f a) r))
JoshuaGross/haskell-learning-log
Code/Haskellbook/ComposeTypes/src/ReaderT.hs
mit
563
0
14
145
243
127
116
10
0
module Colors.SolarizedDark where colorScheme = "solarized-dark" colorBack = "#002b36" colorFore = "#839496" -- Black color00 = "#073642" color08 = "#002b36" -- Red color01 = "#dc322f" color09 = "#cb4b16" -- Green color02 = "#859900" color10 = "#586e75" -- Yellow color03 = "#b58900" color11 = "#657b83" -- Blue color04 = "#268bd2" color12 = "#839496" -- Magenta color05 = "#d33682" color13 = "#6c71c4" -- Cyan color06 = "#2aa198" color14 = "#93a1a1" -- White color07 = "#eee8d5" color15 = "#fdf6e3" colorTrayer :: String colorTrayer = "--tint 0x002b36"
phdenzel/dotfiles
.config/xmonad/lib/Colors/SolarizedDark.hs
mit
558
0
4
87
119
75
44
22
1
module SpaceAge (Planet(..), ageOn) where data Planet ageOn :: Planet -> Float -> Float ageOn planet seconds = undefined
parkertm/exercism
haskell/space-age/src/SpaceAge.hs
mit
123
0
6
21
42
25
17
-1
-1
module Main where import Lexical import Scanner import Data.List import Data.Maybe import Data.Char(readLitChar) import Text.ParserCombinators.ReadP(eof, many, ReadP, readS_to_P, readP_to_S) import System.Directory strParser :: ReadP String strParser = do str <- many (readS_to_P readLitChar) eof return str trans :: String -> String trans = fst . head . (readP_to_S strParser) ----------------------------------------------------------------------------------------------------------------------------- -------------------------------------- Helpers ------------------------------------------------------------------------------ testTokens :: IO [(String, String)] testTokens = do f <- readFile "res/token.test" let nl = zip [0..] (lines f) return (zip [trans t | (n, t) <- nl, mod n 2 == 0] [t | (n, t) <- nl, mod n 2 == 1]) testFiles :: IO [(String, String)] testFiles = do f <- getDirectoryContents "../assignment_testcases/a1" let files = ["../assignment_testcases/a1/" ++ file | file <- f, file /= ".", file /= ".."] contents <- mapM readFile files return (zip contents files) testEFiles :: IO [(String, String)] testEFiles = do f <- getDirectoryContents "../assignment_testcases/a1" let files = ["../assignment_testcases/a1/" ++ file | file <- f, file /= ".", file /= "..", take 2 file == "Je"] contents <- mapM readFile files return (zip contents files) testVFiles :: IO [(String, String)] testVFiles = do f <- getDirectoryContents "../assignment_testcases/a1" let files = ["../assignment_testcases/a1/" ++ file | file <- f, file /= ".", file /= "..", take 2 file /= "Je"] contents <- mapM readFile files return (zip contents files) testSingleFile :: IO (String, String) testSingleFile = do --let file = "../assignment_testcases/a1/J1_1_Cast_MultipleCastOfSameValue_1.java" let file = "../assignment_testcases/a1/Je_1_Escapes_1DigitOctal_1.java" content <- readFile file return (content, file) printList :: Show a => [a] -> IO() printList [] = return () printList (x:ls) = do putStrLn (show x) printList ls ----------------------------------------------------------------------------------------------------------------------------- main :: IO() main = do --pairs <- testTokens --efiles <- testEFiles --vfiles <- testVFiles --fileResults <- mapM (scannerRunner 0 0) vfiles --let res = map (\items -> filter (\(tk, fn) -> elem (tokenType tk) [FAILURE]) items) fileResults --putStrLn (show res) singlefile <- testSingleFile fileResults <- (scannerRunner 0 0) singlefile let res = map (\(tk, tkinfo) -> (tk, ln tkinfo, col tkinfo)) fileResults putStrLn (foldl (\acc t -> acc ++ (show t) ++ "\n") "" res) --let res = map (\items -> filter (\(tk, fn) -> elem (tokenType tk) [FAILURE]) items) fileResults --printList (zip (map snd singlefile) res) --fileResults <- mapM (scannerRunner 0 0) efiles --let res = map (\items -> filter (\(tk, fn) -> elem (tokenType tk) [FAILURE]) items) fileResults --printList (zip (map snd efiles) res) --lexerRunner pairs --putStrLn (show pairs)
yangsiwei880813/CS644
src/SMain.hs
gpl-2.0
3,157
0
15
573
838
430
408
54
1
module Data.Char.WCWidth.Extended ( module Data.Char.WCWidth , wcstrwidth ) where import Data.Char.WCWidth wcstrwidth :: String -> Int wcstrwidth = sum . map wcwidth
jaspervdj/patat
lib/Data/Char/WCWidth/Extended.hs
gpl-2.0
180
0
6
36
47
29
18
6
1
{-# LANGUAGE CPP, ScopedTypeVariables, OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Utils.GUIUtils -- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GNU-GPL -- -- Maintainer : <maintainer at leksah.org> -- Stability : provisional -- Portability : portable -- -- | -- ------------------------------------------------------------------------------- module IDE.Utils.GUIUtils ( chooseFile , chooseDir , chooseSaveFile , openBrowser , showDialog , showErrorDialog , showDialogOptions , showInputDialog , getFullScreenState , setFullScreenState , getDarkState , setDarkState , getBackgroundBuildToggled , setBackgroundBuildToggled , getRunUnitTests , setRunUnitTests , getMakeModeToggled , setMakeModeToggled , getDebugToggled , setDebugToggled , getRecentFiles , getRecentWorkspaces , getVCS , stockIdFromType , mapControlCommand , treeViewToggleRow , treeViewContextMenu , treeViewContextMenu' , treeStoreGetForest , __ , fontDescription ) where import Graphics.UI.Gtk import IDE.Utils.Tool (runProcess) import Data.Maybe (listToMaybe, fromMaybe, catMaybes, fromJust, isJust) import Control.Monad (void, when, unless) import IDE.Core.State --import Graphics.UI.Gtk.Selectors.FileChooser -- (FileChooserAction(..)) --import Graphics.UI.Gtk.General.Structs -- (ResponseId(..)) import Control.Monad.IO.Class (liftIO) import Control.Exception as E import Data.Text (Text) import Data.Monoid ((<>)) import qualified Data.Text as T (unpack #ifdef LOCALIZATION , pack #endif ) import Control.Applicative ((<$>)) import Data.List (intercalate) import Data.Foldable (forM_) import Data.Tree (Tree(..), Forest) #ifdef LOCALIZATION import Text.I18N.GetText import System.IO.Unsafe (unsafePerformIO) #endif chooseDir :: Window -> Text -> Maybe FilePath -> IO (Maybe FilePath) chooseDir window prompt mbFolder = do dialog <- fileChooserDialogNew (Just prompt) (Just window) FileChooserActionSelectFolder [("gtk-cancel" ,ResponseCancel) ,("gtk-open" ,ResponseAccept)] when (isJust mbFolder) . void $ fileChooserSetCurrentFolder dialog (fromJust mbFolder) widgetShow dialog response <- dialogRun dialog case response of ResponseAccept -> do fn <- fileChooserGetFilename dialog widgetDestroy dialog return fn ResponseCancel -> do widgetDestroy dialog return Nothing ResponseDeleteEvent -> do widgetDestroy dialog return Nothing _ -> return Nothing -- | Launch a "choose file" dialog chooseFile :: Window -> Text -- ^ Window title -> Maybe FilePath -- ^ Start location -> [(String, [String])] -- ^ File filters, e.g. [("Music Files", ["*.mp3", "*.wav"])] -> IO (Maybe FilePath) chooseFile window prompt mbFolder filters = do dialog <- fileChooserDialogNew (Just prompt) (Just window) FileChooserActionOpen [("gtk-cancel" ,ResponseCancel) ,("gtk-open" ,ResponseAccept)] forM_ mbFolder $ \folder -> void (fileChooserSetCurrentFolder dialog folder) forM_ filters (addFilter dialog) widgetShow dialog response <- dialogRun dialog case response of ResponseAccept -> do fn <- fileChooserGetFilename dialog widgetDestroy dialog return fn ResponseCancel -> do widgetDestroy dialog return Nothing ResponseDeleteEvent -> do widgetDestroy dialog return Nothing _ -> return Nothing where addFilter dialog (description, exts) = do ff <- fileFilterNew fileFilterSetName ff description forM_ exts (fileFilterAddPattern ff) fileChooserAddFilter dialog ff chooseSaveFile :: Window -> Text -> Maybe FilePath -> IO (Maybe FilePath) chooseSaveFile window prompt mbFolder = do dialog <- fileChooserDialogNew (Just prompt) (Just window) FileChooserActionSave [("gtk-cancel", ResponseCancel) ,("gtk-save", ResponseAccept)] when (isJust mbFolder) $ void (fileChooserSetCurrentFolder dialog (fromJust mbFolder)) widgetShow dialog res <- dialogRun dialog case res of ResponseAccept -> do mbFileName <- fileChooserGetFilename dialog widgetDestroy dialog return mbFileName _ -> do widgetDestroy dialog return Nothing openBrowser :: Text -> IDEAction openBrowser url = do prefs' <- readIDE prefs liftIO (E.catch (do runProcess (T.unpack $ browser prefs') [T.unpack url] Nothing Nothing Nothing Nothing Nothing return ()) (\ (_ :: SomeException) -> sysMessage Normal ("Can't find browser executable " <> browser prefs'))) return () -- | Show a text dialog with an Ok button and a specific messagetype showDialog :: Text -> MessageType -> IO () showDialog msg msgType = do dialog <- messageDialogNew Nothing [] msgType ButtonsOk msg _ <- dialogRun dialog widgetDestroy dialog return () -- | Show an error dialog with an Ok button showErrorDialog :: Text -> IO () showErrorDialog msg = showDialog msg MessageError -- | Show a dialog with custom buttons and callbacks showDialogOptions :: Text -- ^ the message -> MessageType -- ^ type of dialog -> [(Text, IO ())] -- ^ button text and corresponding actions -> Maybe Int -- ^ index of button that has default focus (0-based) -> IO () showDialogOptions msg msgType buttons mbIndex = do dialog <- messageDialogNew Nothing [] msgType ButtonsNone msg forM_ (zip [0..] buttons) $ \(n,(text, _)) -> do dialogAddButton dialog text (ResponseUser n) dialogSetDefaultResponse dialog (ResponseUser (fromMaybe 0 mbIndex)) set dialog [ windowWindowPosition := WinPosCenterOnParent ] res <- dialogRun dialog widgetHide dialog case res of ResponseUser n | n >= 0 && n < length buttons -> map snd buttons !! n _ -> return () -- | Show a simple dialog that asks the user for some text showInputDialog :: Text -- ^ The message text -> Text -- ^ The default value -> IO (Maybe Text) showInputDialog msg def = do dialog <- dialogNew -- Nothing [] MessageQuestion ButtonsOkCancel msg vbox <- castToBox <$> dialogGetContentArea dialog label <- labelNew (Just msg) entry <- entryNew set entry [entryText := def] boxPackStart vbox label PackNatural 0 boxPackStart vbox entry PackNatural 0 widgetShowAll vbox -- Can't use messageDialog because of https://github.com/gtk2hs/gtk2hs/issues/114 dialogAddButton dialog ("Cancel" :: Text) ResponseCancel dialogAddButton dialog ("Ok" :: Text) ResponseOk dialogSetDefaultResponse dialog ResponseOk res <- dialogRun dialog widgetHide dialog case res of ResponseOk -> do text <- get entry entryText widgetDestroy dialog return (Just text) _ -> widgetDestroy dialog >> return Nothing -- get widget elements (menu & toolbar) getFullScreenState :: PaneMonad alpha => alpha Bool getFullScreenState = do ui <- getUIAction "ui/menubar/_View/_Full Screen" castToToggleAction liftIO $toggleActionGetActive ui setFullScreenState :: PaneMonad alpha => Bool -> alpha () setFullScreenState b = do ui <- getUIAction "ui/menubar/_View/_Full Screen" castToToggleAction liftIO $toggleActionSetActive ui b getDarkState :: PaneMonad alpha => alpha Bool getDarkState = do ui <- getUIAction "ui/menubar/_View/_Use Dark Interface" castToToggleAction liftIO $toggleActionGetActive ui setDarkState :: PaneMonad alpha => Bool -> alpha () setDarkState b = do ui <- getUIAction "ui/menubar/_View/_Use Dark Interface" castToToggleAction liftIO $toggleActionSetActive ui b getMenuItem :: Text -> IDEM MenuItem getMenuItem path = do uiManager' <- getUiManager mbWidget <- liftIO $ uiManagerGetWidget uiManager' path case mbWidget of Nothing -> throwIDE ("State.hs>>getMenuItem: Can't find ui path " <> path) Just widget -> return (castToMenuItem widget) getBackgroundBuildToggled :: PaneMonad alpha => alpha Bool getBackgroundBuildToggled = do ui <- getUIAction "ui/toolbar/BuildToolItems/BackgroundBuild" castToToggleAction liftIO $ toggleActionGetActive ui setBackgroundBuildToggled :: PaneMonad alpha => Bool -> alpha () setBackgroundBuildToggled b = do ui <- getUIAction "ui/toolbar/BuildToolItems/BackgroundBuild" castToToggleAction liftIO $ toggleActionSetActive ui b getRunUnitTests :: PaneMonad alpha => alpha Bool getRunUnitTests = do ui <- getUIAction "ui/toolbar/BuildToolItems/RunUnitTests" castToToggleAction liftIO $ toggleActionGetActive ui setRunUnitTests :: PaneMonad alpha => Bool -> alpha () setRunUnitTests b = do ui <- getUIAction "ui/toolbar/BuildToolItems/RunUnitTests" castToToggleAction liftIO $ toggleActionSetActive ui b getMakeModeToggled :: PaneMonad alpha => alpha Bool getMakeModeToggled = do ui <- getUIAction "ui/toolbar/BuildToolItems/MakeMode" castToToggleAction liftIO $ toggleActionGetActive ui setMakeModeToggled :: PaneMonad alpha => Bool -> alpha () setMakeModeToggled b = do ui <- getUIAction "ui/toolbar/BuildToolItems/MakeMode" castToToggleAction liftIO $ toggleActionSetActive ui b getDebugToggled :: PaneMonad alpha => alpha Bool getDebugToggled = do ui <- getUIAction "ui/toolbar/BuildToolItems/Debug" castToToggleAction liftIO $ toggleActionGetActive ui setDebugToggled :: PaneMonad alpha => Bool -> alpha () setDebugToggled b = do ui <- getUIAction "ui/toolbar/BuildToolItems/Debug" castToToggleAction liftIO $ toggleActionSetActive ui b getRecentFiles , getRecentWorkspaces, getVCS :: IDEM MenuItem getRecentFiles = getMenuItem "ui/menubar/_File/Recent Files" getRecentWorkspaces = getMenuItem "ui/menubar/_File/Recent Workspaces" getVCS = getMenuItem "ui/menubar/Version Con_trol" --this could fail, try returning Menu if it does -- (toolbar) stockIdFromType :: DescrType -> StockId stockIdFromType Variable = "ide_function" stockIdFromType Newtype = "ide_newtype" stockIdFromType Type = "ide_type" stockIdFromType Data = "ide_data" stockIdFromType Class = "ide_class" stockIdFromType Instance = "ide_instance" stockIdFromType Constructor = "ide_konstructor" stockIdFromType Field = "ide_slot" stockIdFromType Method = "ide_method" stockIdFromType PatternSynonym = "ide_konstructor" stockIdFromType _ = "ide_other" treeStoreGetForest :: TreeStore a -> IO (Forest a) treeStoreGetForest store = subForest <$> (treeStoreGetTree store []) -- | Toggles a row in a `TreeView` treeViewToggleRow treeView path = do expanded <- treeViewRowExpanded treeView path if expanded then treeViewCollapseRow treeView path else treeViewExpandRow treeView path False -- maps control key for Macos #if defined(darwin_HOST_OS) mapControlCommand Alt = Control #endif mapControlCommand a = a -- | Sets the context menu for a treeView widget treeViewContextMenu' :: TreeViewClass treeView => treeView -- ^ The view -> TreeStore a -- ^ The model -> (a -> TreePath -> TreeStore a -> IDEM [[(Text, IDEAction)]]) -- ^ Produces the menu items for the selected values when right clicking -- The lists are seperated by a seperator -> IDEM (ConnectId treeView, ConnectId treeView) treeViewContextMenu' view store itemsFor = reifyIDE $ \ideRef -> do cid1 <- view `on` popupMenuSignal $ do showMenu Nothing ideRef cid2 <- view `on` buttonPressEvent $ do button <- eventButton click <- eventClick timestamp <- eventTime (x, y) <- eventCoordinates case (button, click) of (RightButton, SingleClick) -> liftIO $ do sel <- treeViewGetSelection view selCount <- treeSelectionCountSelectedRows sel when (selCount <= 1) $ do pathInfo <- treeViewGetPathAtPos view (floor x, floor y) case pathInfo of Just (path, _, _) -> do treeSelectionUnselectAll sel treeSelectionSelectPath sel path _ -> return () showMenu (Just (button, timestamp)) ideRef _ -> return False return (cid1, cid2) where showMenu buttonEventDetails ideRef = do selPaths <- treeViewGetSelection view >>= treeSelectionGetSelectedRows selValues <- mapM (treeStoreGetValue store) selPaths theMenu <- menuNew menuAttachToWidget theMenu view forM_ (listToMaybe $ zip selValues selPaths) $ \(val, path) -> do itemsPerSection <- flip reflectIDE ideRef $ itemsFor val path store menuItemsPerSection <- mapM (mapM (liftIO . menuItemNewWithLabel . fst)) itemsPerSection forM_ (zip itemsPerSection menuItemsPerSection) $ \(section, itemsSection) -> do forM_ (zip section itemsSection) $ \((_, onActivated), m) -> do m `on` menuItemActivated $ reflectIDE onActivated ideRef unless (null itemsPerSection) $ do itemsAndSeparators <- sequence $ intercalate [fmap castToMenuItem separatorMenuItemNew] (map (map (return . castToMenuItem)) menuItemsPerSection) mapM_ (menuShellAppend theMenu) itemsAndSeparators menuPopup theMenu buttonEventDetails widgetShowAll theMenu return True treeViewContextMenu :: TreeViewClass treeView => treeView -> (Menu -> IO ()) -> IO (ConnectId treeView, ConnectId treeView) treeViewContextMenu treeView populateMenu = do cid1 <- treeView `on` popupMenuSignal $ showMenu Nothing cid2 <- treeView `on` buttonPressEvent $ do button <- eventButton click <- eventClick timestamp <- eventTime (x, y) <- eventCoordinates case (button, click) of (RightButton, SingleClick) -> liftIO $ do sel <- treeViewGetSelection treeView selCount <- treeSelectionCountSelectedRows sel when (selCount <= 1) $ do pathInfo <- treeViewGetPathAtPos treeView (floor x, floor y) case pathInfo of Just (path, _, _) -> do treeSelectionUnselectAll sel treeSelectionSelectPath sel path _ -> return () showMenu (Just (button, timestamp)) _ -> return False return (cid1, cid2) where showMenu buttonEventDetails = do theMenu <- menuNew menuAttachToWidget theMenu treeView populateMenu theMenu menuPopup theMenu buttonEventDetails widgetShowAll theMenu return True #ifdef LOCALIZATION -- | For i18n using hgettext __ :: Text -> Text __ = T.pack . unsafePerformIO . getText . T.unpack #else -- | For i18n support. Not included in this build. __ :: Text -> Text __ = id #endif fontDescription :: Maybe Text -> IDEM FontDescription fontDescription mbFontString = liftIO $ case mbFontString of Just str -> fontDescriptionFromString str Nothing -> do f <- fontDescriptionNew fontDescriptionSetFamily f ("Monospace" :: Text) return f
jaccokrijnen/leksah
src/IDE/Utils/GUIUtils.hs
gpl-2.0
16,546
0
27
4,731
3,770
1,842
1,928
351
4
module Commands (parseCommand, handleCommand ) where import Control.Monad.IO.Class (liftIO) import Control.Exception (catch, IOException) import System.IO import Data.Maybe import Data.List import Data.Char import Types import Parser import Eval import Monad import Download import PrettyPrinter data InteractiveCommand = Cmd String String (String -> Command) String data Command = None | Quit | Reload | Download String | Compile String | CompileFile String | Show String | PrintAll | Stop | Delete String | Help commands :: [InteractiveCommand] commands = [ Cmd ":show" "<film list>" Show "Muestra las películas contenidas en la lista.", Cmd ":help" "" (const Help) "Imprime este menú.", Cmd ":all" "" (const PrintAll) "Muestra todas las listas disponibles.", Cmd ":delete" "<film list>" Delete "Borra la lista seleccionada.", Cmd ":load" "<path>" CompileFile "Cargar listas desde un archivo.", Cmd ":reload" "<path>" (const Reload) "Volver a cargar las listas del ultimo archivo.", Cmd ":download" "<film list>@<quality>" Download "Descarga la lista de películas en la calidad seteada.", Cmd ":stop" "" (const Stop) "Detiene todas las descargas iniciadas desde el programa.", Cmd ":quit" "" (const Quit) "Salir del interprete."] -- Parser para los comandos del intérprete. Si la entrada no empieza con un ":", -- se considerará la misma una expresión del lenguaje. parseCommand :: String -> IO Command parseCommand input = if isPrefixOf ":" input then do let (cmd, arg') = break isSpace input arg = dropWhile isSpace arg' validCommand = filter (\ (Cmd c _ _ _) -> isPrefixOf cmd c) commands case validCommand of [] -> do putStrLn ("Comando desconocido: " ++ cmd ++ ". Escriba :help para recibir ayuda.") return None [Cmd _ _ f _] -> return (f arg) _ -> do putStrLn ("Comando ambigüo: " ++ cmd ++ ". Podría ser: " ++ concat (intersperse ", " [ cs | Cmd cs _ _ _ <- validCommand ]) ++ ".") return None else return (Compile input) -- Esta función es la que realiza las acciones pertinentes a cada comando handleCommand :: Command -> StateError () handleCommand comm = case comm of None -> return () Quit -> throw IQuit Help -> liftIO $ putStrLn (printHelp commands) Show l -> do s <- get case lookup l (list s) of Just fl -> liftIO $ putStrLn (show (printfl fl)) Nothing -> liftIO $ putStrLn "Lista no encontrada. Escriba :all para ver las listas disponibles." PrintAll -> do s <- get let allLists = concat $ intersperse ", " (sort (map fst (list s))) if null allLists then liftIO $ putStrLn ("Aún no hay listas definidas.") else liftIO $ putStrLn (allLists) Reload -> do s <- get handleCommand (CompileFile (lfile s)) Delete n -> do s <- get put (s {list = filter (\(x,_) -> n /= x) (list s)}) Compile s -> case runParser s of Right defList -> eval defList Left error -> liftIO $ putStrLn ("Error de parseo: " ++ show error) Download f -> let (n, q') = break (\c -> c == '@') f q = dropWhile (\c -> c == '@') q' in do s <- get case lookup n (list s) of Just fl -> do pids <- liftIO $ download fl q (d_dir s) put (s {dlist = pids}) Nothing -> liftIO $ putStrLn "Lista no encontrada. Escriba :all para ver las listas disponibles." Stop -> do s <- get liftIO $ stopDownload (dlist s) put (s {dlist = []}) CompileFile path -> do f <- liftIO (catch (readFile path) (\e -> do let err = show (e :: IOException) hPutStr stderr ("Error: El archivo " ++ path ++ " no pudo abrirse. \n" ++ err ++ ".\n") return "")) if null f then return () else do s <- get put (s {lfile = path}) handleCommand (Compile f) -- Genera el texto que se mostrará en el comando de ayuda (:help) printHelp :: [InteractiveCommand] -> String printHelp xs = "Lista de comandos: \n\n" ++ "<expresion> Evaluar la expresión.\n" ++ unlines (map (\ (Cmd c arg _ d) -> let fstSpace = replicate (10 - length c) ' ' sndSpace = replicate (35 - length (c ++ fstSpace ++ arg)) ' ' in c ++ fstSpace ++ arg ++ sndSpace ++ d) xs)
g-deluca/yts-dl
app/Commands.hs
gpl-3.0
6,051
0
23
2,850
1,393
697
696
100
16
module Language.SMTLib2.Composite.Data (makeComposite) where import Language.SMTLib2 import Language.SMTLib2.Composite.Class import qualified Language.Haskell.TH as TH import Data.GADT.Compare import Data.GADT.Show import Control.Monad makeComposite :: String -- ^ Name of the composite type -> String -- ^ Name of the reverse type -> Int -- ^ Parameter number -> [(String,[(String,String,TH.TypeQ -> [TH.TypeQ] -> TH.TypeQ)])] -> TH.Q [TH.Dec] makeComposite name rname par' cons = do let name' = TH.mkName name e = TH.mkName "e" par = take par' (fmap (\c -> [c]) ['a'..'z']) i1 <- TH.dataD (TH.cxt []) name' ((fmap (TH.PlainTV . TH.mkName) par)++ [TH.KindedTV e (TH.appK (TH.appK TH.arrowK (TH.conK ''Type)) TH.starK)]) #if MIN_VERSION_template_haskell(2,11,0) Nothing #endif [ TH.recC (TH.mkName con) [ TH.varStrictType (TH.mkName field) (TH.strictType TH.notStrict (TH.appT (tp (TH.conT name') (fmap (TH.varT . TH.mkName) par)) (TH.varT e))) | (field,_,tp) <- fields] | (con,fields) <- cons ] #if MIN_VERSION_template_haskell(2,11,0) (TH.cxt []) #else [] #endif i3 <- TH.dataD (TH.cxt []) (TH.mkName rname) ((fmap (TH.PlainTV . TH.mkName) par)++ [TH.PlainTV $ TH.mkName "tp"]) #if MIN_VERSION_template_haskell(2,11,0) Nothing #endif [ TH.normalC (TH.mkName rev) [TH.strictType TH.notStrict (TH.appT (TH.appT (TH.conT ''RevComp) (tp (TH.conT name') (fmap (TH.varT . TH.mkName) par))) (TH.varT $ TH.mkName "tp"))] | (_,fields) <- cons , (_,rev,tp) <- fields ] #if MIN_VERSION_template_haskell(2,11,0) (TH.cxt []) #else [] #endif let lpar = length par revs = concat $ fmap (\(_,fields) -> fmap (\(_,rev,_) -> TH.mkName rev) fields ) cons i4 <- deriveOrd lpar (TH.mkName name) i5 <- deriveRevShow lpar (TH.mkName rname) revs i6 <- deriveRevGEq lpar (TH.mkName rname) revs i7 <- deriveRevGCompare lpar (TH.mkName rname) revs i8 <- deriveComposite lpar (TH.mkName name) (TH.mkName rname) [ (TH.mkName con, [ (TH.mkName field,TH.mkName rev) | (field,rev,tp) <- fields ]) | (con,fields) <- cons ] return $ [i1,i3]++i4++i5++i6++i7++i8 deriveComposite :: Int -> TH.Name -> TH.Name -> [(TH.Name,[(TH.Name,TH.Name)])] -> TH.Q [TH.Dec] deriveComposite numPar name rname cons = do pars <- replicateM numPar (TH.newName "c") let ctx = TH.cxt $ fmap (\par -> (TH.conT ''Composite) `TH.appT` (TH.varT par) ) pars compArgs n = foldr (\par tp -> TH.appT tp (TH.varT par) ) n pars i1 <- TH.instanceD ctx ((TH.conT ''Composite) `TH.appT` (compArgs (TH.conT name))) [TH.tySynInstD ''RevComp (TH.tySynEqn [compArgs (TH.conT name)] (compArgs (TH.conT rname))) ,TH.funD 'foldExprs [ do fName <- TH.newName "f" fieldNames <- mapM (const (TH.newName "arg")) fields nfieldNames <- mapM (const (TH.newName "res")) fields TH.clause [TH.varP fName ,TH.conP con [ TH.varP fieldName | fieldName <- fieldNames ]] (TH.normalB $ TH.doE $ [ TH.bindS (TH.varP new) (TH.appsE [TH.varE 'foldExprs ,TH.appsE [TH.varE '(.) ,TH.varE fName ,TH.conE rev] ,TH.varE old ]) | (old,new,(_,rev)) <- zip3 fieldNames nfieldNames fields ] ++ [ TH.noBindS (TH.appE (TH.varE 'return) (foldl (\cur fieldName -> cur `TH.appE` (TH.varE fieldName) ) (TH.conE con) nfieldNames)) ] ) [] | (con,fields) <- cons ] ,TH.funD 'accessComposite [ do matchName <- TH.newName "x" revName <- TH.newName "rev" TH.clause [TH.conP rev [TH.varP revName] ,TH.conP con ((replicate n TH.wildP)++[TH.varP matchName]++(replicate (length fields - n - 1) TH.wildP))] (TH.normalB $ TH.appsE [TH.varE 'accessComposite ,TH.varE revName ,TH.varE matchName]) [] | (con,fields) <- cons , (n,(field,rev)) <- zip [0..] fields ] ] return [i1] deriveRevGEq :: Int -> TH.Name -> [TH.Name] -> TH.Q [TH.Dec] deriveRevGEq numPar rname rcons = do pars <- replicateM numPar (TH.newName "c") let ctx = TH.cxt $ fmap (\par -> (TH.conT ''Composite) `TH.appT` (TH.varT par) ) pars compArgs n = foldl (\tp par -> TH.appT tp (TH.varT par) ) n pars i <- TH.instanceD ctx ((TH.conT ''GEq) `TH.appT` (compArgs (TH.conT rname))) [TH.funD 'geq $ [ do r1 <- TH.newName "r1" r2 <- TH.newName "r2" TH.clause [TH.conP rev [TH.varP r1] ,TH.conP rev [TH.varP r2]] (TH.normalB $ TH.doE [TH.bindS (TH.conP 'Refl []) (TH.appsE [TH.varE 'geq ,TH.varE r1 ,TH.varE r2]) ,TH.noBindS $ TH.appsE [TH.varE 'return ,TH.conE 'Refl]]) [] | rev <- rcons ] ++ [ TH.clause [TH.wildP,TH.wildP] (TH.normalB $ TH.conE 'Nothing) [] ]] return [i] deriveRevGCompare :: Int -> TH.Name -> [TH.Name] -> TH.Q [TH.Dec] deriveRevGCompare numPar rname rcons = do pars <- replicateM numPar (TH.newName "c") let ctx = TH.cxt $ fmap (\par -> (TH.conT ''Composite) `TH.appT` (TH.varT par) ) pars compArgs n = foldl (\tp par -> TH.appT tp (TH.varT par) ) n pars i <- TH.instanceD ctx ((TH.conT ''GCompare) `TH.appT` (compArgs (TH.conT rname))) [TH.funD 'gcompare $ concat [ [ do r1 <- TH.newName "r1" r2 <- TH.newName "r2" TH.clause [TH.conP rev [TH.varP r1] ,TH.conP rev [TH.varP r2]] (TH.normalB $ TH.caseE (TH.appsE [TH.varE 'gcompare,TH.varE r1,TH.varE r2]) [TH.match (TH.conP 'GEQ []) (TH.normalB $ TH.conE 'GEQ) [] ,TH.match (TH.conP 'GLT []) (TH.normalB $ TH.conE 'GLT) [] ,TH.match (TH.conP 'GGT []) (TH.normalB $ TH.conE 'GGT) []]) [] ,TH.clause [TH.conP rev [TH.wildP] ,TH.wildP] (TH.normalB $ TH.conE 'GLT) [] ,TH.clause [TH.wildP ,TH.conP rev [TH.wildP]] (TH.normalB $ TH.conE 'GGT) []] | rev <- rcons ]] return [i] deriveRevShow :: Int -> TH.Name -> [TH.Name] -> TH.Q [TH.Dec] deriveRevShow numPar rname rcons = do pars <- replicateM numPar (TH.newName "c") tp <- TH.newName "tp" let ctx = TH.cxt $ fmap (\par -> (TH.conT ''Composite) `TH.appT` (TH.varT par) ) pars compArgs n = foldl (\tp par -> TH.appT tp (TH.varT par) ) n pars i1 <- TH.instanceD ctx ((TH.conT ''Show) `TH.appT` (TH.appT (compArgs (TH.conT rname)) (TH.varT tp))) [TH.funD 'showsPrec $ [ do p <- TH.newName "p" r <- TH.newName "r" TH.clause [TH.varP p ,TH.conP rev [TH.varP r]] (TH.normalB $ [| showParen ($(TH.varE p) > 10) (showString $(TH.stringE ((TH.nameBase rev)++" ")) . gshowsPrec 11 $(TH.varE r)) |]) [] | rev <- rcons ]] i2 <- TH.instanceD ctx ((TH.conT ''GShow) `TH.appT` (compArgs (TH.conT rname))) [TH.funD 'gshowsPrec [TH.clause [] (TH.normalB $ TH.varE 'showsPrec) []]] return [i1,i2] deriveOrd :: Int -> TH.Name -> TH.Q [TH.Dec] deriveOrd numPar dname = do pars <- replicateM numPar (TH.newName "c") e <- TH.newName "e" let ctxEq = TH.cxt $ fmap (\par -> (TH.conT ''Eq) `TH.appT` ((TH.varT par) `TH.appT` (TH.varT e)) ) pars ctxOrd = TH.cxt $ fmap (\par -> (TH.conT ''Ord) `TH.appT` ((TH.varT par) `TH.appT` (TH.varT e)) ) pars compArgs n = foldl (\tp par -> TH.appT tp (TH.varT par) ) n (pars ++ [e]) i1 <- TH.standaloneDerivD ctxEq ((TH.conT ''Eq) `TH.appT` (compArgs (TH.conT dname))) i2 <- TH.standaloneDerivD ctxOrd ((TH.conT ''Ord) `TH.appT` (compArgs (TH.conT dname))) return [i1,i2]
hguenther/smtlib2
extras/composite/Language/SMTLib2/Composite/Data.hs
gpl-3.0
8,770
0
28
3,015
3,685
1,899
1,786
-1
-1
module Sites.TryingHuman ( tryingHuman ) where import Network.HTTP.Types.URI (decodePathSegments) import Data.Maybe (catMaybes) import qualified Data.List as DL import qualified Data.Text as T import qualified Data.ByteString.UTF8 as US import qualified Data.ByteString.Lazy as BL import Control.Monad import Control.Monad.IO.Class import Pipes (Pipe) -- Local imports import Types import Parser.Words import Sites.Util import Interpreter -- Tagsoup import Text.HTML.TagSoup hiding (parseTags, renderTags) import Text.HTML.TagSoup.Fast -- -- TryingHuman -- rootUrl = "http://tryinghuman.com/" tryingHuman = Comic { comicName = "Trying Human" , seedPage = rootUrl ++ "archive.php" , seedCache = Always , pageParse = tryingHumanPageParse , cookies = [] } tryingHumanPageParse :: Pipe ReplyType FetchType IO () tryingHumanPageParse = runWebFetchT $ do html <- fetchSeedpage let page = parseTagsT $ BL.toStrict html let subset = ( filterAny [ (\a -> isTagText a && T.isPrefixOf (T.pack "VOLUME") (fromTagText a)) , (\a -> isTagText a && T.isPrefixOf (T.pack "Chapter") (fromTagText a)) , (\a -> isTagText a && T.isPrefixOf (T.pack "Prologue") (fromTagText a)) , (\a -> a ~== "<a>" && T.isPrefixOf (T.pack rootUrl) (fromAttrib (T.pack "href") a)) ] $ ( takeWhile (~/= "<select>") $ dropWhile (~/= "<div id=maincontent>") page) ++ ( dropWhile (~/= "</select>") $ dropWhile (~/= "<div id=maincontent>") page)) forM_ (buildTreeUrl subset) (\(url, pg, ct) -> do html' <- fetchWebpage [(url, Always)] let page' = parseTagsT $ BL.toStrict html' let img = ( (fromAttrib $ T.pack "src") $ head $ filter (~== "<img id=comic>") page') (liftIO . print) img debug "" fetchImage (rootUrl ++ T.unpack img) (toPage ct pg img) ) toPage :: ComicTag -> Integer -> T.Text -> ComicTag toPage ct page url = ct{ctFileName = Just $ T.justifyRight 8 '0' $ T.pack (show page ++ (T.unpack $ T.dropWhile (/= '.') $ last $ decodePathSegments $ US.fromString $ T.unpack url))} buildTreeUrl :: [Tag T.Text] -> [(String, Integer, ComicTag)] buildTreeUrl xs = catMaybes $ snd $ DL.mapAccumL accum (T.pack "", T.pack "", 1) xs where accum (vol, chp, pg) x | isTagText x && T.isPrefixOf (T.pack "VOLUME") (fromTagText x) = ((fromTagText x, chp, pg), Nothing) | isTagText x && T.isPrefixOf (T.pack "Chapter") (fromTagText x) = ((vol, fromTagText x, pg), Nothing) | isTagText x && T.isPrefixOf (T.pack "Prologue") (fromTagText x) = ((vol, fromTagText x, pg), Nothing) | otherwise = ((vol, chp, pg + 1), Just (toCT vol chp pg $ fromAttrib (T.pack "href") x)) toCT :: T.Text -> T.Text -> Integer -> T.Text -> (String, Integer, ComicTag) toCT vol chp pg url = ((T.unpack url), pg, (ComicTag (T.pack "Trying Human") Nothing (Just $ UnitTag [StandAlone $ Digit (parseVol vol) Nothing Nothing Nothing] Nothing) (Just $ UnitTag [StandAlone $ Digit (parseChp chp) Nothing Nothing Nothing] Nothing) Nothing)) parseVol :: T.Text -> Integer parseVol t = wordToNumber $ T.unpack $ T.drop (length "VOLUME ") t parseChp :: T.Text -> Integer parseChp t | (t == T.pack "Prologue") = 0 | otherwise = wordToNumber $ T.unpack $ T.drop (length "Chapter ") t
pharaun/hComicFetcher
src/Sites/TryingHuman.hs
gpl-3.0
3,610
0
24
982
1,314
700
614
68
1
{- The Delve Programming Language Copyright 2009 John Morrice Distributed under the terms of the GNU General Public License v3, or ( at your option ) any later version. This file is part of Delve. Delve 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. Delve 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 Delve. If not, see <http://www.gnu.org/licenses/>. -} import VarApp import ResolveLocal import SExp import Compiler ( compile ) import VMCompiler import Embed import VMASTCompiler embedded = do l <- lecore f <- Prelude.readFile "EmbedTest.delve" let VarApp o vcore = compile $ NonVarApp 0 $ from_sexp $ to_sexp f Resolved lcore = compile $ Unresolved vcore EmbedModule w m ec = compile $ EmbeddedHaskell o "EmbedTest" lcore VMAST haskell = compile $ EmbedCore w m ec return haskell lecore = do f <- Prelude.readFile "CoreTest.delve" let VarApp _ vcore = compile $ NonVarApp 0 $ from_sexp $ to_sexp f Resolved lcore = compile $ Unresolved vcore return lcore dcode = do f <- Prelude.readFile "CoreTest.delve" let VarApp uniq vcore = compile $ NonVarApp 0 $ from_sexp $ to_sexp f Resolved lcore = compile $ Unresolved vcore VMCode d = compile $ LocalCore uniq lcore return d
elginer/Delve
src/phase_test.hs
gpl-3.0
1,775
0
13
440
313
142
171
26
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DialogFlow.Projects.Agent.Sessions.Contexts.Patch -- 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) -- -- Updates the specified context. -- -- /See:/ <https://cloud.google.com/dialogflow-enterprise/ Dialogflow API Reference> for @dialogflow.projects.agent.sessions.contexts.patch@. module Network.Google.Resource.DialogFlow.Projects.Agent.Sessions.Contexts.Patch ( -- * REST Resource ProjectsAgentSessionsContextsPatchResource -- * Creating a Request , projectsAgentSessionsContextsPatch , ProjectsAgentSessionsContextsPatch -- * Request Lenses , pascpXgafv , pascpUploadProtocol , pascpUpdateMask , pascpAccessToken , pascpUploadType , pascpPayload , pascpName , pascpCallback ) where import Network.Google.DialogFlow.Types import Network.Google.Prelude -- | A resource alias for @dialogflow.projects.agent.sessions.contexts.patch@ method which the -- 'ProjectsAgentSessionsContextsPatch' request conforms to. type ProjectsAgentSessionsContextsPatchResource = "v2" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" GFieldMask :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] GoogleCloudDialogflowV2Context :> Patch '[JSON] GoogleCloudDialogflowV2Context -- | Updates the specified context. -- -- /See:/ 'projectsAgentSessionsContextsPatch' smart constructor. data ProjectsAgentSessionsContextsPatch = ProjectsAgentSessionsContextsPatch' { _pascpXgafv :: !(Maybe Xgafv) , _pascpUploadProtocol :: !(Maybe Text) , _pascpUpdateMask :: !(Maybe GFieldMask) , _pascpAccessToken :: !(Maybe Text) , _pascpUploadType :: !(Maybe Text) , _pascpPayload :: !GoogleCloudDialogflowV2Context , _pascpName :: !Text , _pascpCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsAgentSessionsContextsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pascpXgafv' -- -- * 'pascpUploadProtocol' -- -- * 'pascpUpdateMask' -- -- * 'pascpAccessToken' -- -- * 'pascpUploadType' -- -- * 'pascpPayload' -- -- * 'pascpName' -- -- * 'pascpCallback' projectsAgentSessionsContextsPatch :: GoogleCloudDialogflowV2Context -- ^ 'pascpPayload' -> Text -- ^ 'pascpName' -> ProjectsAgentSessionsContextsPatch projectsAgentSessionsContextsPatch pPascpPayload_ pPascpName_ = ProjectsAgentSessionsContextsPatch' { _pascpXgafv = Nothing , _pascpUploadProtocol = Nothing , _pascpUpdateMask = Nothing , _pascpAccessToken = Nothing , _pascpUploadType = Nothing , _pascpPayload = pPascpPayload_ , _pascpName = pPascpName_ , _pascpCallback = Nothing } -- | V1 error format. pascpXgafv :: Lens' ProjectsAgentSessionsContextsPatch (Maybe Xgafv) pascpXgafv = lens _pascpXgafv (\ s a -> s{_pascpXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pascpUploadProtocol :: Lens' ProjectsAgentSessionsContextsPatch (Maybe Text) pascpUploadProtocol = lens _pascpUploadProtocol (\ s a -> s{_pascpUploadProtocol = a}) -- | Optional. The mask to control which fields get updated. pascpUpdateMask :: Lens' ProjectsAgentSessionsContextsPatch (Maybe GFieldMask) pascpUpdateMask = lens _pascpUpdateMask (\ s a -> s{_pascpUpdateMask = a}) -- | OAuth access token. pascpAccessToken :: Lens' ProjectsAgentSessionsContextsPatch (Maybe Text) pascpAccessToken = lens _pascpAccessToken (\ s a -> s{_pascpAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pascpUploadType :: Lens' ProjectsAgentSessionsContextsPatch (Maybe Text) pascpUploadType = lens _pascpUploadType (\ s a -> s{_pascpUploadType = a}) -- | Multipart request metadata. pascpPayload :: Lens' ProjectsAgentSessionsContextsPatch GoogleCloudDialogflowV2Context pascpPayload = lens _pascpPayload (\ s a -> s{_pascpPayload = a}) -- | Required. The unique identifier of the context. Format: -- \`projects\/\/agent\/sessions\/\/contexts\/\`. The \`Context ID\` is -- always converted to lowercase, may only contain characters in -- [a-zA-Z0-9_-%] and may be at most 250 bytes long. pascpName :: Lens' ProjectsAgentSessionsContextsPatch Text pascpName = lens _pascpName (\ s a -> s{_pascpName = a}) -- | JSONP pascpCallback :: Lens' ProjectsAgentSessionsContextsPatch (Maybe Text) pascpCallback = lens _pascpCallback (\ s a -> s{_pascpCallback = a}) instance GoogleRequest ProjectsAgentSessionsContextsPatch where type Rs ProjectsAgentSessionsContextsPatch = GoogleCloudDialogflowV2Context type Scopes ProjectsAgentSessionsContextsPatch = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/dialogflow"] requestClient ProjectsAgentSessionsContextsPatch'{..} = go _pascpName _pascpXgafv _pascpUploadProtocol _pascpUpdateMask _pascpAccessToken _pascpUploadType _pascpCallback (Just AltJSON) _pascpPayload dialogFlowService where go = buildClient (Proxy :: Proxy ProjectsAgentSessionsContextsPatchResource) mempty
brendanhay/gogol
gogol-dialogflow/gen/Network/Google/Resource/DialogFlow/Projects/Agent/Sessions/Contexts/Patch.hs
mpl-2.0
6,425
0
17
1,425
863
504
359
130
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Jobs.Projects.Jobs.BatchDelete -- 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 a list of Jobs by filter. -- -- /See:/ <https://cloud.google.com/talent-solution/job-search/docs/ Cloud Talent Solution API Reference> for @jobs.projects.jobs.batchDelete@. module Network.Google.Resource.Jobs.Projects.Jobs.BatchDelete ( -- * REST Resource ProjectsJobsBatchDeleteResource -- * Creating a Request , projectsJobsBatchDelete , ProjectsJobsBatchDelete -- * Request Lenses , pjbdParent , pjbdXgafv , pjbdUploadProtocol , pjbdAccessToken , pjbdUploadType , pjbdPayload , pjbdCallback ) where import Network.Google.Jobs.Types import Network.Google.Prelude -- | A resource alias for @jobs.projects.jobs.batchDelete@ method which the -- 'ProjectsJobsBatchDelete' request conforms to. type ProjectsJobsBatchDeleteResource = "v3p1beta1" :> Capture "parent" Text :> "jobs:batchDelete" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] BatchDeleteJobsRequest :> Post '[JSON] Empty -- | Deletes a list of Jobs by filter. -- -- /See:/ 'projectsJobsBatchDelete' smart constructor. data ProjectsJobsBatchDelete = ProjectsJobsBatchDelete' { _pjbdParent :: !Text , _pjbdXgafv :: !(Maybe Xgafv) , _pjbdUploadProtocol :: !(Maybe Text) , _pjbdAccessToken :: !(Maybe Text) , _pjbdUploadType :: !(Maybe Text) , _pjbdPayload :: !BatchDeleteJobsRequest , _pjbdCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsJobsBatchDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pjbdParent' -- -- * 'pjbdXgafv' -- -- * 'pjbdUploadProtocol' -- -- * 'pjbdAccessToken' -- -- * 'pjbdUploadType' -- -- * 'pjbdPayload' -- -- * 'pjbdCallback' projectsJobsBatchDelete :: Text -- ^ 'pjbdParent' -> BatchDeleteJobsRequest -- ^ 'pjbdPayload' -> ProjectsJobsBatchDelete projectsJobsBatchDelete pPjbdParent_ pPjbdPayload_ = ProjectsJobsBatchDelete' { _pjbdParent = pPjbdParent_ , _pjbdXgafv = Nothing , _pjbdUploadProtocol = Nothing , _pjbdAccessToken = Nothing , _pjbdUploadType = Nothing , _pjbdPayload = pPjbdPayload_ , _pjbdCallback = Nothing } -- | Required. The resource name of the project under which the job is -- created. The format is \"projects\/{project_id}\", for example, -- \"projects\/api-test-project\". pjbdParent :: Lens' ProjectsJobsBatchDelete Text pjbdParent = lens _pjbdParent (\ s a -> s{_pjbdParent = a}) -- | V1 error format. pjbdXgafv :: Lens' ProjectsJobsBatchDelete (Maybe Xgafv) pjbdXgafv = lens _pjbdXgafv (\ s a -> s{_pjbdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pjbdUploadProtocol :: Lens' ProjectsJobsBatchDelete (Maybe Text) pjbdUploadProtocol = lens _pjbdUploadProtocol (\ s a -> s{_pjbdUploadProtocol = a}) -- | OAuth access token. pjbdAccessToken :: Lens' ProjectsJobsBatchDelete (Maybe Text) pjbdAccessToken = lens _pjbdAccessToken (\ s a -> s{_pjbdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pjbdUploadType :: Lens' ProjectsJobsBatchDelete (Maybe Text) pjbdUploadType = lens _pjbdUploadType (\ s a -> s{_pjbdUploadType = a}) -- | Multipart request metadata. pjbdPayload :: Lens' ProjectsJobsBatchDelete BatchDeleteJobsRequest pjbdPayload = lens _pjbdPayload (\ s a -> s{_pjbdPayload = a}) -- | JSONP pjbdCallback :: Lens' ProjectsJobsBatchDelete (Maybe Text) pjbdCallback = lens _pjbdCallback (\ s a -> s{_pjbdCallback = a}) instance GoogleRequest ProjectsJobsBatchDelete where type Rs ProjectsJobsBatchDelete = Empty type Scopes ProjectsJobsBatchDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/jobs"] requestClient ProjectsJobsBatchDelete'{..} = go _pjbdParent _pjbdXgafv _pjbdUploadProtocol _pjbdAccessToken _pjbdUploadType _pjbdCallback (Just AltJSON) _pjbdPayload jobsService where go = buildClient (Proxy :: Proxy ProjectsJobsBatchDeleteResource) mempty
brendanhay/gogol
gogol-jobs/gen/Network/Google/Resource/Jobs/Projects/Jobs/BatchDelete.hs
mpl-2.0
5,418
0
17
1,270
784
458
326
116
1
module Chain where import UU.Parsing import Data.Char main = do let tokens = "s*s*C" resultado <- parseIO pSE tokens putStrLn . show $ resultado instance Symbol Char -- Sintaxis concreta data Class = Class deriving Show {- pRE :: Parser Char RE pRE = pChainl pOp pClass pSE :: Parser Char RE pSE = SE <$ pSym 's' pOp :: Parser Char (RE -> Class -> RE) pOp = (:*:) <$ pSym '*' pClass :: Parser Char Class pClass = Class <$ pSym 'C' data RE = SE | RE :*: Class deriving Show -} pRE = pChainl pOp pSE -- pClass pSE :: Parser Char RE pSE = SE <$ pSym 's' -- pOp :: Parser Char (RE -> Class -> RE) pOp = (:*:) <$ pSym '*' pClass :: Parser Char Class pClass = Class <$ pSym 'C' data RE = SE | RE :*: RE deriving Show
andreagenso/java2scala
src/J2s/Chain.hs
apache-2.0
855
0
9
294
157
84
73
18
1
{-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE ScopedTypeVariables #-} -- | -- Module : Data.Map.Justified -- Copyright : (c) Matt Noonan 2017 -- License : BSD-style -- Maintainer : [email protected] -- Portability : portable -- -- = Description -- -- Have you ever /known/ that a key could be found in a certain map? Were you tempted to -- reach for @'fromJust'@ or @'error'@ to handle the "impossible" case, when you knew that -- @'lookup'@ should give @'Just' v@? (and did shifting requirements ever make the impossible -- become possible after all?) -- -- "Data.Map.Justified" provides a zero-cost @newtype@ wrapper around "Data.Map"'s @'Data.Map.Map'@ that enables you -- to separate the /proof that a key is present/ from the /operations using the key/. Once -- you prove that a key is present, you can use it @Maybe@-free in any number of other -- operations -- sometimes even operations on other maps! -- -- None of the functions in this module can cause a run-time error, and very few -- of the operations return a @'Maybe'@ value. -- -- See the "Data.Map.Justified.Tutorial" module for usage examples. -- -- === Example -- @ -- withMap test_table $ \\table -> do -- -- case member 1 table of -- -- Nothing -> putStrLn "Sorry, I couldn\'t prove that the key is present." -- -- Just key -> do -- -- -- We have proven that the key is present, and can now use it Maybe-free... -- putStrLn ("Found key: " ++ show key) -- putStrLn ("Value for key: " ++ lookup key table) -- -- -- ...even in certain other maps! -- let table\' = reinsert key "howdy" table -- putStrLn ("Value for key in updated map: " ++ lookup key table\') -- @ -- Output: -- -- @ -- Found key: Key 1 -- Value for key: hello -- Value for key in updated map: howdy -- @ -- -- == Motivation: "Data.Map" and @'Maybe'@ values -- -- Suppose you have a key-value mapping using "Data.Map"'s type @'Data.Map.Map' k v@. Anybody making -- use of @'Data.Map.Map' k v@ to look up or modify a value must take into account the possibility -- that the given key is not present. -- -- In "Data.Map", there are two strategies for dealing with absent keys: -- -- 1. Cause a runtime error (e.g. "Data.Map"'s @'Data.Map.!'@ when the key is absent) -- -- 2. Return a @'Maybe'@ value (e.g. "Data.Map"'s @'Data.Map.lookup'@) -- -- The first option introduces partial functions, so is not very palatable. But what is -- wrong with the second option? -- -- To understand the problem with returning a @'Maybe'@ value, let's ask what returning -- @Maybe v@ from @'Data.Map.lookup' :: k -> Map k v -> Maybe v@ really does for us. By returning -- a @Maybe v@ value, @lookup key table@ is saying "Your program must account -- for the possibility that @key@ cannot be found in @table@. I will ensure that you -- account for this possibility by forcing you to handle the @'Nothing'@ case." -- In effect, "Data.Map" is requiring the user to prove they have handled the -- possibility that a key is absent whenever they use the @'Data.Map.lookup'@ function. -- -- == Laziness (the bad kind) -- -- Every programmer has probably had the experience of knowing, somehow, that a certain -- key is going to be present in a map. In this case, the @'Maybe' v@ feels like a burden: -- I already /know/ that this key is in the map, why should I have to handle the @'Nothing'@ case? -- -- In this situation, it is tempting to reach for the partial function @'Data.Maybe.fromJust'@, -- or a pattern match like @'Nothing' -> 'error' "The impossible happened!"@. But as parts of -- the program are changed over time, you may find the impossible has become possible after -- all (or perhaps you'll see the dreaded and unhelpful @*** Exception: Maybe.fromJust: Nothing@) -- -- It is tempting to reach for partial functions or "impossible" runtime errors here, because -- the programmer has proven that the key is a member of the map in some other way. They -- know that @'Data.Map.lookup'@ should return a @'Just' v@ --- but the /compiler/ doesn't know this! -- -- The idea behind "Data.Map.Justified" is to encode the programmer's knowledge that a key -- is present /within the type system/, where it can be checked at compile-time. Once a key -- is known to be present, @'Data.Map.Justified.lookup'@ will never fail. Your justification -- removes the @'Just'@! -- -- == How it works -- -- Evidence that a key can indeed be found in a map is carried by a phantom type parameter @ph@ -- shared by both the @'Data.Map.Justified.Map'@ and @'Data.Map.Justified.Key'@ types. If you are -- able to get your hands on a value of type @'Key' ph k@, then you must have already proven that -- the key is present in /any/ value of type @'Map' ph k v@. -- -- The @'Key' ph k@ type is simply a @newtype@ wrapper around @k@, but the phantom type @ph@ allows -- @'Key' ph k@ to represent both /a key of type @k@/ __and__ /a proof that the key is present in/ -- /all maps of type @'Map' ph k v@/. -- -- There are several ways to prove that a key belongs to a map, but the simplest is to just use -- "Data.Map.Justified"'s @'Data.Map.Justified.member'@ function. In "Data.Map", @'Data.Map.member'@ -- has the type -- -- @'Data.Map.member' :: 'Ord' k => k -> 'Data.Map.Map' k v -> 'Bool'@ -- -- and reports whether or not the key can be found in the map. In "Data.Map.Justified", -- @'Data.Map.Member'@ has the type -- -- @'member' :: 'Ord' k => k -> 'Map' ph k v -> 'Maybe' ('Key' ph k)@ -- -- Instead of a boolean, @'Data.Map.Justified.member'@ either says "the key is not present" -- (@'Nothing'@), or gives back the same key, /augmented with evidence that they key/ -- /is present/. This key-plus-evidence can then be used to do any number of @'Maybe'@-free -- operations on the map. -- -- "Data.Map.Justified" uses the same rank-2 polymorphism trick used in the @'Control.Monad.ST'@ monad to -- ensure that the @ph@ phantom type can not be extracted; in effect, the proof that a key is -- present can't leak to contexts where the proof would no longer be valid. -- module Data.Map.Justified ( -- * Map and Key types Map , Key , Index , theMap , theKey , theIndex -- * Evaluation , withMap , withSingleton , KeyInfo(..) , MissingReference , withRecMap -- * Gathering evidence , member , keys , lookupMay , lookupLT , lookupLE , lookupGT , lookupGE -- * Safe lookup , lookup , (!) -- * Preserving key sets -- ** Localized updates , adjust , adjustWithKey , reinsert -- ** Mapping values , mapWithKey , traverseWithKey , mapAccum , mapAccumWithKey -- ** Zipping , zip , zipWith , zipWithKey -- * Enlarging key sets -- ** Inserting new keys , inserting , insertingWith -- ** Unions , unioning , unioningWith , unioningWithKey -- * Reducing key sets -- ** Removing keys , deleting , subtracting -- ** Filtering , filtering , filteringWithKey -- ** Intersections , intersecting , intersectingWith , intersectingWithKey -- * Mapping key sets , mappingKeys , mappingKnownKeys , mappingKeysWith , mappingKnownKeysWith -- * Indexing , findIndex , elemAt -- * Utilities , tie ) where import Control.Arrow ((&&&)) import Data.List (partition) import qualified Data.Map as M import Prelude hiding (lookup, zip, zipWith) import Data.Roles import Data.Type.Coercion {-------------------------------------------------------------------- Map and Key types --------------------------------------------------------------------} -- | A "Data.Map" @'Data.Map.Map'@ wrapper that allows direct lookup of keys that -- are known to exist in the map. -- -- Here, "direct lookup" means that once a key has been proven -- to exist in the map, it can be used to extract a value directly -- from the map, rather than requiring a @'Maybe'@ layer. -- -- @'Map'@ allows you to shift the burden of proof that a key exists -- in a map from "prove at every lookup" to "prove once per key". newtype Map ph k v = Map (M.Map k v) deriving (Eq, Ord, Show, Functor, Foldable, Traversable) type role Map nominal nominal representational -- | A key that knows it can be found in certain @'Map'@s. -- -- The evidence that the key can be found in a map is carried by -- the type system via the phantom type parameter @ph@. Certain -- operations such as lookup will only type-check if the @'Key'@ -- and the @'Map'@ have the same phantom type parameter. newtype Key ph k = Key k deriving (Eq, Ord, Show) type role Key nominal representational -- | An index that knows it is valid in certain @'Map'@s. -- -- The evidence that the index is valid for a map is carried by -- the type system via the phantom type parameter @ph@. Indexing -- operations such as `elemAt` will only type-check if the @'Index'@ -- and the @'Map'@ have the same phantom type parameter. newtype Index ph = Index Int deriving (Eq, Ord, Show) type role Index nominal -- | Get the underlying "Data.Map" @'Data.Map'@ out of a @'Map'@. theMap :: Map ph k v -> M.Map k v theMap (Map m) = m -- | Get a bare key out of a key-plus-evidence by forgetting -- what map the key can be found in. theKey :: Key ph k -> k theKey (Key k) = k -- | Get a bare index out of an index-plus-evidence by forgetting -- what map the index is valid for. theIndex :: Index ph -> Int theIndex (Index n) = n {-------------------------------------------------------------------- Evaluation --------------------------------------------------------------------} -- | Evaluate an expression using justified key lookups into the given map. -- -- > import qualified Data.Map as M -- > -- > withMap (M.fromList [(1,"A"), (2,"B")]) $ \m -> do -- > -- > -- prints "Found Key 1 with value A" -- > case member 1 m of -- > Nothing -> putStrLn "Missing key 1." -- > Just k -> putStrLn ("Found " ++ show k ++ " with value " ++ lookup k m) -- > -- > -- prints "Missing key 3." -- > case member 3 m of -- > Nothing -> putStrLn "Missing key 3." -- > Just k -> putStrLn ("Found " ++ show k ++ " with value " ++ lookup k m) withMap :: M.Map k v -- ^ The map to use as input -> (forall ph. Map ph k v -> t) -- ^ The computation to apply -> t -- ^ The resulting value withMap m cont = cont (Map m) -- | Like @'withMap'@, but begin with a singleton map taking @k@ to @v@. -- -- The continuation is passed a pair consisting of: -- -- 1. Evidence that @k@ is in the map, and -- -- 2. The singleton map itself, of type @'Map' ph k v@. -- -- > withSingleton 1 'a' (uncurry lookup) == 'a' withSingleton :: k -> v -> (forall ph. (Key ph k, Map ph k v) -> t) -> t withSingleton k v cont = cont (Key k, Map (M.singleton k v)) -- | Information about whether a key is present or missing. -- See @'Data.Map.Justified.withRecMap'@ and "Data.Map.Justified.Tutorial"'s @'Data.Map.Justified.Tutorial.example5'@. data KeyInfo = Present | Missing deriving (Show, Eq, Ord) -- | A description of what key/value-containing-keys pairs failed to be found. -- See @'Data.Map.Justified.withRecMap'@ and "Data.Map.Justified.Tutorial"'s @'Data.Map.Justified.Tutorial.example5'@. type MissingReference k f = (k, f (k, KeyInfo)) -- | Evaluate an expression using justified key lookups into the given map, -- when the values can contain references back to keys in the map. -- -- Each referenced key is checked to ensure that it can be found in the map. -- If all referenced keys are found, they are augmented with evidence and the -- given function is applied. -- If some referenced keys are missing, information about the missing references -- is generated instead. -- -- > import qualified Data.Map as M -- > -- > data Cell ptr = Nil | Cons ptr ptr deriving (Functor, Foldable, Traversable) -- > -- > memory1 = M.fromList [(1, Cons 2 1), (2, Nil)] -- > withRecMap memory1 (const ()) -- Right () -- > -- > memory2 = M.fromList [(1, Cons 2 3), (2, Nil)] -- > withRecMap memory2 (const ()) -- Left [(1, Cons (2,Present) (3,Missing))] -- -- See @'Data.Map.Justified.Tutorial.example5'@ for more usage examples. withRecMap :: forall k f t . (Ord k, Traversable f, Representational f) => M.Map k (f k) -- ^ A map with key references -> (forall ph. Map ph k (f (Key ph k)) -> t) -- ^ The checked continuation -> Either [MissingReference k f] t -- ^ Resulting value, or failure report. withRecMap m cont = case snd (partition (allKeysPresent . snd) $ M.toList m) of -- All referenced keys are found in the map; coerce the map's type. [] -> Right $ cont (Map $ (coerceWith mapCoercion) m) -- There were some dangling key references; report them. bads -> Left (map (\(k,v) -> (k, fmap (id &&& locate) v)) bads) where allKeysPresent = all ((== Present) . locate) locate k = if M.member k m then Present else Missing nestedValueCoercion :: Coercion (f k) (f (Key ph0 k)) nestedValueCoercion = rep Coercion mapCoercion :: Coercion (M.Map k (f k)) (M.Map k (f (Key ph0 k))) mapCoercion = rep nestedValueCoercion {-------------------------------------------------------------------- Gathering evidence --------------------------------------------------------------------} -- | /O(log n)/. Obtain evidence that the key is a member of the map. -- -- Where "Data.Map" generally requires evidence that a key exists in a map -- at every use of some functions (e.g. "Data.Map"'s @'Data.Map.lookup'@), -- @'Map'@ requires the evidence up-front. After it is known that a key can be -- found, there is no need for @'Maybe'@ types or run-time errors. -- -- The @Maybe value@ that has to be checked at every lookup in "Data.Map" -- is then shifted to a @Maybe (Key ph k)@ that has to be checked in order -- to obtain evidence that a key is in the map. -- -- Note that the "evidence" only exists at the type level, during compilation; -- there is no runtime distinction between keys and keys-plus-evidence. -- -- > withMap (M.fromList [(5,'a'), (3,'b')]) (isJust . member 1) == False -- > withMap (M.fromList [(5,'a'), (3,'b')]) (isJust . member 5) == True member :: Ord k => k -> Map ph k v -> Maybe (Key ph k) member k (Map m) = fmap (const $ Key k) (M.lookup k m) -- | A list of all of the keys in a map, along with proof -- that the keys exist within the map. keys :: Map ph k v -> [Key ph k] keys (Map m) = map Key (M.keys m) {-------------------------------------------------------------------- Lookup and update --------------------------------------------------------------------} -- | /O(log n)/. Find the value at a key. Unlike -- "Data.Map"'s @'Data.Map.!'@, this function is total and can not fail at runtime. (!) :: Ord k => Map ph k v -> Key ph k -> v (!) = flip lookup -- | /O(log n)/. Lookup the value at a key, known to be in the map. -- -- The result is a @v@ rather than a @Maybe v@, because the -- proof obligation that the key is in the map must already -- have been discharged to obtain a value of type @Key ph k@. -- lookup :: Ord k => Key ph k -> Map ph k v -> v lookup (Key k) (Map m) = case M.lookup k m of Just value -> value Nothing -> error "Data.Map.Justified has been subverted!" -- | /O(log n)/. Lookup the value at a key that is /not/ already known -- to be in the map. Return @Just@ the value /and/ the key-with-evidence -- if the key was present, or @Nothing@ otherwise. lookupMay :: Ord k => k -> Map ph k v -> Maybe (Key ph k, v) lookupMay k (Map m) = fmap (\v -> (Key k, v)) (M.lookup k m) -- | /O(log n)/. Find the largest key smaller than the given one -- and return the corresponding (key,value) pair, with evidence for the key. -- -- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupLT 3 table == Nothing -- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupLT 4 table == Just (Key 3, 'a') lookupLT :: Ord k => k -> Map ph k v -> Maybe (Key ph k, v) lookupLT k (Map m) = fmap (\(key, v) -> (Key key, v)) (M.lookupLT k m) -- | /O(log n)/. Find the smallest key greater than the given one -- and return the corresponding (key,value) pair, with evidence for the key. -- -- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupGT 4 table == Just (Key 5, 'b') -- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupGT 5 table == Nothing lookupGT :: Ord k => k -> Map ph k v -> Maybe (Key ph k, v) lookupGT k (Map m) = fmap (\(key, v) -> (Key key, v)) (M.lookupGT k m) -- | /O(log n)/. Find the largest key smaller than or equal to the given one -- and return the corresponding (key,value) pair, with evidence for the key. -- -- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupLE 2 table == Nothing -- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupLE 4 table == Just (Key 3, 'a') -- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupLE 5 table == Just (Key 5, 'b') lookupLE :: Ord k => k -> Map ph k v -> Maybe (Key ph k, v) lookupLE k (Map m) = fmap (\(key, v) -> (Key key, v)) (M.lookupLE k m) -- | /O(log n)/. Find the smallest key greater than or equal to the given one -- and return the corresponding (key,value) pair, with evidence for the key. -- -- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupGE 3 table == Just (Key 3, 'a') -- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupGE 4 table == Just (Key 5, 'b') -- > withMap (M.fromList [(3,'a'), (5,'b')]) $ \table -> lookupGE 6 table == Nothing lookupGE :: Ord k => k -> Map ph k v -> Maybe (Key ph k, v) lookupGE k (Map m) = fmap (\(key, v) -> (Key key, v)) (M.lookupGE k m) -- | Adjust the valid at a key, known to be in the map, -- using the given function. -- -- Since the set of valid keys in the input map and output map -- are the same, keys that were valid for the input map remain -- valid for the output map. adjust :: Ord k => (v -> v) -> Key ph k -> Map ph k v -> Map ph k v adjust f (Key k) = mmap (M.adjust f k) -- | Adjust the valid at a key, known to be in the map, -- using the given function. -- -- Since the set of valid keys in the input map and output map -- are the same, keys that were valid for the input map remain -- valid for the output map. adjustWithKey :: Ord k => (Key ph k -> v -> v) -> Key ph k -> Map ph k v -> Map ph k v adjustWithKey f (Key k) = mmap (M.adjustWithKey f' k) where f' key = f (Key key) -- | Replace the value at a key, known to be in the map. -- -- Since the set of valid keys in the input map and output map -- are the same, keys that were valid for the input map remain -- valid for the output map. reinsert :: Ord k => Key ph k -> v -> Map ph k v -> Map ph k v reinsert (Key k) v = mmap (M.insert k v) -- | Insert a value for a key that is /not/ known to be in the map, -- evaluating the updated map with the given continuation. -- -- The continuation is given three things: -- -- 1. A proof that the inserted key exists in the new map, -- -- 2. A function that can be used to convert evidence that a key -- exists in the original map, to evidence that the key exists in -- the updated map, and -- -- 3. The updated @'Data.Map.Justified.Map'@, with a /different phantom type/. -- -- > withMap (M.fromList [(5,'a'), (3,'b')]) (\table -> inserting 5 'x' table $ \(_,_,table') -> theMap table') == M.fromList [(3, 'b'), (5, 'x')] -- > withMap (M.fromList [(5,'a'), (3,'b')]) (\table -> inserting 7 'x' table $ \(_,_,table') -> theMap table') == M.fromList [(3, 'b'), (5, 'b'), (7, 'x')] -- -- See @'Data.Map.Justified.Tutorial.example4'@ for more usage examples. inserting :: Ord k => k -- ^ key to insert at -> v -- ^ value to insert -> Map ph k v -- ^ initial map -> (forall ph'. (Key ph' k, Key ph k -> Key ph' k, Map ph' k v) -> t) -- ^ continuation -> t inserting k v m cont = cont (Key k, qed, mmap (M.insert k v) m) -- | /O(log n)/. Insert with a function, combining new value and old value. -- @'insertingWith' f key value mp cont@ -- will insert the pair (key, value) into @mp@ if key does -- not exist in the map. If the key /does/ exist, the function will -- insert the pair @(key, f new_value old_value)@. -- -- The continuation is given three things (as in @'inserting'@): -- -- 1. A proof that the inserted key exists in the new map, -- -- 2. A function that can be used to convert evidence that a key -- exists in the original map, to evidence that the key exists in -- the updated map, and -- -- 3. The updated @'Data.Map.Justified.Map'@, with a /different phantom type/. -- -- > withMap (M.fromList [(5,"a"), (3,"b")]) (theMap . insertingWith (++) 5) == M.fromList [(3,"b"), (5,"xxxa")] -- > withMap (M.fromList [(5,"a"), (3,"b")]) (theMap . insertingWith (++) 7) == M.fromList [(3,"b"), (5,"a"), (7,"xxx")] insertingWith :: Ord k => (v -> v -> v) -- ^ combining function for existing keys -> k -- ^ key to insert at -> v -- ^ value to insert -> Map ph k v -- ^ initial map -> (forall ph'. (Key ph' k, Key ph k -> Key ph' k, Map ph' k v) -> t) -- ^ continuation -> t insertingWith f k v m cont = cont (Key k, qed, mmap (M.insertWith f k v) m) -- | /O(log n)/. Delete a key and its value from the map. -- -- The continuation is given two things: -- -- 1. A function that can be used to convert evidence that a key -- exists in the /updated/ map, to evidence that the key exists -- in the /original/ map. (contrast with 'inserting') -- -- 2. The updated map itself. -- deleting :: Ord k => k -- ^ key to remove -> Map ph k v -- ^ initial map -> (forall ph'. (Key ph' k -> Key ph k, Map ph' k v) -> t) -- ^ continuation -> t deleting k m cont = cont (qed, mmap (M.delete k) m) -- | /O(log n)/. Difference of two maps. -- Return elements of the first map not existing in the second map. -- -- The continuation is given two things: -- -- 1. A function that can be used to convert evidence that a key -- exists in the difference, to evidence that the key exists -- in the original left-hand map. -- -- 2. The updated map itself. -- subtracting :: Ord k => Map phL k a -- ^ the left-hand map -> Map phR k b -- ^ the right-hand map -> (forall ph'. (Key ph' k -> Key phL k, Map ph' k a) -> t) -- ^ continuation -> t subtracting mapL mapR cont = cont (qed, mmap2 M.difference mapL mapR) {-------------------------------------------------------------------- Unions --------------------------------------------------------------------} -- | Take the left-biased union of two @'Data.Map.Justified.Map'@s, as in "Data.Map"'s -- @'Data.Map.union'@, evaluating the unioned map with the given continuation. -- -- The continuation is given three things: -- -- 1. A function that can be used to convert evidence that a key exists in the left -- map to evidence that the key exists in the union, -- -- 2. A function that can be used to convert evidence that a key exists in the right -- map to evidence that the key exists in the union, and -- -- 3. The updated @'Data.Map.Justified.Map'@, with a /different phantom type/. -- unioning :: Ord k => Map phL k v -- ^ left-hand map -> Map phR k v -- ^ right-hand map -> (forall ph'. (Key phL k -> Key ph' k, Key phR k -> Key ph' k, Map ph' k v) -> t) -- ^ continuation -> t unioning mapL mapR cont = cont (qed, qed, mmap2 M.union mapL mapR) -- | @'unioningWith' f@ is the same as @'unioning'@, except that @f@ is used to -- combine values that correspond to keys found in both maps. unioningWith :: Ord k => (v -> v -> v) -- ^ combining function for intersection -> Map phL k v -- ^ left-hand map -> Map phR k v -- ^ right-hand map -> (forall ph'. (Key phL k -> Key ph' k, Key phR k -> Key ph' k, Map ph' k v) -> t) -- ^ continuation -> t unioningWith f mapL mapR cont = cont (qed, qed, mmap2 (M.unionWith f) mapL mapR) -- | @'unioningWithKey' f@ is the same as @'unioningWith' f@, except that @f@ also -- has access to the key and evidence that it is present in both maps. unioningWithKey :: Ord k => (Key phL k -> Key phR k -> v -> v -> v) -- ^ combining function for intersection, using key evidence -> Map phL k v -- ^ left-hand map -> Map phR k v -- ^ right-hand map -> (forall ph'. (Key phL k -> Key ph' k, Key phR k -> Key ph' k, Map ph' k v) -> t) -- ^ continuation -> t unioningWithKey f mapL mapR cont = cont (qed, qed, mmap2 (M.unionWithKey f') mapL mapR) where f' k = f (Key k) (Key k) {-------------------------------------------------------------------- Filtering --------------------------------------------------------------------} -- | Keep only the keys and associated values in a map that satisfy -- the predicate. -- -- The continuation is given two things: -- -- 1. A function that converts evidence that a key is present in -- the filtered map into evidence that the key is present in -- the original map, and -- -- 2. The filtered map itself, with a new phantom type parameter. -- filtering :: (v -> Bool) -- ^ predicate on values -> Map ph k v -- ^ original map -> (forall ph'. (Key ph' k -> Key ph k, Map ph' k v) -> t) -- ^ continuation -> t filtering f m cont = cont (qed, mmap (M.filter f) m) -- | As 'filtering', except the filtering function also has access to -- the key and existence evidence. filteringWithKey :: (Key ph k -> v -> Bool) -- ^ predicate on keys and values -> Map ph k v -- ^ original map -> (forall ph'. (Key ph' k -> Key ph k, Map ph' k v) -> t) -- ^ continuation -> t filteringWithKey f m cont = cont (qed, mmap (M.filterWithKey (f . Key)) m) {-------------------------------------------------------------------- Mapping and traversing --------------------------------------------------------------------} -- | /O(n)/. Map a function over all keys and values in the map. -- mapWithKey :: (Key ph k -> a -> b) -> Map ph k a -> Map ph k b mapWithKey f = mmap (M.mapWithKey f') where f' k = f (Key k) -- | /O(n)/. As in @'Data.Map.traverse'@: traverse the map, but give the -- traversing function access to the key associated with each value. traverseWithKey :: Applicative t => (Key ph k -> a -> t b) -- ^ traversal function -> Map ph k a -- ^ the map to traverse -> t (Map ph k b) traverseWithKey f (Map m) = fmap Map (M.traverseWithKey f' m) where f' k = f (Key k) -- | /O(n)/. The function @'mapAccum'@ threads an accumulating -- argument through the map in ascending order of keys. -- mapAccum :: (a -> b -> (a,c)) -> a -> Map ph k b -> (a, Map ph k c) mapAccum f a (Map m) = fmap Map (M.mapAccum f a m) -- | /O(n)/. The function @'mapAccumWithKey'@ threads an accumulating -- argument through the map in ascending order of keys. -- mapAccumWithKey :: (a -> Key ph k -> b -> (a,c)) -> a -> Map ph k b -> (a, Map ph k c) mapAccumWithKey f a (Map m) = fmap Map (M.mapAccumWithKey f' a m) where f' x k = f x (Key k) -- | /O(n*log n)/. -- @'mappingKeys'@ evaluates a continuation with the map obtained by applying -- @f@ to each key of @s@. -- -- The size of the resulting map may be smaller if @f@ maps two or more distinct -- keys to the same new key. In this case the value at the greatest of the -- original keys is retained. -- -- The continuation is passed two things: -- -- 1. A function that converts evidence that a key belongs to the original map -- into evidence that a key belongs to the new map. -- -- 2. The new, possibly-smaller map. -- -- mappingKeys :: Ord k2 => (k1 -> k2) -- ^ key-mapping function -> Map ph k1 v -- ^ initial map -> (forall ph'. (Key ph k1 -> Key ph' k2, Map ph' k2 v) -> t) -- ^ continuation -> t mappingKeys f m cont = cont (via f, mmap (M.mapKeys f) m) -- | /O(n*log n)/. -- Same as @'mappingKeys'@, but the key-mapping function can make use of -- evidence that the input key belongs to the original map. -- mappingKnownKeys :: Ord k2 => (Key ph k1 -> k2) -- ^ key-and-evidence-mapping function -> Map ph k1 v -- ^ initial map -> (forall ph'. (Key ph k1 -> Key ph' k2, Map ph' k2 v) -> t) -- ^ continuation -> t mappingKnownKeys f m cont = cont (Key . f, mmap (M.mapKeys f') m) where f' k = f (Key k) -- | /O(n*log n)/. -- Same as @'mappingKeys'@, except a function is used to combine values when -- two or more keys from the original map correspond to the same key in the -- final map. mappingKeysWith :: Ord k2 => (v -> v -> v) -- ^ value-combining function -> (k1 -> k2) -- ^ key-mapping function -> Map ph k1 v -- ^ initial map -> (forall ph'. (Key ph k1 -> Key ph' k2, Map ph' k2 v) -> t) -- ^ continuation -> t mappingKeysWith op f m cont = cont (via f, mmap (M.mapKeysWith op f) m) -- | /O(n*log n)/. -- Same as @'mappingKnownKeys'@, except a function is used to combine values when -- two or more keys from the original map correspond to the same key in the -- final map. mappingKnownKeysWith :: Ord k2 => (v -> v -> v) -- ^ value-combining function -> (Key ph k1 -> k2) -- ^ key-plus-evidence-mapping function -> Map ph k1 v -- ^ initial map -> (forall ph'. (Key ph k1 -> Key ph' k2, Map ph' k2 v) -> t) -- ^ continuation -> t mappingKnownKeysWith op f m cont = cont (Key . f, mmap (M.mapKeysWith op f') m) where f' k = f (Key k) {-------------------------------------------------------------------- Intersections --------------------------------------------------------------------} -- | Take the left-biased intersections of two @'Data.Map.Justified.Map'@s, as in "Data.Map"'s -- @'Data.Map.intersection'@, evaluating the intersection map with the given continuation. -- -- The continuation is given two things: -- -- 1. A function that can be used to convert evidence that a key exists in the intersection -- to evidence that the key exists in each original map, and -- -- 2. The updated @'Data.Map.Justified.Map'@, with a /different phantom type/. -- intersecting :: Ord k => Map phL k a -- ^ left-hand map -> Map phR k b -- ^ right-hand map -> (forall ph'. (Key ph' k -> (Key phL k, Key phR k), Map ph' k a) -> t) -- ^ continuation -> t intersecting mapL mapR cont = cont (qed2, mmap2 M.intersection mapL mapR) -- | As @'intersecting'@, but uses the combining function to merge mapped values on the intersection. intersectingWith :: Ord k => (a -> b -> c) -- ^ combining function -> Map phL k a -- ^ left-hand map -> Map phR k b -- ^ right-hand map -> (forall ph'. (Key ph' k -> (Key phL k, Key phR k), Map ph' k c) -> t) -- ^ continuation -> t intersectingWith f mapL mapR cont = cont (qed2, mmap2 (M.intersectionWith f) mapL mapR) -- | As @'intersectingWith'@, but the combining function has access to the map keys. intersectingWithKey :: Ord k => (Key phL k -> Key phR k -> a -> b -> c) -- ^ combining function -> Map phL k a -- ^ left-hand map -> Map phR k b -- ^ right-hand map -> (forall ph'. (Key ph' k -> (Key phL k, Key phR k), Map ph' k c) -> t) -- ^ continuation -> t intersectingWithKey f mapL mapR cont = cont (qed2, mmap2 (M.intersectionWithKey f') mapL mapR) where f' k = f (Key k) (Key k) {-------------------------------------------------------------------- Zipping --------------------------------------------------------------------} -- | Zip the values in two maps together. The phantom type @ph@ ensures -- that the two maps have the same set of keys, so no elements are left out. -- zip :: Ord k => Map ph k a -> Map ph k b -> Map ph k (a,b) zip = zipWith (,) -- | Combine the values in two maps together. The phantom type @ph@ ensures -- that the two maps have the same set of keys, so no elements are left out. zipWith :: Ord k => (a -> b -> c) -> Map ph k a -> Map ph k b -> Map ph k c zipWith f m1 m2 = mapWithKey (\k x -> f x (m2 ! k)) m1 -- | Combine the values in two maps together, using the key and values. -- The phantom type @ph@ ensures that the two maps have the same set of -- keys. zipWithKey :: Ord k => (Key ph k -> a -> b -> c) -> Map ph k a -> Map ph k b -> Map ph k c zipWithKey f m1 m2 = mapWithKey (\k x -> f k x (m2 ! k)) m1 {-------------------------------------------------------------------- Indexing --------------------------------------------------------------------} -- | /O(log n)/. Return the /index/ of a key, which is its zero-based index in -- the sequence sorted by keys. The index is a number from /0/ up to, but not -- including, the size of the map. The index also carries a proof that it is -- valid for the map. -- -- Unlike "Data.Map"'s @'Data.Map.findIndex'@, this function can not fail at runtime. findIndex :: Ord k => Key ph k -> Map ph k a -> Index ph findIndex (Key k) (Map m) = Index (M.findIndex k m) -- | /O(log n)/. Retrieve an element by its /index/, i.e. by its zero-based -- index in the sequence sorted by keys. -- -- Unlike "Data.Map"'s @'Data.Map.elemAt'@, this function can not fail at runtime. elemAt :: Index ph -> Map ph k v -> (Key ph k, v) elemAt (Index n) (Map m) = let (k,v) = M.elemAt n m in (Key k, v) {-------------------------------------------------------------------- Utilities --------------------------------------------------------------------} -- | Build a value by "tying the knot" according to the references in the map. tie :: (Functor f, Ord k) => (f a -> a) -- ^ folding function -> Map ph k (f (Key ph k)) -- ^ map with recursive key references -> Key ph k -> a tie phi m = go where go = (`lookup` table) table = fmap (phi . fmap go) m {-------------------------------------------------------------------- INTERNAL ONLY These functions are used to inform the type system about invariants of Data.Map. They cannot be available outside of this module. --------------------------------------------------------------------} -- | Coerce key-existence evidence qed :: Key ph k -> Key ph' k qed (Key k) = Key k -- | Coerce key-existence evidence qed2 :: Key ph k -> (Key phL k, Key phR k) qed2 (Key k) = (Key k, Key k) -- | Coerce key-existence evidence transported along a function via :: (k1 -> k2) -> Key ph k1 -> Key ph' k2 via f (Key k) = Key (f k) -- | Coerce one map type to another, using a function on "Data.Map"'s @'Data.Map.Map'@. mmap :: (M.Map k1 v1 -> M.Map k2 v2) -> Map ph1 k1 v1 -> Map ph2 k2 v2 mmap f (Map m) = Map (f m) -- | Coerce one map type to another, using a binary function on "Data.Map"'s @'Data.Map.Map'@. mmap2 :: (M.Map k1 v1 -> M.Map k2 v2 -> M.Map k3 v3) -> Map ph1 k1 v1 -> Map ph2 k2 v2 -> Map ph3 k3 v3 mmap2 f (Map m1) (Map m2) = Map (f m1 m2)
matt-noonan/justified-containers
src/Data/Map/Justified.hs
bsd-2-clause
35,649
0
16
8,386
5,914
3,268
2,646
292
3
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# OPTIONS_HADDOCK not-home #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Edward Kmett and Ted Cooper -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Ted Cooper <[email protected]> -- Stability : experimental -- Portability : non-portable -- -- STM-based RCU with concurrent writers ----------------------------------------------------------------------------- module Control.Concurrent.RCU.STM.Internal ( SRef(..) , RCUThread(..) , RCU(..) , runRCU , ReadingRCU(..) , WritingRCU(..) ) where import Control.Applicative import Control.Concurrent import Control.Concurrent.STM import Control.Concurrent.RCU.Class import Control.Monad import Control.Monad.IO.Class import Data.Coerce import Data.Int import Prelude hiding (read, Read) -------------------------------------------------------------------------------- -- * Shared References -------------------------------------------------------------------------------- -- | Shared references newtype SRef s a = SRef { unSRef :: TVar a } deriving Eq -------------------------------------------------------------------------------- -- * Read-Side Critical Sections -------------------------------------------------------------------------------- -- | This is the basic read-side critical section for an RCU computation newtype ReadingRCU s a = ReadingRCU { runReadingRCU :: IO a } deriving (Functor, Applicative, Monad) instance MonadNew (SRef s) (ReadingRCU s) where newSRef = r where r :: forall a. a -> ReadingRCU s (SRef s a) r = coerce (newTVarIO :: a -> IO (TVar a)) instance MonadReading (SRef s) (ReadingRCU s) where readSRef = r where r :: forall a. SRef s a -> ReadingRCU s a r = coerce (readTVarIO :: TVar a -> IO a) {-# INLINE readSRef #-} -------------------------------------------------------------------------------- -- * Write-Side Critical Sections -------------------------------------------------------------------------------- -- | This is the basic write-side critical section for an RCU computation newtype WritingRCU s a = WritingRCU { runWritingRCU :: TVar Int64 -> STM a } deriving Functor instance Applicative (WritingRCU s) where pure a = WritingRCU $ \ _ -> pure a WritingRCU mf <*> WritingRCU ma = WritingRCU $ \c -> mf c <*> ma c instance Monad (WritingRCU s) where return a = WritingRCU $ \ _ -> pure a WritingRCU m >>= f = WritingRCU $ \ c -> do a <- m c runWritingRCU (f a) c fail s = WritingRCU $ \ _ -> fail s instance Alternative (WritingRCU s) where empty = WritingRCU $ \ _ -> empty WritingRCU ma <|> WritingRCU mb = WritingRCU $ \c -> ma c <|> mb c instance MonadPlus (WritingRCU s) where mzero = WritingRCU $ \ _ -> mzero WritingRCU ma `mplus` WritingRCU mb = WritingRCU $ \c -> ma c `mplus` mb c instance MonadNew (SRef s) (WritingRCU s) where newSRef a = WritingRCU $ \_ -> SRef <$> newTVar a instance MonadReading (SRef s) (WritingRCU s) where readSRef (SRef r) = WritingRCU $ \ _ -> readTVar r {-# INLINE readSRef #-} instance MonadWriting (SRef s) (WritingRCU s) where writeSRef (SRef r) a = WritingRCU $ \ _ -> writeTVar r a synchronize = WritingRCU $ \ c -> modifyTVar' c (+1) -------------------------------------------------------------------------------- -- * RCU Context -------------------------------------------------------------------------------- -- | This is an RCU computation. It can use 'forking' and 'joining' to form -- new threads, and then you can use 'reading' and 'writing' to run classic -- read-side and write-side RCU computations. Contention between multiple -- write-side computations is managed by STM. newtype RCU s a = RCU { unRCU :: TVar Int64 -> IO a } deriving Functor instance Applicative (RCU s) where pure = return (<*>) = ap instance Monad (RCU s) where return a = RCU $ \ _ -> return a RCU m >>= f = RCU $ \s -> do a <- m s unRCU (f a) s instance MonadNew (SRef s) (RCU s) where newSRef a = RCU $ \_ -> SRef <$> newTVarIO a -- | This is a basic 'RCU' thread. It may be embellished when running in a more -- exotic context. data RCUThread s a = RCUThread { rcuThreadId :: {-# UNPACK #-} !ThreadId , rcuThreadVar :: {-# UNPACK #-} !(MVar a) } instance MonadRCU (SRef s) (RCU s) where type Reading (RCU s) = ReadingRCU s type Writing (RCU s) = WritingRCU s type Thread (RCU s) = RCUThread s forking (RCU m) = RCU $ \ c -> do result <- newEmptyMVar tid <- forkIO $ do x <- m c putMVar result x return (RCUThread tid result) joining (RCUThread _ m) = RCU $ \ _ -> readMVar m reading (ReadingRCU m) = RCU $ \ _ -> m writing (WritingRCU m) = RCU $ \ c -> atomically $ do _ <- readTVar c -- deliberately incur a data dependency! m c {-# INLINE forking #-} {-# INLINE joining #-} {-# INLINE reading #-} {-# INLINE writing #-} instance MonadIO (RCU s) where liftIO m = RCU $ \ _ -> m {-# INLINE liftIO #-} -- | Run an RCU computation. runRCU :: (forall s. RCU s a) -> IO a runRCU m = do c <- newTVarIO 0 unRCU m c {-# INLINE runRCU #-}
anthezium/rcu
src/Control/Concurrent/RCU/STM/Internal.hs
bsd-2-clause
5,541
0
15
1,051
1,412
761
651
106
1
module Handler.PostNew where import Import import Yesod.Form.Bootstrap3 import Yesod.Text.Markdown blogPostNewForm :: AForm Handler BlogPost blogPostNewForm = BlogPost <$> areq textField (bfs ("Title" :: Text)) Nothing <*> lift (liftIO getCurrentTime) <*> lift (liftIO getCurrentTime) <*> areq markdownField (bfs ("Article" :: Text)) Nothing getPostNewR :: Handler Html getPostNewR = do (widget, enctype) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm blogPostNewForm defaultLayout $ do $(widgetFile "posts/new") -- YesodPersist master => YesodPersistBackend master ~ SqlBackend => … postPostNewR :: Handler Html postPostNewR = do ((res, widget), enctype) <- runFormPostNoToken $ renderBootstrap3 BootstrapBasicForm blogPostNewForm case res of FormSuccess blogPost -> do blogPostId <- runDB $ insert blogPost redirect $ PostDetailsR blogPostId FormFailure errorMsgs -> defaultLayout $(widgetFile "errorpage") _ -> defaultLayout $(widgetFile "posts/new")
roggenkamps/steveroggenkamp.com
Handler/PostNew.hs
bsd-3-clause
1,115
0
14
263
277
138
139
-1
-1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Pack7 where import Data.Set (Set) import qualified Data.Set as Set import GHC.Exts (Constraint) -- type class for abstract sets class ISet s where type ISetCxt (s :: * -> *) a :: Constraint fromList :: ISetCxt s a => [a] -> s a instance ISet [] where type ISetCxt [] a = () fromList = id instance ISet Set where type ISetCxt Set a = Ord a fromList = Set.fromList -- type class for mapping sets in containers class ISet g => SetMap s t g | t -> g where setMap :: s -> t instance (ISet g, ISetCxt g a, ISetCxt g b) => SetMap ([a], [b]) (g a, g b) g where setMap (a, b) = (fromList a, fromList b) p1 :: ([Int], [Bool]) p1 = ([1, 2], [True, False]) {-| >>> testSetMap (fromList [1,2],fromList [False,True]) -} testSetMap :: (Set Int, Set Bool) testSetMap = setMap p1 -- TBD: replace ISet to a type variable
notae/haskell-exercise
pack/Pack7.hs
bsd-3-clause
1,188
0
9
288
341
196
145
30
1
module Util.Command where import System.Exit import Data.Tuple import Data.Map (Map, (!)) import qualified Data.Map as M import Data.Char import Genome.Dna.Kmer import Genome.Dna.Dna data Command = Command {utility :: String, arguments :: Map String String } instance Show Command where show (Command name args) = foldl addArg ("command" ++ name) (M.toList args) where addArg = \s xy -> s ++ " -" ++ (fst xy) ++ "=" ++ (snd xy) emptyCommand = Command "empty" M.empty readCommand :: [String] -> Command readCommand [] = emptyCommand readCommand (u:args) = if (allowedWord u) then Command u (readArgs args) else Command "illegal" M.empty where allowedWord :: String -> Bool allowedWord [] = False allowedWord (x:xs) = (isAlphaNum x) && all allowedChar xs allowedChar = \c -> (c == '-') || (isAlphaNum c) readArgs :: [String] -> Map String String readArgs = M.fromList . (map readOneArg) where readOneArg s = (tail $ takeWhile (/= '=') s, tail $ dropWhile (/= '=') s) availableCommands = M.fromList [ ("ptrn-count", "-f=<file-name> -p=<ptrn>"), ("most-frequent-kmers", "-f=<file-name> -k=<kmer-size> -n=<number>") ] usage u = if M.notMember u availableCommands then "Exception: " ++ u ++ " is not a valid command." else "Usage: " ++ u ++ " " ++ (availableCommands ! u) execute :: Command -> IO() execute (Command "hello" _) = do putStrLn "Hello jee! What may bioalgo tool-kit do for you?" putStrLn "Please call me with a command" putStrLn "" putStrLn "!!! BYE for now !!!" execute (Command "ptrn-count" argMap) = do text <- readFile (argMap ! "f") pcounts <- return $ ptrnCount (argMap ! "p") text putStr "number of appearances of " putStr (argMap ! "p") putStr ": " putStrLn (show pcounts) execute (Command "most-frequent-kmers" argMap) = do text <- readFile f kcounts <- return $ kmerCounts k text putStr (show (sum kcounts)) putStr (" total ") putStr (show k) putStrLn "-mers found." putStr " of which " putStr (show (length kcounts)) putStrLn " are unique." putStrLn $ "Top " ++ (show n) ++ " " ++ (show k) ++ "-mers: " mapM_ (\(s, m) -> putStrLn ((show m) ++ ": " ++ s))(topFrequentKmers n kcounts) where k = read (argMap ! "k") :: Int n = read (argMap ! "n") :: Int f = argMap ! "f" execute (Command "reverse-complement" argMap) = do putStrLn (if (isDNA seq) then reverseComplement seq else "Not a DNA sequence") where seq = argMap ! "s" execute (Command "illegal" _) = do putStrLn "Exception: illegal utility name." cltoolsUsage >> exitWith ExitSuccess execute (Command "empty" _) = do putStrLn "Exception: utility not specified." cltoolsUsage >> exitWith ExitSuccess -- last case, when every other case unmet execute (Command s _) = do putStrLn $ "Exception: unknown utility " ++ s ++ "." cltoolsUsage >> exitWith ExitSuccess cltoolsUsage = do putStrLn "Usage: [-vh] <utility> <arguments>" putStrLn "Available utilities: " mapM pcmd (M.toList availableCommands) where pcmd = (\ua -> putStrLn ((fst ua) ++ " " ++ (snd ua)))
visood/bioalgo
src/lib/Util/Command.hs
bsd-3-clause
3,189
0
15
741
1,112
559
553
77
3
{-# Language ScopedTypeVariables #-} module Pipes.Formats where import Control.Monad as M import Data.Array.Accelerate as A import Data.Array.Accelerate.IO as A import qualified Data.Vector.Storable as S import qualified Data.Vector.Storable.Mutable as SM import Pipes import Prelude as P vectorToArray :: (Int,Int,Int) -> Pipe (S.Vector Word8) (Array DIM3 Word8) IO () vectorToArray (h,w,d) = let dim = Z :. h :. w :. d in forever $ do v <- await yield $ fromVectors dim v -- | Takes in vectors and 'chunks' them out as int x dim size vectors -- vectorsToChunks :: forall m. MonadIO m => Int -> (Int,Int,Int) -> Pipe (S.Vector Word8) (S.Vector Word8) m () vectorsToChunks limit (h,w,d) = let maxCubeSize = limit * imageSize imageSize = (h*w*d) cubeAggregator :: Pipe (S.Vector Word8) (S.Vector Word8) m () cubeAggregator = do mem <- liftIO $ SM.new maxCubeSize M.forM_ (P.init [0..limit]) $ (\i -> do arr <- await let sliced = SM.unsafeSlice (i*imageSize) (imageSize) mem thawed <- liftIO $ S.unsafeThaw arr liftIO $ SM.copy sliced thawed ) liftIO (S.unsafeFreeze mem) >>= yield in forever $ cubeAggregator -- | Takes in chunks and slices them out as int number of dim vectors -- chunksToVectors :: MonadIO m => Int -> (Int,Int,Int) -> Pipe (S.Vector Word8) (S.Vector Word8) m () chunksToVectors limit (h,w,d) = let imageSize = h*w*d slicer = do chunk <- await mapM_ yield $ P.map (\i -> S.slice (i*imageSize) imageSize chunk) $ P.init [0..limit] in forever slicer
cpdurham/accelerate-camera-sandbox
src/Pipes/Formats.hs
bsd-3-clause
1,722
0
21
493
616
327
289
49
1
{-# LANGUAGE QuasiQuotes #-} module System.Console.CmdArgs.Test.SplitJoin(test) where import System.Console.CmdArgs.Explicit import System.Console.CmdArgs.Test.Util import Control.Monad test = do forM_ tests $ \(src,parsed) -> do let a = splitArgs src b1 = joinArgs parsed b2 = joinArgs $ splitArgs b1 if a == parsed then return () else failure "splitArgs" [("Given ",src),("Expected",show parsed),("Found ",show a)] if b1 == b2 then return () else failure "joinArgs" [("Given ",show parsed),("Expected",b1),("Found ",b2)] success {- newtype CmdLine = CmdLine String deriving Show instance Arbitrary CmdLine where arbitrary = fmap CmdLine $ listOf $ elements "abcd \\/\'\"" generateTests :: IO () generateTests = withTempFile $ \src -> do writeFile src "import System.Environment\nmain = print =<< getArgs\n" quickCheckWith stdArgs{chatty=False} $ \(CmdLine x) -> unsafePerformIO $ do putStr $ ",(,) " ++ (show x) ++ " " system $ "runghc \"" ++ src ++ "\" " ++ x return True withTempFile :: (FilePath -> IO a) -> IO a withTempFile f = bracket (do (file,h) <- openTempFile "." "cmdargs.hs"; hClose h; return file) removeFile f -} -- Pregenerate the QuickCheck tests and run them through the system console -- Not done each time for three reasons -- * Avoids an extra dependency on QuickCheck + process -- * Slow to run through the command line -- * Can't figure out how to read the output, without adding more escaping (which breaks the test) tests = [f "" [] ,f "c" ["c"] ,f "b" ["b"] ,f "\\" ["\\"] ,f "'//" ["'//"] ,f "a" ["a"] ,f "cda" ["cda"] ,f "b'" ["b'"] ,f "" [] ,f " " [] ,f "/b" ["/b"] ,f "\"b/\"d a'b'b" ["b/d","a'b'b"] ,f "d'c a\"/\\" ["d'c","a/\\"] ,f "d" ["d"] ,f "bb' " ["bb'"] ,f "b'\\" ["b'\\"] ,f "\"\\ac" ["\\ac"] ,f "\\'\"abbb\"c/''' \\ c" ["\\'abbbc/'''","\\","c"] ,f "/bbdbb a " ["/bbdbb","a"] ,f "b\" d" ["b d"] ,f "" [] ,f "\\cc/''\\b\\ccc\\'\\b\\" ["\\cc/''\\b\\ccc\\'\\b\\"] ,f "/" ["/"] ,f "///\"b\\c/b\"cd//c'\"" ["///b\\c/bcd//c'"] ,f "\\\"d\\\\' /d\\\\/bb'a /\\d" ["\"d\\\\'","/d\\\\/bb'a","/\\d"] ,f "c/ \\''/c b\\'" ["c/","\\''/c","b\\'"] ,f "dd'b\\\\\\' /c'aaa\"" ["dd'b\\\\\\'","/c'aaa"] ,f "b'd''\\/ b\\'b'db/'cd " ["b'd''\\/","b\\'b'db/'cd"] ,f "a\"ba\\/\\ " ["aba\\/\\ "] ,f "b\"'dd'c /b/c\"bbd \"\"\\ad'\"c\\\"" ["b'dd'c /b/cbbd","\\ad'c\""] ,f "da 'c\\\\acd/'dbaaa///dccbc a \\" ["da","'c\\\\acd/'dbaaa///dccbc","a","\\"] ,f "a'ac \"da\"" ["a'ac","da"] ,f "\"'\\\"/\"\"b\\b \"'\"\"ccd'a\"/c /da " ["'\"/\"b\\b","'\"ccd'a/c /da "] ,f "d\"\\c\\\\cb c/\"aa' b\"\\/d \"'c c/" ["d\\c\\\\cb c/aa'","b\\/d 'c","c/"] ,f "dbc\\/\"\"//c/\"accda" ["dbc\\///c/accda"] ,f "aca a'' \\ c b'\\/d\\" ["aca","a''","\\","c","b'\\/d\\"] ,f "dc\"bc/a\\ccdd\\\\aad\\c'ab '\\cddcdba" ["dcbc/a\\ccdd\\\\aad\\c'ab '\\cddcdba"] ,f " c'\"ba \"b\\dc\"" ["c'ba b\\dc"] ,f "a\\acd/a \"'c /'c'" ["a\\acd/a","'c /'c'"] ,f " ac ddc/\"\"a/\\bd\\d c'cac\"c\\a/a''c" ["ac","ddc/a/\\bd\\d","c'cacc\\a/a''c"] ,f "b/cd\"//bb\"/daaab/ b b \"' d\"a\" 'd b" ["b/cd//bb/daaab/","b","b","' da 'd b"] ,f "a\"cc'cd\"\\'ad '\"dcc acb\"\\\\" ["acc'cd\\'ad","'dcc acb\\\\"] ,f "/bc/bc'/\"d \"a/\"\\ad aba\\da" ["/bc/bc'/d a/\\ad aba\\da"] ,f "b\\a" ["b\\a"] ,f "/dc ''c'a\"'/'\\ /'cd\\'d/'db/b\"' cabacaaa\"\"dd" ["/dc","''c'a'/'\\ /'cd\\'d/'db/b'","cabacaaadd"] ,f "\"ac\\\"c'/c'b\"b\"b'd\"c\"\"" ["ac\"c'/c'bbb'dc"] ,f "/ 'ccc\"d\\dc'\"'\\ b" ["/","'cccd\\dc''\\","b"] ,f " '\"/\\cc\\/c '\\\\" ["'/\\cc\\/c '\\\\"] ,f "\\ \\' ' /d \"cc\\\\//da\"d'a/a\"ca\\\\\"\\cb c\"d'b 'acb" ["\\","\\'","'","/d","cc\\\\//dad'a/aca\\\\cb","cd'b 'acb"] ,f "a\"\"d'\"a\"\\ \\c db'da/d\\c\"a/ aa c/db" ["ad'a\\","\\c","db'da/d\\ca/ aa c/db"] ,f " d\\" ["d\\"] ,f "d c b'/\\/'\"/'a'aa\"a\"/ad\\/" ["d","c","b'/\\/'/'a'aaa/ad\\/"] ,f " a \\' /" ["a","\\'","/"] ,f "'/ c" ["'/","c"] ,f "acd 'bcab /ba'daa'/ba/\"dcdadbcacb" ["acd","'bcab","/ba'daa'/ba/dcdadbcacb"] ,f "a\\\"dd'a c\"a\"\"ac\\" ["a\"dd'a","ca\"ac\\"] ,f "\"dba /'bb\\ d ba '/c' \"dd\\' cbcd c /b/\\b///" ["dba /'bb\\ d ba '/c' dd\\'","cbcd","c","/b/\\b///"] ,f "a'c/c \"ccb '/d\\abd/bc " ["a'c/c","ccb '/d\\abd/bc "] ,f "\\da\"\\//add\\\\ c" ["\\da\\//add\\\\ c"] ,f "c/\\\"// a/\"ac\"//''ba\"c/\\bc\\\"d\"bc/d" ["c/\"//","a/ac//''bac/\\bc\"dbc/d"] ,f "/d/ a dc'\\ \"" ["/d/","a","dc'\\",""] ,f " \"dc//b\\cd/ \\ac\"b\"b\"d\"\"\"dd\"\" ' a\\'/ \"/'/\\a/abd\\ddd" ["dc//b\\cd/ \\acbbd\"dd","'","a\\'/","/'/\\a/abd\\ddd"] ,f "\\' ' d\"b bbc" ["\\'","'","db bbc"] ,f "'ba\\a'db/bd d\\'b\\ \\/a'da' " ["'ba\\a'db/bd","d\\'b\\","\\/a'da'"] ,f "\\b\\cc\"\"d' dd ddcb\"d" ["\\b\\ccd'","dd","ddcbd"] ,f "d\"dc'\\d\"/'\\\"b\\c'c\" db' \\'b/\"a' / da'\"/ab'\\ c\\bc\\//dbcb\\" ["ddc'\\d/'\"b\\c'c db' \\'b/a'","/","da'/ab'\\ c\\bc\\//dbcb\\"] ,f " b ddbbbbc\"da\\c\"'\\" ["b","ddbbbbcda\\c'\\"] ,f "b/\"d dacd'/'\\\"''a a /'\\c'b ab\\ dda\\c'abdd'a\"//d \\\\\\ d\"\"" ["b/d dacd'/'\"''a a /'\\c'b ab\\ dda\\c'abdd'a//d","\\\\\\","d"] ,f "/c\"\" dd'a'/b\\/'\"'/" ["/c","dd'a'/b\\/''/"] ,f "/\"'\"\"'cc a a\\dd''\\'b" ["/'\"'cc","a","a\\dd''\\'b"] ,f "c\"dcd''aba\" \" /'" ["cdcd''aba"," /'"] ,f "'\"/''\\\\d'/ad\\baadabdca\\ /\\'''bd\\/\"'/' aca \\ \\a'\\ cd\"d /bdcd''cac" ["'/''\\\\d'/ad\\baadabdca\\ /\\'''bd\\/'/'","aca","\\","\\a'\\","cdd /bdcd''cac"] ,f "\" /\"da" [" /da"] ,f "'\"ca/'d/d/d\\ca\"/\"\" ddac cc\" ''a c''bd\"bc'dc\\/\"b\"a\\\"\"a/\\ " ["'ca/'d/d/d\\ca/","ddac","cc ''a c''bdbc'dc\\/ba\"a/\\ "] ,f "\\\\d'ad ' ''\"cd/a \"\"\\'\\\"'dc\\" ["\\\\d'ad","'","''cd/a \"\\'\"'dc\\"] ,f " ab c'\\a" ["ab","c'\\a"] ,f "b" ["b"] ,f "''c dc c\\'d'ab'd\"\\\"cca\"b'da\"dbcdbd\"cd'/d \\cd'\"d \"\"b cdc''/\\\"b'" ["''c","dc","c\\'d'ab'd\"ccab'dadbcdbdcd'/d","\\cd'd \"b","cdc''/\"b'"] ,f " \"'cb dbddbdd/" ["'cb dbddbdd/"] ,f "a/\"d// dd/cc/\"cc\"d\" d\\/a a \\c\" \\\\/\"\\ bcc'ac'\"\\c//d\"da/\\aac\\b\"c/'b\"\"bbd/\\" ["a/d// dd/cc/ccd","d\\/a","a","\\c \\\\/\\","bcc'ac'\\c//dda/\\aac\\bc/'b\"bbd/\\"] ,f "b\"ddccd\"a\"/ba\"" ["bddccda/ba"] ,f " \" c/b/'/bdd cb d'c a'\"'a d\\\\db//\\\"' c'/'c\\/aa" [" c/b/'/bdd cb d'c a''a","d\\\\db//\"'","c'/'c\\/aa"] ,f "\\caab" ["\\caab"] ,f "bb\"'\"/d'bad 'd\\/'\\b//\\\\ \\d''c\"c b\\b/\\" ["bb'/d'bad","'d\\/'\\b//\\\\","\\d''cc b\\b/\\"] ,f " c'a\" \\cab\"bd\"dcd\"/cb/\"\"b\"b'\"d" ["c'a \\cabbddcd/cb/bb'd"] ,f "\\/ \"c'ca" ["\\/","c'ca"] ,f " d' /c'bc\"'/'\\\\dca'cc\"'\"''/d cb//'a \"bd ab\"dcaadc\\\"'d\\\"/a\"a\\\"ba//b/ d/dbac/d\\caa\"bc/ " ["d'","/c'bc'/'\\\\dca'cc'''/d cb//'a bd","abdcaadc\"'d\"/aa\"ba//b/","d/dbac/d\\caabc/ "] ,f "/\"\\db'd/ ca\"ad b\\\\\"cd/a bbc\\ " ["/\\db'd/ caad","b\\cd/a bbc\\ "] ,f "cdc bd'/\"c''c d \\\"aa \\d\\ bb'b/ /b/a/c'acda\\'\"\"c \"bbbaa/'/a \\aca\"'/ac' " ["cdc","bd'/c''c d \"aa \\d\\ bb'b/ /b/a/c'acda\\'\"c","bbbaa/'/a \\aca'/ac'"] ,f "ad/'b\\d /cc\"\"ab \\ \"' ''b\\\"/\\ a\"'d\"\\ddacdbbabb b b //' acd\"c\\d'd\\b\"'\\\"aaba/bda/c'// \\b" ["ad/'b\\d","/ccab","\\","' ''b\"/\\ a'd\\ddacdbbabb b b //' acdc\\d'd\\b'\"aaba/bda/c'// \\b"] ,f "bac cc \"ac\"/ca/ '\"\" b/b d /cd'\\'bb\" \\ \"b '/ b c ' c''\"a/ad\\ " ["bac","cc","ac/ca/","'","b/b","d","/cd'\\'bb \\ b","'/","b","c","'","c''a/ad\\ "] ,f "baa' b'b''\\dab/'c" ["baa'","b'b''\\dab/'c"] ,f "cb\\\\ " ["cb\\\\"] ,f "/b'a''d\"b\" 'c'b ba\\'b\" bb" ["/b'a''db","'c'b","ba\\'b bb"] ,f "b /\"ca\\cbac " ["b","/ca\\cbac "] ,f " \"\"/\"bcaa\"\"a' \\/bb \"a\\\"'\"" ["/bcaa\"a'","\\/bb","a\"'"] ,f "\"c /''c\"\\badc/\\daa/\\ c\"a c\\ \\/cab \"b\"\\ ba\"\"/d/cd'a ad'c/ad\"' a\\d/d\\c\\'cdccd/\"a'/\"b///ac\"" ["c /''c\\badc/\\daa/\\","ca c\\ \\/cab b\\ ba\"/d/cd'a","ad'c/ad' a\\d/d\\c\\'cdccd/a'/b///ac"] ,f "/cbbd\"/b' /dd\"/c\\ca/'\"\\ cc \\d\"aca/\"b caa\\d\\'\"b'b dc\"cd\\'c\" 'd/ac\"cacc\"" ["/cbbd/b' /dd/c\\ca/'\\ cc \\daca/b caa\\d\\'b'b","dccd\\'c","'d/accacc"] ,f "bc/bd\\ca\\bcacca\"\"\\c/\\ /\"\"a/\"c'//b'\\d/a/'ab/cbd/cacb//b \\d\"aac\\d'\"/" ["bc/bd\\ca\\bcacca\\c/\\","/a/c'//b'\\d/a/'ab/cbd/cacb//b \\daac\\d'/"] ,f "bbac bdc/d\\\"/db\"dbdb\"a \" /\"/'a\\acacbcc c'//\\//b\"ca\"bcca c\\/aaa/c/bccbccaa \"\" cdccc/bddcbc c''" ["bbac","bdc/d\"/dbdbdba"," //'a\\acacbcc","c'//\\//bcabcca","c\\/aaa/c/bccbccaa","","cdccc/bddcbc","c''"] ] where f = (,)
ndmitchell/cmdargs
System/Console/CmdArgs/Test/SplitJoin.hs
bsd-3-clause
8,627
0
15
1,452
1,731
999
732
115
3
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} ------------------------------------------------------------------------------ -- | This module is where all the routes and handlers are defined for your -- site. The 'app' function is the initializer that combines everything -- together and is exported by this module. module Site ( app ) where ------------------------------------------------------------------------------ import Control.Applicative import Control.Concurrent import Control.Concurrent.Async import Control.Concurrent.MVar import Control.Lens import Control.Monad import Control.Monad.Reader (asks) import Control.Monad.IO.Class (liftIO) import qualified Data.Acid as AS import Data.ByteString (ByteString) import Data.Default (def) import Data.List (groupBy) import Data.Maybe import qualified Data.Map as M import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Data.Time.Clock import Data.Time.Clock.POSIX import qualified Network.Gravatar as G import Snap import Snap.Core import Snap.Snaplet import Snap.Snaplet.AcidState (Update, Query, update, query, acidInitManual) import Snap.Snaplet.Auth import Snap.Snaplet.Auth.Backends.JsonFile import Snap.Snaplet.Heist import Snap.Snaplet.Session.Backends.CookieSession import Snap.Util.FileServe import Heist import qualified Heist.Interpreted as I import qualified Text.XmlHtml as X import Web.Bugzilla ------------------------------------------------------------------------------ import Application import Bugzilla ------------------------------------------------------------------------------ -- | Render login form handleLogin :: Maybe T.Text -> Handler App (AuthManager App) () handleLogin authError = heistLocal (I.bindSplices errs) $ render "login" where errs = maybe noSplices splice authError splice err = "loginError" ## I.textSplice err ------------------------------------------------------------------------------ -- | Handle login submit handleLoginSubmit :: Handler App (AuthManager App) () handleLoginSubmit = do mUser <- getParam "login" mPass <- getParam "password" case (mUser, mPass) of (Just user, Just pass) -> loginUser "login" "password" Nothing (\_ -> handleLogin err) (loginSuccess user pass) _ -> handleLogin invalidErr where err = Just "Unknown user or password." invalidErr = Just "Invalid request. Try again." loginSuccess user pass = do let userText = TE.decodeUtf8 user passText = TE.decodeUtf8 pass -- Create a Bugzilla session for this user. session <- liftIO $ newBzSession userText (Just passText) mvSessions <- withTop' id $ gets $ _bzSessions liftIO $ modifyMVar_ mvSessions $ return . M.insert userText session -- Synchronously update requests if there are none stored. mReqs <- query $ GetRequests userText when (isNothing mReqs) $ do reqs <- liftIO $ bzRequests session userText update $ UpdateRequests userText reqs -- We're now ready to display the dashboard. redirect "/dashboard" ------------------------------------------------------------------------------ -- | Logs out and redirects the user to the site index. handleLogout :: Handler App (AuthManager App) () handleLogout = logout >> redirect "/" ------------------------------------------------------------------------------ -- | Handle new user form submit handleNewUser :: Handler App (AuthManager App) () handleNewUser = method GET handleForm <|> method POST handleFormSubmit where handleForm = render "new_user" handleFormSubmit = do mUser <- getParam "login" case mUser of (Just user) -> do let newTime = posixSecondsToUTCTime 0 userText = TE.decodeUtf8 user update $ AddUser userText (UserInfo newTime) registerUser "login" "password" redirect "/" _ -> redirect "/new_user" ------------------------------------------------------------------------------ -- | Handle dashboard handleDashboard :: Handler App (AuthManager App) () handleDashboard = do mUser <- currentUser case mUser of Just user -> do let login = userLogin user curTime <- liftIO $ getCurrentTime mUserInfo <- query $ GetUser login update $ UpdateUser login (UserInfo curTime) mReqs <- query $ GetRequests login case (mUserInfo, mReqs) of (Just ui, Just reqs) -> renderDashboard curTime (ui ^. uiLastSeen) reqs (Nothing, _) -> handleLogin $ Just "You don't exist." _ -> handleLogin $ Just "You've been logged out. Please log in again." Nothing -> handleLogin $ Just "You need to be logged in for that." renderDashboard :: UTCTime -> UTCTime -> [BzRequest] -> Handler App (AuthManager App) () renderDashboard curTime lastSeen requests = do let (nis, rs, fs, as, ps, rds) = countRequests requests splices = do "dashboardItems" ## I.mapSplices (dashboardItemSplice lastSeen curTime) requests "needinfoCount" ## (return [X.TextNode . T.pack . show $ nis]) "reviewCount" ## (return [X.TextNode . T.pack . show $ rs]) "feedbackCount" ## (return [X.TextNode . T.pack . show $ fs]) "assignedCount" ## (return [X.TextNode . T.pack . show $ as]) "pendingCount" ## (return [X.TextNode . T.pack . show $ ps]) "reviewedCount" ## (return [X.TextNode . T.pack . show $ rds]) heistLocal (I.bindSplices splices) $ render "dashboard" dashboardItemSplice :: UTCTime -> UTCTime -> BzRequest -> I.Splice (Handler App App) dashboardItemSplice lastSeen curTime req = return $ [divNode ["item", containerClass req] $ [ divNode [reqClass req] $ titleBadge req ++ [X.Element "h1" [classes ["card-title", reqClass req]] [title req]] ] ++ extended req ++ [ divNode ["summary"] [X.Element "p" [] [bugLink req]] ] ++ details req ++ [ lastComment req , comments req ] ] where containerClass (NeedinfoRequest _ _ _) = "needinfo-container" containerClass (ReviewRequest _ _ _) = "review-container" containerClass (FeedbackRequest _ _ _) = "feedback-container" containerClass (AssignedRequest _ _ _) = "assigned-container" containerClass (PendingRequest _ _ _) = "pending-container" containerClass (ReviewedRequest _ _ _) = "reviewed-container" title r = linkNode (url r) [T.toUpper . reqClass $ r] where url (NeedinfoRequest _ _ _) = bugURL r url (ReviewRequest _ _ att) = attURL r att url (FeedbackRequest _ _ att) = attURL r att url (AssignedRequest _ _ _) = bugURL r url (PendingRequest _ _ _) = bugURL r url (ReviewedRequest _ _ _) = bugURL r titleBadge (NeedinfoRequest _ cs flag) = timeBadgeNode lastSeen cs curTime (flagCreationDate flag) titleBadge (ReviewRequest _ cs att) = timeBadgeNode lastSeen cs curTime (attachmentCreationTime att) titleBadge (FeedbackRequest _ cs att) = timeBadgeNode lastSeen cs curTime (attachmentCreationTime att) titleBadge (AssignedRequest bug cs _) = timeBadgeNode lastSeen cs curTime (bugCreationTime bug) titleBadge (PendingRequest bug cs _) = timeBadgeNode lastSeen cs curTime (bugCreationTime bug) titleBadge (ReviewedRequest bug cs _) = timeBadgeNode lastSeen cs curTime (bugCreationTime bug) reqClass (NeedinfoRequest _ _ _) = "needinfo" reqClass (ReviewRequest _ _ _) = "review" reqClass (FeedbackRequest _ _ _) = "feedback" reqClass (AssignedRequest _ _ _) = "assigned" reqClass (PendingRequest _ _ _) = "pending" reqClass (ReviewedRequest _ _ _) = "reviewed" bugLink r = linkNode (bugURL r) [bugIdText r, ": ", bugSummary . reqBug $ r] details (NeedinfoRequest bug _ flag) = [] details (ReviewRequest bug _ att) = [ divNode ["detail"] (attachmentNode att) ] details (FeedbackRequest bug _ att) = [ divNode ["detail"] (attachmentNode att) ] details (AssignedRequest bug _ atts) = [ divNode ["detail"] (concatMap attachmentNode atts) ] details (PendingRequest bug _ atts) = [ divNode ["detail"] (concatMap attachmentNode atts) ] details (ReviewedRequest bug _ atts) = [ divNode ["detail"] (concatMap attachmentNode atts) ] attachmentNode att = [ X.Element "hr" [] [] , divNode ["attachment"] $ [ divNode ["attachment-icon"] [] , pNode' ["attachment-summary"] [attachmentSummary att] ] ++ map attachmentFlagNode (attachmentFlags att) ] attachmentFlagNode f = divNode ["attachment-flag"] $ [ maybe noSmallGravatar smallGravatarImg (flagRequestee f) , X.Element "p" [] $ [ flagNameNode [flagName f, flagStatus f] , textNode [" " , fromMaybe "" (flagRequestee f)] ] ] extended (NeedinfoRequest bug _ flag) = [ divNode ["extended"] [ gravatarImg (flagSetter flag) , pNode [flagSetter flag] , timeNode curTime (flagCreationDate flag) ] ] extended (ReviewRequest bug _ att) = [ divNode ["extended"] [ gravatarImg (attachmentCreator att) , pNode [attachmentCreator att] , timeNode curTime (attachmentCreationTime att) ] ] extended (FeedbackRequest bug _ att) = [ divNode ["extended"] [ gravatarImg (attachmentCreator att) , pNode [attachmentCreator att] , timeNode curTime (attachmentCreationTime att) ] ] extended (AssignedRequest bug _ _) = [] extended (PendingRequest bug _ _) = [] extended (ReviewedRequest bug _ _) = [] lastComment r = divNode ["last-comment-wrapper"] $ map (commentNode r 200) (take 1 . reqComments $ r) comments r = divNode ["comments-wrapper"] $ [ divNode ["comments-inner-wrapper"] $ [ divNode ["comments"] $ map (commentNode r 0) (reqComments r)]] commentNode r limit c = divNode ["comment"] $ [ divNode (commentHeaderClasses lastSeen $ commentCreationTime c) $ [ gravatarImg (commentCreator c) , pNode [commentCreator c] , X.Element "p" [] $ [ linkNode (commentURL r c) ["#", T.pack . show $ commentCount c] , textNode [" (", T.pack . show $ commentCreationTime c, ")"] ] ] ] ++ (mergedComments . T.lines . applyLimit limit . commentText $ c) mergedComments = concatMap mergeQuotes . groupBy (same numQuotes) where mergeQuotes [] = [] mergeQuotes ls@(l:_) | isQuote l = if any (";" `T.isSuffixOf`) ls then map (pQuoteNode . (:[])) ls else [pQuoteNode [T.intercalate " " . map stripQuotes $ ls]] | otherwise = map (pNode . (:[])) ls commentTextNode line | ">" `T.isPrefixOf` line = X.Element "p" [classes ["quote"]] [X.TextNode line] | otherwise = pNode [line] gravatarImg email = divNode ["gravatar"] [X.Element "img" [("src", url)] []] where url = T.pack $ G.gravatar settings email settings = def { G.gDefault = Just G.Retro, G.gSize = Just $ G.Size 48 } smallGravatarImg email = divNode ["small-gravatar"] [X.Element "img" [("src", url)] []] where url = T.pack $ G.gravatar settings email settings = def { G.gDefault = Just G.Retro, G.gSize = Just $ G.Size 32 } noGravatar = divNode ["no-gravatar"] [] noSmallGravatar = divNode ["no-small-gravatar"] [] attURL :: BzRequest -> Attachment -> T.Text attURL r att = T.concat [ "https://bugzilla.mozilla.org/page.cgi?id=splinter.html&bug=" , bugIdText r , "&attachment=" , attachmentIdText att ] bugURL :: BzRequest -> T.Text bugURL r = T.concat ["https://bugzilla.mozilla.org/show_bug.cgi?id=", bugIdText r] commentURL :: BzRequest -> Comment -> T.Text commentURL r c = T.concat [ "https://bugzilla.mozilla.org/show_bug.cgi?id=" , bugIdText r , "#c" , commentIdText c ] attachmentIdText :: Attachment -> T.Text attachmentIdText = T.pack . show . attachmentId bugIdText :: BzRequest -> T.Text bugIdText = T.pack . show . bugId . reqBug commentIdText :: Comment -> T.Text commentIdText = T.pack . show . commentCount classes :: [T.Text] -> (T.Text, T.Text) classes cs = ("class", T.intercalate " " cs) textNode :: [T.Text] -> X.Node textNode = X.TextNode . T.concat linkNode :: T.Text -> [T.Text] -> X.Node linkNode url ts = X.Element "a" [("href", url)] [textNode ts] pNode :: [T.Text] -> X.Node pNode ts = X.Element "p" [] [textNode ts] flagNameNode :: [T.Text] -> X.Node flagNameNode ts = X.Element "span" [classes ["flag-name"]] [textNode ts] pNode' :: [T.Text] -> [T.Text] -> X.Node pNode' cs ts = X.Element "p" [classes cs] [textNode ts] pQuoteNode :: [T.Text] -> X.Node pQuoteNode ts = X.Element "p" [classes ["quote"]] [textNode ts] isQuote :: T.Text -> Bool isQuote = (">" `T.isPrefixOf`) divNode :: [T.Text] -> [X.Node] -> X.Node divNode cs es = X.Element "div" [classes cs] es oneWeek, twoWeeks, oneMonth :: NominalDiffTime oneWeek = fromIntegral $ 1 * 604800 twoWeeks = fromIntegral $ 2 * 604800 oneMonth = fromIntegral $ 4 * 604800 timeNode :: UTCTime -> UTCTime -> X.Node timeNode curTime itemTime | timeDiff > oneWeek = node ["overdue"] | otherwise = node [] where timeDiff = curTime `diffUTCTime` itemTime node cs = X.Element "p" [classes cs] [textNode [T.pack . show $ itemTime]] timeBadgeNode :: UTCTime -> [Comment] -> UTCTime -> UTCTime -> [X.Node] timeBadgeNode lastSeen cs curTime itemTime = newComment cs ++ overdue where newComment (c:_) | commentTimeDiff > 0 = [divNode ["left-badge"] [textNode ["+"]]] | otherwise = [] where commentTimeDiff = (commentCreationTime c) `diffUTCTime` lastSeen newComment _ = [] overdue | overdueTimeDiff > oneMonth = [overdueNode ["!!!"]] | overdueTimeDiff > twoWeeks = [overdueNode ["!!"]] | overdueTimeDiff > oneWeek = [overdueNode ["!"]] | otherwise = [] where overdueTimeDiff = curTime `diffUTCTime` itemTime overdueNode ts = divNode ["right-badge"] [textNode ts] commentHeaderClasses :: UTCTime -> UTCTime -> [T.Text] commentHeaderClasses lastSeen itemTime | timeDiff > 0 = ["comment-header", "new-comment"] | otherwise = ["comment-header"] where timeDiff = itemTime `diffUTCTime` lastSeen same :: Eq b => (a -> b) -> a -> a -> Bool same f a b = f a == f b numQuotes :: T.Text -> Int numQuotes = length . takeWhile (== "> ") . T.chunksOf 2 stripQuotes :: T.Text -> T.Text stripQuotes = T.concat . dropWhile (== "> ") . T.chunksOf 2 applyLimit :: Int -> T.Text -> T.Text applyLimit 0 = id applyLimit n = (`T.append` "...") . T.take n countRequests :: [BzRequest] -> (Int, Int, Int, Int, Int, Int) countRequests rs = go (0, 0, 0, 0, 0, 0) rs where go !count [] = count go (!nis, !rvs, !fbs, !as, !ps, !rds) ((NeedinfoRequest _ _ _) : rs) = go (nis + 1, rvs, fbs, as, ps, rds) rs go (!nis, !rvs, !fbs, !as, !ps, !rds) ((ReviewRequest _ _ _) : rs) = go (nis, rvs + 1, fbs, as, ps, rds) rs go (!nis, !rvs, !fbs, !as, !ps, !rds) ((FeedbackRequest _ _ _) : rs) = go (nis, rvs, fbs + 1, as, ps, rds) rs go (!nis, !rvs, !fbs, !as, !ps, !rds) ((AssignedRequest _ _ _) : rs) = go (nis, rvs, fbs, as + 1, ps, rds) rs go (!nis, !rvs, !fbs, !as, !ps, !rds) ((PendingRequest _ _ _) : rs) = go (nis, rvs, fbs, as, ps + 1, rds) rs go (!nis, !rvs, !fbs, !as, !ps, !rds) ((ReviewedRequest _ _ _) : rs) = go (nis, rvs, fbs, as, ps, rds + 1) rs ------------------------------------------------------------------------------ -- | The application's routes. routes :: [(ByteString, Handler App App ())] routes = [ ("/login", with auth handleLoginSubmit) , ("/logout", with auth handleLogout) , ("/new_user", with auth handleNewUser) , ("/dashboard", with auth handleDashboard) , ("", serveDirectory "static") ] ------------------------------------------------------------------------------ -- | The application initializer. app :: SnapletInit App App app = makeSnaplet "app" "An snaplet example application." Nothing $ do h <- nestSnaplet "" heist $ heistInit "templates" s <- nestSnaplet "sess" sess $ initCookieSessionManager "site_key.txt" "sess" (Just 3600) -- NOTE: We're using initJsonFileAuthManager here because it's easy and -- doesn't require any kind of database server to run. In practice, -- you'll probably want to change this to a more robust auth backend. a <- nestSnaplet "auth" auth $ initJsonFileAuthManager defAuthSettings sess "users.json" state <- liftIO $ AS.openLocalState (AppState M.empty M.empty) onUnload (AS.closeAcidState state) acid <- nestSnaplet "acid" acid $ acidInitManual state addRoutes routes addAuthSplices h auth mvSessions <- liftIO $ newMVar M.empty t <- liftIO $ async $ pollBugzilla mvSessions state 15 return $ App h s a acid t mvSessions pollBugzilla :: MVar (M.Map UserLogin BugzillaSession) -> AS.AcidState AppState -> Int -> IO () pollBugzilla !mvSessions !state !intervalMin = do -- Wait appropriately. let intervalUs = 60000000 * intervalMin threadDelay intervalUs -- Update all users with current sessions. sessions <- readMVar mvSessions forM_ (M.toList sessions) $ \(user, session) -> do putStrLn $ "Updating requests from Bugzilla for user " ++ show user reqs <- bzRequests session user AS.update state $ UpdateRequests user reqs -- Do it again. pollBugzilla mvSessions state intervalMin
sethfowler/bzbeaver
src/Site.hs
bsd-3-clause
19,014
0
19
5,288
5,832
3,002
2,830
327
33
module Del.Parser where import Control.Applicative import Control.Exception import qualified Data.Set as S import qualified Data.MultiSet as MS import Data.Typeable import Text.Trifecta import Del.Syntax eomParser :: Parser EOM eomParser = many equationParser equationParser :: Parser Equation equationParser = do spaces l <- symParser spaces char '=' spaces r <- expParser spaces return $ Equation l r expParser :: Parser Exp expParser = expr -- この実装は正しくない -- `*`, `/` よりも `**` のほうが結合性が高くなっているが -- `-c**2` を `-(c**2)` ではなく `(-c)**2` と解釈してしまう。 expr :: Parser Exp expr = (factor `chainl1` powop) `chainl1` mulop `chainl1` addop where addop = infixOp "+" Add <|> infixOp "-" Sub mulop = infixOp "*" Mul <|> infixOp "/" Div powop = infixOp "**" Pow infixOp :: String -> (a -> a -> a) -> Parser (a -> a -> a) infixOp op f = f <$ symbol op factor :: Parser Exp factor = parens expr <|> neg <|> symParser <|> numParser neg :: Parser Exp neg = symbol "-" >> Neg <$> factor numParser :: Parser Exp numParser = Num . either fromIntegral id <$> integerOrDouble symParser :: Parser Exp symParser = do n <- (:) <$> letter <*> many alphaNum as <- option S.empty $ brackets args ds <- option MS.empty $ MS.fromList <$> (char '_' *> some coord) return $ Sym n as ds args :: Parser Arg args = S.fromList <$> some (coord <* optional comma) coord :: Parser Coord coord = (char 't' *> pure T) <|> (char 'x' *> pure X) <|> (char 'y' *> pure Y) <|> (char 'z' *> pure Z) parseEOM :: String -> Either ErrInfo EOM parseEOM str = case parseString eomParser mempty $ filter (/=' ') str of Success eom -> Right eom Failure err -> Left err getEOMFromFile :: String -> IO EOM getEOMFromFile fn = do str <- readFile fn case parseEOM str of Right eom -> return eom Left err -> throwIO $ ParseException err data ParseException = ParseException ErrInfo deriving Typeable instance Show ParseException where show (ParseException e) = show e instance Exception ParseException
ishiy1993/mk-sode1
src/Del/Parser.hs
bsd-3-clause
2,197
0
11
510
743
369
374
66
2
module Trans where import Control.Monad.Trans.Reader import Control.Monad.Trans.State import Data.Functor.Identity import Control.Monad.Trans import Control.Monad.Trans.Maybe import Control.Monad rDec :: Num a => Reader a a rDec = fmap (flip (-) 1) ask rShow :: Show a => ReaderT a Identity String rShow = show <$> ask rPrintAndInc :: (Num a, Show a) => ReaderT a IO a rPrintAndInc = do a <- ask liftIO $ print ("Hi: " ++ show a) return (a + 1) sPrintIncAccum :: (Num a, Show a) => StateT a IO String sPrintIncAccum = do state <- get liftIO $ print ("Hi: " ++ show state) put (state + 1) return (show state) isValid :: String -> Bool isValid v = '!' `elem` v maybeExcite :: MaybeT IO String maybeExcite = do v <- liftIO getLine guard $ isValid v return v doExcite :: IO () doExcite = do putStrLn "Say something excite!" excite <- runMaybeT maybeExcite case excite of Nothing -> putStrLn "MOAR EXCITE" Just e -> putStrLn ("Good, was very excite: " ++ e)
nicklawls/haskellbook
src/Trans.hs
bsd-3-clause
998
0
12
213
393
198
195
38
2
module Logic.ProofNet where
digitalheir/net-prove
src/Logic/ProofNet.hs
bsd-3-clause
27
0
3
2
6
4
2
1
0
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} module Language.Epilog.AST.Program ( Program (..) ) where -------------------------------------------------------------------------------- import Language.Epilog.AST.Procedure import Language.Epilog.Epilog (Strings, Types) import Language.Epilog.SymbolTable import Language.Epilog.Treelike -------------------------------------------------------------------------------- import qualified Data.Map as Map (keys) import Prelude hiding (Either, null) -------------------------------------------------------------------------------- data Program = Program { types :: Types , procs :: Procedures , scope :: Scope , strings :: Strings } instance Treelike Program where toTree Program { types, procs, scope, strings } = Node "Program" [ Node "Types" (toForest' $ fst <$> types) , Node "Procs" (toForest procs) , Node "Scope" [toTree scope] , Node "Strings" (leaf <$> Map.keys strings) ]
adgalad/Epilog
src/Haskell/Language/Epilog/AST/Program.hs
bsd-3-clause
1,113
0
12
274
216
130
86
22
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- Load information on package sources module Stack.Build.Source ( loadSourceMap , SourceMap , PackageSource (..) ) where import Network.HTTP.Client.Conduit (HasHttpManager) import Control.Monad import Control.Monad.Catch (MonadCatch) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Resource import Data.Either import Data.Function import Data.List import qualified Data.Map as Map import Data.Map.Strict (Map) import Data.Maybe import Data.Monoid ((<>)) import qualified Data.Set as Set import qualified Data.Text as T import Path import Prelude hiding (FilePath, writeFile) import Stack.Build.Cache import Stack.Build.Types import Stack.BuildPlan (loadMiniBuildPlan, shadowMiniBuildPlan) import Stack.Package import Stack.Types import System.Directory hiding (findExecutable, findFiles) type SourceMap = Map PackageName PackageSource data PackageSource = PSLocal LocalPackage | PSUpstream Version Location (Map FlagName Bool) instance PackageInstallInfo PackageSource where piiVersion (PSLocal lp) = packageVersion $ lpPackage lp piiVersion (PSUpstream v _ _) = v piiLocation (PSLocal _) = Local piiLocation (PSUpstream _ loc _) = loc loadSourceMap :: (MonadIO m, MonadCatch m, MonadReader env m, HasBuildConfig env, MonadBaseControl IO m, HasHttpManager env, MonadLogger m) => BuildOpts -> m (MiniBuildPlan, [LocalPackage], SourceMap) loadSourceMap bopts = do bconfig <- asks getBuildConfig mbp0 <- case bcResolver bconfig of ResolverSnapshot snapName -> do $logDebug $ "Checking resolver: " <> renderSnapName snapName mbp <- loadMiniBuildPlan snapName return mbp ResolverGhc ghc -> return MiniBuildPlan { mbpGhcVersion = fromMajorVersion ghc , mbpPackages = Map.empty } locals <- loadLocals bopts let shadowed = Set.fromList (map (packageName . lpPackage) locals) <> Map.keysSet (bcExtraDeps bconfig) (mbp, extraDeps0) = shadowMiniBuildPlan mbp0 shadowed -- Add the extra deps from the stack.yaml file to the deps grabbed from -- the snapshot extraDeps1 = Map.union (Map.map (\v -> (v, Map.empty)) (bcExtraDeps bconfig)) (Map.map (\mpi -> (mpiVersion mpi, mpiFlags mpi)) extraDeps0) -- Overwrite any flag settings with those from the config file extraDeps2 = Map.mapWithKey (\n (v, f) -> PSUpstream v Local $ fromMaybe f $ Map.lookup n $ bcFlags bconfig) extraDeps1 let sourceMap = Map.unions [ Map.fromList $ flip map locals $ \lp -> let p = lpPackage lp in (packageName p, PSLocal lp) , extraDeps2 , flip fmap (mbpPackages mbp) $ \mpi -> (PSUpstream (mpiVersion mpi) Snap (mpiFlags mpi)) ] return (mbp, locals, sourceMap) loadLocals :: (MonadReader env m, HasBuildConfig env, MonadIO m, MonadLogger m, MonadThrow m, MonadCatch m) => BuildOpts -> m [LocalPackage] loadLocals bopts = do targets <- mapM parseTarget $ case boptsTargets bopts of Left [] -> ["."] Left x -> x Right _ -> [] (dirs, names0) <- case partitionEithers targets of ([], targets') -> return $ partitionEithers targets' (bad, _) -> throwM $ Couldn'tParseTargets bad let names = Set.fromList names0 bconfig <- asks getBuildConfig lps <- forM (Set.toList $ bcPackages bconfig) $ \dir -> do cabalfp <- getCabalFileName dir name <- parsePackageNameFromFilePath cabalfp let wanted = isWanted dirs names dir name pkg <- readPackage PackageConfig { packageConfigEnableTests = wanted && boptsFinalAction bopts == DoTests , packageConfigEnableBenchmarks = wanted && boptsFinalAction bopts == DoBenchmarks , packageConfigFlags = localFlags bopts bconfig name , packageConfigGhcVersion = bcGhcVersion bconfig , packageConfigPlatform = configPlatform $ getConfig bconfig } cabalfp when (packageName pkg /= name) $ throwM $ MismatchedCabalName cabalfp (packageName pkg) mbuildCache <- tryGetBuildCache dir mconfigCache <- tryGetConfigCache dir fileModTimes <- getPackageFileModTimes pkg cabalfp return LocalPackage { lpPackage = pkg , lpWanted = wanted , lpLastConfigOpts = mconfigCache , lpDirtyFiles = maybe True ((/= fileModTimes) . buildCacheTimes) mbuildCache , lpCabalFile = cabalfp , lpDir = dir } let known = Set.fromList $ map (packageName . lpPackage) lps unknown = Set.difference names known unless (Set.null unknown) $ throwM $ UnknownTargets $ Set.toList unknown return lps where parseTarget t = do let s = T.unpack t isDir <- liftIO $ doesDirectoryExist s if isDir then liftM (Right . Left) $ liftIO (canonicalizePath s) >>= parseAbsDir else return $ case parsePackageNameFromString s of Left _ -> Left t Right pname -> Right $ Right pname isWanted dirs names dir name = name `Set.member` names || any (`isParentOf` dir) dirs || any (== dir) dirs -- | All flags for a local package localFlags :: BuildOpts -> BuildConfig -> PackageName -> Map FlagName Bool localFlags bopts bconfig name = Map.union (fromMaybe Map.empty $ Map.lookup name $ boptsFlags bopts) (fromMaybe Map.empty $ Map.lookup name $ bcFlags bconfig)
mietek/stack
src/Stack/Build/Source.hs
bsd-3-clause
6,444
0
18
2,122
1,657
857
800
134
6
{-# LANGUAGE BangPatterns #-} module Atomo.Environment where import Control.Monad.Cont import Control.Monad.State import Data.IORef import Atomo.Method import Atomo.Pattern import Atomo.Pretty import Atomo.Types -- | Evaluate an expression, yielding a value. eval :: Expr -> VM Value eval (EDefine { emPattern = p, eExpr = ev }) = do define p ev return (particle "ok") eval (ESet { ePattern = PMessage p, eExpr = ev }) = do v <- eval ev define p (EPrimitive (eLocation ev) v) return v eval (ESet { ePattern = p, eExpr = ev }) = do v <- eval ev set p v eval (EDispatch { eMessage = Single i n t [] }) = do v <- eval t dispatch (Single i n v []) eval (EDispatch { eMessage = Single i n t os }) = do v <- eval t nos <- forM os $ \(Option oi on oe) -> do ov <- eval oe return (Option oi on ov) dispatch (Single i n v nos) eval (EDispatch { eMessage = Keyword i ns ts [] }) = do vs <- mapM eval ts dispatch (Keyword i ns vs []) eval (EDispatch { eMessage = Keyword i ns ts os }) = do vs <- mapM eval ts nos <- forM os $ \(Option oi on e) -> do ov <- eval e return (Option oi on ov) dispatch (Keyword i ns vs nos) eval (EOperator { eNames = ns, eAssoc = a, ePrec = p }) = do forM_ ns $ \n -> modify $ \s -> s { parserState = (parserState s) { psOperators = (n, (a, p)) : psOperators (parserState s) } } return (particle "ok") eval (EPrimitive { eValue = v }) = return v eval (EBlock { eArguments = as, eContents = es }) = do t <- gets top return (Block t as es) eval (EList { eContents = es }) = do vs <- mapM eval es return (list vs) eval (ETuple { eContents = es }) = do vs <- mapM eval es return (tuple vs) eval (EMacro {}) = return (particle "ok") eval (EForMacro {}) = return (particle "ok") eval (EParticle { eParticle = Single i n mt os }) = do nos <- forM os $ \(Option oi on me) -> liftM (Option oi on) (maybe (return Nothing) (liftM Just . eval) me) nmt <- maybe (return Nothing) (liftM Just . eval) mt return (Particle $ Single i n nmt nos) eval (EParticle { eParticle = Keyword i ns mts os }) = do nmts <- forM mts $ maybe (return Nothing) (liftM Just . eval) nos <- forM os $ \(Option oi on me) -> liftM (Option oi on) (maybe (return Nothing) (liftM Just . eval) me) return (Particle $ Keyword i ns nmts nos) eval (ETop {}) = gets top eval (EVM { eAction = x }) = x eval (EUnquote { eExpr = e }) = raise ["out-of-quote"] [Expression e] eval (EQuote { eExpr = qe }) = do unquoted <- unquote 0 qe return (Expression unquoted) where unquote :: Int -> Expr -> VM Expr unquote 0 (EUnquote { eExpr = e }) = do r <- eval e case r of Expression e' -> return e' _ -> return (EPrimitive Nothing r) unquote n u@(EUnquote { eExpr = e }) = do ne <- unquote (n - 1) e return (u { eExpr = ne }) unquote n q@(EQuote { eExpr = e }) = do ne <- unquote (n + 1) e return q { eExpr = ne } unquote n d@(EDefine { eExpr = e }) = do ne <- unquote n e return (d { eExpr = ne }) unquote n s@(ESet { eExpr = e }) = do ne <- unquote n e return (s { eExpr = ne }) unquote n d@(EDispatch { eMessage = em }) = case em of Keyword { mTargets = ts } -> do nts <- mapM (unquote n) ts return d { eMessage = em { mTargets = nts } } Single { mTarget = t } -> do nt <- unquote n t return d { eMessage = em { mTarget = nt } } unquote n b@(EBlock { eContents = es }) = do nes <- mapM (unquote n) es return b { eContents = nes } unquote n l@(EList { eContents = es }) = do nes <- mapM (unquote n) es return l { eContents = nes } unquote n t@(ETuple { eContents = es }) = do nes <- mapM (unquote n) es return t { eContents = nes } unquote n m@(EMacro { eExpr = e }) = do ne <- unquote n e return m { eExpr = ne } unquote n p@(EParticle { eParticle = ep }) = case ep of Keyword { mNames = ns, mTargets = mes } -> do nmes <- forM mes $ \me -> case me of Nothing -> return Nothing Just e -> liftM Just (unquote n e) return p { eParticle = keyword ns nmes } _ -> return p unquote n d@(ENewDynamic { eExpr = e }) = do ne <- unquote n e return d { eExpr = ne } unquote n d@(EDefineDynamic { eExpr = e }) = do ne <- unquote n e return d { eExpr = ne } unquote n d@(ESetDynamic { eExpr = e }) = do ne <- unquote n e return d { eExpr = ne } unquote n p@(EPrimitive { eValue = Expression e }) = do ne <- unquote n e return p { eValue = Expression ne } unquote n m@(EMatch { eTarget = t, eBranches = bs }) = do nt <- unquote n t nbs <- forM bs $ \(p, e) -> do ne <- unquote n e return (p, ne) return m { eTarget = nt, eBranches = nbs } unquote _ p@(EPrimitive {}) = return p unquote _ t@(ETop {}) = return t unquote _ v@(EVM {}) = return v unquote _ o@(EOperator {}) = return o unquote _ f@(EForMacro {}) = return f unquote _ g@(EGetDynamic {}) = return g unquote _ q@(EMacroQuote {}) = return q eval (ENewDynamic { eBindings = bes, eExpr = e }) = do bvs <- forM bes $ \(n, b) -> do v <- eval b return (n, v) dynamicBind bvs (eval e) eval (EDefineDynamic { eName = n, eExpr = e }) = do v <- eval e modify $ \env -> env { dynamic = newDynamic n v (dynamic env) } return v eval (ESetDynamic { eName = n, eExpr = e }) = do v <- eval e d <- gets dynamic if isBound n d then modify $ \env -> env { dynamic = setDynamic n v d } else raise ["unbound-dynamic"] [string n] return v eval (EGetDynamic { eName = n }) = do mv <- gets (getDynamic n . dynamic) maybe (raise ["unknown-dynamic"] [string n]) return mv eval (EMacroQuote { eName = n, eRaw = r, eFlags = fs }) = do t <- gets (psEnvironment . parserState) dispatch $ keyword' ["quote", "as"] [t, string r, particle n] [option "flags" (list (map Character fs))] eval (EMatch { eTarget = t, eBranches = bs }) = do v <- eval t ids <- gets primitives matchBranches ids bs v matchBranches :: IDs -> [(Pattern, Expr)] -> Value -> VM Value matchBranches _ [] v = raise ["no-match-for"] [v] matchBranches ids ((p, e):ps) v = do p' <- matchable' p if match ids Nothing p' v then newScope $ set p' v >> eval e else matchBranches ids ps v -- | Evaluate multiple expressions, returning the last result. evalAll :: [Expr] -> VM Value evalAll [] = throwError NoExpressions evalAll [e] = eval e evalAll (e:es) = eval e >> evalAll es -- | Create a new empty object, passing a function to initialize it. newObject :: Delegates -> (MethodMap, MethodMap) -> VM Value newObject ds mm = do ms <- liftIO (newIORef mm) return (Object ds ms) -- | Run x with t as its toplevel object. withTop :: Value -> VM a -> VM a withTop !t x = do o <- gets top modify (\e -> e { top = t }) res <- x modify (\e -> e { top = o }) return res -- | Execute an action with the given dynamic bindings. dynamicBind :: [(String, Value)] -> VM a -> VM a dynamicBind bs x = do modify $ \e -> e { dynamic = foldl (\m (n, v) -> bindDynamic n v m) (dynamic e) bs } res <- x modify $ \e -> e { dynamic = foldl (\m (n, _) -> unbindDynamic n m) (dynamic e) bs } return res -- | Execute an action with a new toplevel delegating to the old one. newScope :: VM a -> VM a newScope x = do t <- gets top nt <- newObject [t] noMethods withTop nt x ----------------------------------------------------------------------------- -- Define ------------------------------------------------------------------- ----------------------------------------------------------------------------- -- | Insert a method on a single value. defineOn :: Value -> Method -> VM () defineOn v m' = liftIO $ do (oss, oks) <- readIORef (oMethods v) writeIORef (oMethods v) $ case mPattern m of Single {} -> (addMethod m oss, oks) Keyword {} -> (oss, addMethod m oks) where m = m' { mPattern = setSelf v (mPattern m') } -- | Define a method on all roles involved in its pattern. define :: Message Pattern -> Expr -> VM () define !p !e = do is <- gets primitives newp <- matchable p m <- method newp e os <- targets is newp forM_ os (flip defineOn m) where method p' (EPrimitive _ v) = return (Slot p' v) method p' e' = gets top >>= \t -> return (Responder p' t e') -- | Swap out a reference match with PThis, for inserting on an object. setSelf :: Value -> Message Pattern -> Message Pattern setSelf v (Keyword i ns ps os) = Keyword i ns (map (setSelf' v) ps) os setSelf v (Single i n t os) = Single i n (setSelf' v t) os setSelf' :: Value -> Pattern -> Pattern setSelf' v (PMatch x) | v == x = PThis setSelf' v (PMessage m) = PMessage $ setSelf v m setSelf' v (PNamed n p') = PNamed n (setSelf' v p') setSelf' v (PInstance p) = PInstance (setSelf' v p) setSelf' v (PStrict p) = PStrict (setSelf' v p) setSelf' _ p' = p' -- | Pattern-match a value, inserting bindings into the current toplevel. set :: Pattern -> Value -> VM Value set p v = do is <- gets primitives if match is Nothing p v then do forM_ (bindings' p v) $ \(p', v') -> define p' (EPrimitive Nothing v') return v else throwError (Mismatch p v) -- | Turn any PObject patterns into PMatches. matchable :: Message Pattern -> VM (Message Pattern) matchable p'@(Single { mTarget = t }) = do t' <- matchable' t return p' { mTarget = t' } matchable p'@(Keyword { mTargets = ts }) = do ts' <- mapM matchable' ts return p' { mTargets = ts' } matchable' :: Pattern -> VM Pattern matchable' PThis = liftM PMatch (gets top) matchable' (PObject oe) = liftM PMatch (eval oe) matchable' (PInstance p) = liftM PInstance (matchable' p) matchable' (PStrict p) = liftM PStrict (matchable' p) matchable' (PVariable p) = liftM PVariable (matchable' p) matchable' (PNamed n p') = liftM (PNamed n) (matchable' p') matchable' (PMessage m) = liftM PMessage (matchable m) matchable' p' = return p' -- | Find the target objects for a message pattern. targets :: IDs -> Message Pattern -> VM [Value] targets is (Single { mTarget = p }) = targets' is p targets is (Keyword { mTargets = ps }) = targets' is (head ps) -- | Find the target objects for a pattern. targets' :: IDs -> Pattern -> VM [Value] targets' _ (PMatch v) = liftM (: []) (objectFor v) targets' is (PNamed _ p) = targets' is p targets' is PAny = return [idObject is] targets' is (PList _) = return [idList is] targets' is (PTuple _) = return [idTuple is] targets' is (PHeadTail h t) = do ht <- targets' is h tt <- targets' is t if idCharacter is `elem` ht || idString is `elem` tt then return [idList is, idString is] else return [idList is] targets' is (PPMKeyword {}) = return [idParticle is] targets' is (PExpr _) = return [idExpression is] targets' is (PInstance p) = targets' is p targets' is (PStrict p) = targets' is p targets' is (PVariable _) = return [idObject is] targets' is (PMessage m) = targets is m targets' _ p = error $ "no targets for " ++ show p ----------------------------------------------------------------------------- -- Dispatch ----------------------------------------------------------------- ----------------------------------------------------------------------------- -- | Dispatch a message to all roles and return a value. -- -- If the message is not understood, @\@did-not-understand:(at:)@ is sent to all -- roles until one responds to it. If none of them handle it, a -- @\@did-not-understand:@ error is raised. dispatch :: Message Value -> VM Value dispatch !m = do find <- findMethod (target m) m case find of Just method -> runMethod method m Nothing -> case m of Single { mTarget = t } -> sendDNU t Keyword { mTargets = ts } -> sendDNUs ts 0 where target (Single { mTarget = t }) = t target (Keyword { mTargets = ts }) = head ts sendDNU v = do find <- findMethod v (dnuSingle v) case find of Nothing -> throwError $ DidNotUnderstand m Just method -> runMethod method (dnuSingle v) sendDNUs [] _ = throwError $ DidNotUnderstand m sendDNUs (v:vs') n = do find <- findMethod v (dnu v n) case find of Nothing -> sendDNUs vs' (n + 1) Just method -> runMethod method (dnu v n) dnu v n = keyword ["did-not-understand", "at"] [v, Message m, Integer n] dnuSingle v = keyword ["did-not-understand"] [v, Message m] -- | Find a method on an object that responds to a given message, searching -- its delegates if necessary. findMethod :: Value -> Message Value -> VM (Maybe Method) findMethod v m = do is <- gets primitives o <- objectFor v ms <- liftIO (readIORef (oMethods o)) case relevant is o ms m of Nothing -> findFirstMethod m (oDelegates o) mt -> return mt -- | Find the first value that has a method defiend for a given message. findFirstMethod :: Message Value -> [Value] -> VM (Maybe Method) findFirstMethod _ [] = return Nothing findFirstMethod m (v:vs) = do r <- findMethod v m case r of Nothing -> findFirstMethod m vs _ -> return r -- | Find a method on an object that responds to a given message. relevant :: IDs -> Value -> (MethodMap, MethodMap) -> Message Value -> Maybe Method relevant ids o ms m = lookupMap (mID m) (methods m) >>= firstMatch ids (Just o) m where methods (Single {}) = fst ms methods (Keyword {}) = snd ms firstMatch _ _ _ [] = Nothing firstMatch ids' r' m' (mt:mts) | match ids' r' (PMessage (mPattern mt)) (Message m') = Just mt | otherwise = firstMatch ids' r' m' mts -- | Evaluate a method. -- -- Responder methods: evaluates its expression in a scope with the pattern's -- bindings, delegating to the method's context. -- -- Slot methods: simply returns the value. -- -- Macro methods: evaluates its expression in a scope with the pattern's -- bindings. runMethod :: Method -> Message Value -> VM Value runMethod (Slot { mValue = v }) _ = return v runMethod (Responder { mPattern = p, mContext = c, mExpr = e }) m = do nt <- newObject [c] (bindings p m, emptyMap) forM_ (mOptionals p) $ \(Option i n (PObject oe)) -> case filter (\(Option x _ _) -> x == i) (mOptionals m) of [] -> do d <- withTop nt (eval oe) define (Single i n (PMatch nt) []) (EPrimitive Nothing d) (Option oi on ov:_) -> define (Single oi on (PMatch nt) []) (EPrimitive Nothing ov) withTop nt $ eval e runMethod (Macro { mPattern = p, mExpr = e }) m = do t <- gets (psEnvironment . parserState) nt <- newObject [t] (bindings p m, emptyMap) forM_ (mOptionals p) $ \(Option i n (PExpr d)) -> case filter (\(Option x _ _) -> x == i) (mOptionals m) of [] -> define (Single i n (PMatch nt) []) (EPrimitive Nothing (Expression d)) (Option oi on ov:_) -> define (Single oi on (PMatch nt) []) (EPrimitive Nothing ov) withTop nt $ eval e -- | Get the object for a value. objectFor :: Value -> VM Value {-# INLINE objectFor #-} objectFor !v = gets primitives >>= \is -> return $ objectFrom is v -- | Raise a keyword particle as an error. raise :: [String] -> [Value] -> VM a {-# INLINE raise #-} raise ns vs = throwError . Error $ keyParticleN ns vs -- | Raise a single particle as an error. raise' :: String -> VM a {-# INLINE raise' #-} raise' = throwError . Error . particle -- | Convert an AtomoError into a value and raise it as an error. throwError :: AtomoError -> VM a {-throwError e = error ("panic: " ++ show (pretty e))-} throwError e = gets top >>= \t -> do r <- dispatch (keyword ["responds-to?"] [t, particle "Error"]) if r == Boolean True then do dispatch (msg t) error ("panic: error returned normally for: " ++ show e) else error ("panic: " ++ show (pretty e)) where msg t = keyword ["error"] [t, asValue e]
vito/atomo
src/Atomo/Environment.hs
bsd-3-clause
16,982
0
20
5,074
6,835
3,405
3,430
390
28
module Test where test :: Int -> Int -> IO () test a b = putStrLn $ mconcat [ "Addition: " , show addition , ", Subtraction: " , show subtraction ] where addition = a + b subtraction = a - b main :: IO () main = output 1 where output 0 = test 0 0 output a = test a 2
hecrj/haskell-format
test/specs/where/output.hs
bsd-3-clause
436
0
8
233
123
63
60
20
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} -- | A pool of handles module Data.Concurrent.Queue.Roq.HandlePool ( -- * Starting the server hroq_handle_pool_server , hroq_handle_pool_server_closure , hroq_handle_pool_server_pid -- * API , append -- * Types -- , CallbackFun -- * Debug , ping , safeOpenFile -- * Remote Table , Data.Concurrent.Queue.Roq.HandlePool.__remoteTable ) where import Control.Distributed.Process hiding (call) import Control.Distributed.Process.Closure import Control.Distributed.Process.Platform.ManagedProcess hiding (runProcess) import Control.Distributed.Process.Platform.Time import Control.Distributed.Process.Serializable() import Control.Exception hiding (try,catch) import Data.Binary import Data.Concurrent.Queue.Roq.Logger import Data.List import Data.Typeable (Typeable) import GHC.Generics import System.Directory import System.IO import System.IO.Error import qualified Data.ByteString.Lazy.Char8 as B import qualified Data.Map as Map -------------------------------------------------------------------------------- -- Types -- -------------------------------------------------------------------------------- {- -define(MONITOR_INTERVAL_MS, 30000). -} mONITOR_INTERVAL_MS :: Delay -- mONITOR_INTERVAL_MS = Delay $ milliSeconds 30000 mONITOR_INTERVAL_MS = Delay $ milliSeconds 9000 ------------------------------------------------------------------------ -- Data Types ------------------------------------------------------------------------ -- Call operations data AppendFile = AppendFile FilePath B.ByteString deriving (Show,Typeable,Generic) instance Binary AppendFile where data CloseAppend = CloseAppend FilePath deriving (Show,Typeable,Generic) instance Binary CloseAppend where -- Cast operations data Ping = Ping deriving (Typeable, Generic, Eq, Show) instance Binary Ping where -- --------------------------------------------------------------------- data State = ST { stAppends :: Map.Map FilePath Handle } deriving (Show) emptyState :: State emptyState = ST Map.empty -------------------------------------------------------------------------------- -- API -- -------------------------------------------------------------------------------- hroq_handle_pool_server :: Process () hroq_handle_pool_server = do logm $ "HroqHandlePool:hroq_handle_pool_server entered" start_handle_pool_server hroq_handle_pool_server_pid :: Process ProcessId hroq_handle_pool_server_pid = getServerPid -- --------------------------------------------------------------------- append :: ProcessId -> FilePath -> B.ByteString -> Process () append pid filename val = call pid (AppendFile filename val) closeAppend :: ProcessId -> FilePath -> Process () closeAppend pid filename = call pid (CloseAppend filename) ping :: Process () ping = do pid <- getServerPid cast pid Ping -- --------------------------------------------------------------------- getServerPid :: Process ProcessId getServerPid = do mpid <- whereis hroqHandlePoolServerProcessName case mpid of Just pid -> return pid Nothing -> do logm "HroqHandlePool:getServerPid failed" error "HroqHandlePool:blow up" -- ------------------------------------- hroqHandlePoolServerProcessName :: String hroqHandlePoolServerProcessName = "HroqHandlePool" -- --------------------------------------------------------------------- start_handle_pool_server :: Process () start_handle_pool_server = do logm $ "HroqHandlePool:start_handle_pool_server entered" self <- getSelfPid register hroqHandlePoolServerProcessName self serve () initFunc serverDefinition where initFunc :: InitHandler () State initFunc _ = do logm $ "HroqHandlePool:start.initFunc" return $ InitOk emptyState mONITOR_INTERVAL_MS serverDefinition :: ProcessDefinition State serverDefinition = defaultProcess { apiHandlers = [ handleCall handleAppendFileCall , handleCall handleCloseAppendCall -- , handleCast handlePublishConsumerStatsCast , handleCast (\s Ping -> do {logm $ "HroqHandlePool:ping"; continue s }) ] , infoHandlers = [ handleInfo handleInfoProcessMonitorNotification ] , timeoutHandler = handleTimeout , shutdownHandler = \_ reason -> do { logm $ "HroqHandlePool terminateHandler:" ++ (show reason) } } :: ProcessDefinition State -- --------------------------------------------------------------------- -- Implementation -- --------------------------------------------------------------------- -- --------------------------------------------------------------------- handleAppendFileCall :: State -> AppendFile -> Process (ProcessReply () State) handleAppendFileCall st (AppendFile fileName val) = do -- logm $ "HroqHandlePool.handleAppendFileCall entered for :" ++ show fileName (st',h) <- case Map.lookup fileName (stAppends st) of Just h -> do -- logm $ "HroqHandlePool.handleAppendFileCall re-using handle" return (st,h) Nothing -> do logm $ "HroqHandlePool.handleAppendFileCall opening file:" ++ show fileName h <- liftIO $ safeOpenFile fileName AppendMode return (st { stAppends = Map.insert fileName h (stAppends st) },h) -- logm $ "HroqHandlePool.handleAppendFileCall writing:" ++ show val liftIO $ B.hPut h val -- >> hFlush h reply () st' -- --------------------------------------------------------------------- handleCloseAppendCall :: State -> CloseAppend -> Process (ProcessReply () State) handleCloseAppendCall st (CloseAppend fileName) = do logm $ "HroqHandlePool.handleCloseAppendCall entered for :" ++ show fileName st' <- case Map.lookup fileName (stAppends st) of Just h -> do liftIO $ hClose h return st { stAppends = Map.delete fileName (stAppends st) } Nothing -> do return st reply () st' -- --------------------------------------------------------------------- -- |Try to open a file in the given mode, creating any required -- directory structure if necessary safeOpenFile :: FilePath -> IOMode -> IO Handle safeOpenFile filename mode = handle handler (openBinaryFile filename mode) where handler e | isDoesNotExistError e = do createDirectoryIfMissing True $ take (1+(last $ elemIndices '/' filename)) filename -- maybe the path does not exist safeOpenFile filename mode | otherwise= if ("invalid" `isInfixOf` ioeGetErrorString e) then error $ "writeResource: " ++ show e ++ " defPath and/or keyResource are not suitable for a file path" else do hPutStrLn stderr $ "defaultWriteResource: " ++ show e ++ " in file: " ++ filename ++ " retrying" safeOpenFile filename mode -- --------------------------------------------------------------------- handleTimeout :: TimeoutHandler State handleTimeout st currDelay = do logm $ "HroqHandlePool:handleTimeout entered" mapM_ (\h -> liftIO $ hClose h) $ Map.elems (stAppends st) timeoutAfter currDelay (st {stAppends = Map.empty }) -- timeoutAfter currDelay st -- --------------------------------------------------------------------- handleShutdown :: ShutdownHandler State handleShutdown st reason = do logm $ "HroqHandlePool.handleShutdown called for:" ++ show reason return () -- --------------------------------------------------------------------- handleInfoProcessMonitorNotification :: State -> ProcessMonitorNotification -> Process (ProcessAction State) handleInfoProcessMonitorNotification st n@(ProcessMonitorNotification ref _pid _reason) = do logm $ "HroqHandlePool:handleInfoProcessMonitorNotification called with: " ++ show n let m = stAppends st {- case Map.lookup ref m of Just key -> continue st { stMdict = Map.delete ref m , stGdict = Map.delete key g } Nothing -> continue st -} continue st -- --------------------------------------------------------------------- -- NOTE: the TH crap has to be a the end, as it can only see the stuff lexically before it in the file $(remotable [ 'hroq_handle_pool_server ]) hroq_handle_pool_server_closure :: Closure (Process ()) hroq_handle_pool_server_closure = ( $(mkStaticClosure 'hroq_handle_pool_server)) -- EOF
alanz/hroq
src/Data/Concurrent/Queue/Roq/HandlePool.hs
bsd-3-clause
8,601
0
19
1,615
1,584
832
752
141
2
-- -- An AST format for generated code in imperative languages -- module SyntaxImp -- Uncomment the below line to expose all top level symbols for -- repl testing {- () -- -} where data IId = IId [String] (Maybe Int) deriving( Show ) data IAnnTy = INoAnn ITy | IMut ITy -- things are immutable by default deriving( Show ) data ITy = IBool | IArr IAnnTy (Maybe Int) | IByte | IPtr IAnnTy | IStruct IId deriving( Show ) -- Id, type pair data IAnnId = IAnnId IId IAnnTy deriving( Show ) data IDecl = IFun IId [IAnnId] IAnnTy [IStmt] | IStructure IId [IAnnId] deriving( Show ) data IStmt = IReturn IId deriving( Show )
ethanpailes/bbc
src/SyntaxImp.hs
bsd-3-clause
707
0
8
208
172
102
70
19
0
{-# LANGUAGE DeriveGeneric #-} -- | This is a wrapper around IO that permits SMT queries module Language.Fixpoint.Solver.Monad ( -- * Type SolveM -- * Execution , runSolverM -- * Get Binds , getBinds -- * SMT Query , filterValid -- * Debug , Stats , tickIter , stats , numIter ) where import Control.DeepSeq import GHC.Generics import Language.Fixpoint.Utils.Progress import Language.Fixpoint.Misc (groupList) import Language.Fixpoint.Types.Config (Config, solver, real) import qualified Language.Fixpoint.Types as F import qualified Language.Fixpoint.Types.Errors as E import qualified Language.Fixpoint.Smt.Theories as Thy import Language.Fixpoint.Types.PrettyPrint import Language.Fixpoint.Smt.Interface import Language.Fixpoint.Solver.Validate import Language.Fixpoint.Solver.Solution import Data.Maybe (isJust, catMaybes) import Text.PrettyPrint.HughesPJ (text) import Control.Monad.State.Strict import qualified Data.HashMap.Strict as M --------------------------------------------------------------------------- -- | Solver Monadic API --------------------------------------------------- --------------------------------------------------------------------------- type SolveM = StateT SolverState IO data SolverState = SS { ssCtx :: !Context -- ^ SMT Solver Context , ssBinds :: !F.BindEnv -- ^ All variables and types , ssStats :: !Stats -- ^ Solver Statistics } data Stats = Stats { numCstr :: !Int -- ^ # Horn Constraints , numIter :: !Int -- ^ # Refine Iterations , numBrkt :: !Int -- ^ # smtBracket calls (push/pop) , numChck :: !Int -- ^ # smtCheckUnsat calls , numVald :: !Int -- ^ # times SMT said RHS Valid } deriving (Show, Generic) instance NFData Stats stats0 :: F.GInfo c b -> Stats stats0 fi = Stats nCs 0 0 0 0 where nCs = M.size $ F.cm fi instance PTable Stats where ptable s = DocTable [ (text "# Constraints" , pprint (numCstr s)) , (text "# Refine Iterations" , pprint (numIter s)) , (text "# SMT Push & Pops" , pprint (numBrkt s)) , (text "# SMT Queries (Valid)" , pprint (numVald s)) , (text "# SMT Queries (Total)" , pprint (numChck s)) ] --------------------------------------------------------------------------- runSolverM :: Config -> F.GInfo c b -> Int -> SolveM a -> IO a --------------------------------------------------------------------------- runSolverM cfg fi t act = do ctx <- makeContext (not $ real cfg) (solver cfg) file fst <$> runStateT (declare fi >> act) (SS ctx be $ stats0 fi) where be = F.bs fi file = F.fileName fi -- (inFile cfg) --------------------------------------------------------------------------- getBinds :: SolveM F.BindEnv --------------------------------------------------------------------------- getBinds = ssBinds <$> get --------------------------------------------------------------------------- getIter :: SolveM Int --------------------------------------------------------------------------- getIter = numIter . ssStats <$> get --------------------------------------------------------------------------- incIter, incBrkt :: SolveM () --------------------------------------------------------------------------- incIter = modifyStats $ \s -> s {numIter = 1 + numIter s} incBrkt = modifyStats $ \s -> s {numBrkt = 1 + numBrkt s} --------------------------------------------------------------------------- incChck, incVald :: Int -> SolveM () --------------------------------------------------------------------------- incChck n = modifyStats $ \s -> s {numChck = n + numChck s} incVald n = modifyStats $ \s -> s {numVald = n + numVald s} withContext :: (Context -> IO a) -> SolveM a withContext k = (lift . k) =<< getContext getContext :: SolveM Context getContext = ssCtx <$> get modifyStats :: (Stats -> Stats) -> SolveM () modifyStats f = modify $ \s -> s { ssStats = f (ssStats s) } --------------------------------------------------------------------------- -- | SMT Interface -------------------------------------------------------- --------------------------------------------------------------------------- filterValid :: F.Pred -> Cand a -> SolveM [a] --------------------------------------------------------------------------- filterValid p qs = do qs' <- withContext $ \me -> smtBracket me $ filterValid_ p qs me -- stats incBrkt incChck (length qs) incVald (length qs') return qs' filterValid_ :: F.Pred -> Cand a -> Context -> IO [a] filterValid_ p qs me = catMaybes <$> do smtAssert me p forM qs $ \(q, x) -> smtBracket me $ do smtAssert me (F.PNot q) valid <- smtCheckUnsat me return $ if valid then Just x else Nothing --------------------------------------------------------------------------- declare :: F.GInfo c a -> SolveM () --------------------------------------------------------------------------- declare fi = withContext $ \me -> do xts <- either E.die return $ declSymbols fi let ess = declLiterals fi forM_ xts $ uncurry $ smtDecl me forM_ ess $ smtDistinct me declLiterals :: F.GInfo c a -> [[F.Expr]] declLiterals fi = [es | (_, es) <- tess ] where notFun = not . F.isFunctionSortedReft . (`F.RR` F.trueReft) tess = groupList [(t, F.expr x) | (x, t) <- F.toListSEnv $ F.lits fi, notFun t] declSymbols :: F.GInfo c a -> Either E.Error [(F.Symbol, F.Sort)] declSymbols = fmap dropThy . symbolSorts where dropThy = filter (not . isThy . fst) isThy = isJust . Thy.smt2Symbol --------------------------------------------------------------------------- stats :: SolveM Stats --------------------------------------------------------------------------- stats = ssStats <$> get --------------------------------------------------------------------------- tickIter :: Bool -> SolveM Int --------------------------------------------------------------------------- tickIter newScc = progIter newScc >> incIter >> getIter progIter :: Bool -> SolveM () progIter newScc = lift $ when newScc progressTick
gridaphobe/liquid-fixpoint
src/Language/Fixpoint/Solver/Monad.hs
bsd-3-clause
6,560
0
16
1,514
1,550
838
712
122
2
{-# LANGUAGE OverloadedStrings #-} module TW.Utils where import Data.Char import qualified Data.Text as T capitalizeText :: T.Text -> T.Text capitalizeText = T.pack . go . T.unpack where go (x:xs) = toUpper x : xs go [] = [] uncapitalizeText :: T.Text -> T.Text uncapitalizeText = T.pack . go . T.unpack where go (x:xs) = toLower x : xs go [] = [] makeSafePrefixedFieldName :: T.Text -> T.Text makeSafePrefixedFieldName = T.filter isAlphaNum
typed-wire/typed-wire
src/TW/Utils.hs
mit
490
0
9
119
175
94
81
16
2
{-# LANGUAGE DeriveAnyClass, TemplateHaskell, PostfixOperators, LambdaCase, OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-type-defaults #-} {-# OPTIONS_GHC -O0 -fno-cse -fno-full-laziness #-} -- preserve "lexical" sharing for observed sharing module Commands.Plugins.Spiros.Act.Grammar where import Commands.Plugins.Spiros.Act.Types import Commands.Plugins.Spiros.Edit import Commands.Plugins.Spiros.Number import Commands.Plugins.Spiros.Keys import Commands.Mixins.DNS13OSX9 import Control.Applicative acts = 'acts <=> ActsRW <$> (number-?-1) <*> act act = 'act <=> empty -- boilerplate (mostly) <|> KeyRiff_ <$> keyriff --TODO <|> Click_ <$> click <|> Edit_ <$> edit <|> Move_ <$> move -- acts = 'acts -- <=> ActRW <$> (number-?-1) <*> actRW -- <|> ActRO <$> actRO -- actRO = 'actRO <=> empty -- TODO -- actRW = 'actRW <=> empty -- <|> act
sboosali/commands-spiros
config/Commands/Plugins/Spiros/Act/Grammar.hs
gpl-2.0
962
0
11
197
120
79
41
16
1
import System.IO import System.Environment import System.IO.Unsafe import Data.List import Data.List (intercalate) import Data.Char -- Returns a list with all of the lines from the XML file -- I'm just feeding it a file name for now read_file :: String -> [String] read_file fileName = do let file = unsafePerformIO . readFile $ fileName lines file -- Breaks down subsections into their individual items -- Subsection heading is the first item in the list it returns item_breakdown :: [String] -> [String] -> Int -> ([String], Int) item_breakdown [] elementList count = (elementList, count) item_breakdown [x] elementList count = do -- if the element is a new subsection header or a newline, then we know that it is not a subsection item if (length x > 0) then do let a = head x if (a == '#' || a == ' ') then do (elementList, count) -- otherwise, it is an item to be included in the subsection list else do let newCount = count + 1 let newElementList = elementList ++ [x] (newElementList, newCount) else (elementList, count) item_breakdown remaining elementList count = do if (length remaining > 0) then do let h = head remaining let t = tail remaining if (length h > 0) then do let a = head h if a == '#' then (elementList, count) else do let newCount = count+1 let newElementList = elementList ++ [h] let i = item_breakdown t newElementList newCount let (a, b) = i (a, b) else (elementList, count) else (elementList, count) breakdown :: [String] -> [[String]] -> [[String]] breakdown [] buffer = buffer breakdown [h] buffer = do buffer ++ [[h]] breakdown fileData buffer = do if (length fileData > 0) then do let h = head fileData let t = tail fileData if (length h > 0) then do let a = head h if a == '#' -- if we encounter a sublist, we must extract all the elements that belong to the sublist then do -- item_breakdown gets all of the elements belonging to the sublist and returns them -- it also returns a count of how many items were in that list, so that we know how many to remove from t before recursing again let (sublist, count) = item_breakdown t [h] 0 -- We don't want the part of the list with the old items, so we leave them out let (_, remaining) = splitAt count t -- newElement is the "subsection" that we're adding to the buffer. I -- It consists of the name of the subsection at list[0], and the items belonging to it from list[1]-[n] let newBuffer = buffer ++ [sublist] breakdown remaining newBuffer else if a == ' ' then do -- if it's just a blank line in the text, we don't add that as an element in the list and just move on breakdown t buffer else do -- else, it's a subsection-less element -- we will probably want more elses in here for error-handling, but for now, I'm just assuming these 3 possibilities let newBuffer = buffer ++ [[h]] breakdown t newBuffer else breakdown t buffer else buffer main = do -- Takes in the text file with the list of coordinates, and returns a tuple with the list of coordinates, -- and an int, which is the number of evolutions to print args <- getArgs let [file] = args let items = read_file (file) if (length items > 0) then do let buffer = breakdown (tail items) [] let a = head items let printList = [[a]] ++ buffer print (printList) else print ("gaahhhhhh")
nadyac/todo-list
src/readMD.hs
gpl-3.0
5,911
0
22
3,284
890
461
429
84
6
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Data.Science.CF import Options.Generic data Opts = Suggest { dataFile :: String, user :: String} -- the recommendation | Blah { bob :: String } deriving (Generic, Show) instance ParseRecord Opts toSample :: String -> Sample String String toSample line = error "lol" doSuggest :: String -> String -> IO () doSuggest file user = do contents <- readFile file let lines' = lines contents let samples = map toSample lines' let userSample = findUser user samples let recs = recommend euclidean userSample samples mapM_ printRec recs where printRec (item, sc) = putStrLn ("Item: " ++ item ++ ", Score: " ++ (show sc)) main :: IO () main = do opts <- getRecord "dsci" case opts of (Suggest f u) -> doSuggest f u _ -> putStrLn "What?"
akisystems/haskell-dsci
app/Main.hs
gpl-3.0
897
0
11
220
295
148
147
26
2
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>ViewState</title> <maps> <homeID>viewstate</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
denniskniep/zap-extensions
addOns/viewstate/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs
apache-2.0
960
77
66
155
404
205
199
-1
-1
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Data/Streaming/Zlib.hs" #-} {-# LANGUAGE DeriveDataTypeable #-} -- | This is a middle-level wrapper around the zlib C API. It allows you to -- work fully with bytestrings and not touch the FFI at all, but is still -- low-level enough to allow you to implement high-level abstractions such as -- enumerators. Significantly, it does not use lazy IO. -- -- You'll probably need to reference the docs a bit to understand the -- WindowBits parameters below, but a basic rule of thumb is 15 is for zlib -- compression, and 31 for gzip compression. -- -- A simple streaming compressor in pseudo-code would look like: -- -- > def <- initDeflate ... -- > popper <- feedDeflate def rawContent -- > pullPopper popper -- > ... -- > finishDeflate def sendCompressedData -- -- You can see a more complete example is available in the included -- file-test.hs. module Data.Streaming.Zlib ( -- * Inflate Inflate , initInflate , initInflateWithDictionary , feedInflate , finishInflate , flushInflate , getUnusedInflate , isCompleteInflate -- * Deflate , Deflate , initDeflate , initDeflateWithDictionary , feedDeflate , finishDeflate , flushDeflate , fullFlushDeflate -- * Data types , WindowBits (..) , defaultWindowBits , ZlibException (..) , Popper , PopperRes (..) ) where import Data.Streaming.Zlib.Lowlevel import Foreign.ForeignPtr import Foreign.C.Types import Data.ByteString.Unsafe import Codec.Compression.Zlib (WindowBits(WindowBits), defaultWindowBits) import qualified Data.ByteString as S import Data.ByteString.Lazy.Internal (defaultChunkSize) import Data.Typeable (Typeable) import Control.Exception (Exception) import Control.Monad (when) import Data.IORef type ZStreamPair = (ForeignPtr ZStreamStruct, ForeignPtr CChar) -- | The state of an inflation (eg, decompression) process. All allocated -- memory is automatically reclaimed by the garbage collector. -- Also can contain the inflation dictionary that is used for decompression. data Inflate = Inflate ZStreamPair (IORef S.ByteString) -- last ByteString fed in, needed for getUnusedInflate (IORef Bool) -- set True when zlib indicates that inflation is complete (Maybe S.ByteString) -- dictionary -- | The state of a deflation (eg, compression) process. All allocated memory -- is automatically reclaimed by the garbage collector. newtype Deflate = Deflate ZStreamPair -- | Exception that can be thrown from the FFI code. The parameter is the -- numerical error code from the zlib library. Quoting the zlib.h file -- directly: -- -- * #define Z_OK 0 -- -- * #define Z_STREAM_END 1 -- -- * #define Z_NEED_DICT 2 -- -- * #define Z_ERRNO (-1) -- -- * #define Z_STREAM_ERROR (-2) -- -- * #define Z_DATA_ERROR (-3) -- -- * #define Z_MEM_ERROR (-4) -- -- * #define Z_BUF_ERROR (-5) -- -- * #define Z_VERSION_ERROR (-6) data ZlibException = ZlibException Int deriving (Show, Typeable) instance Exception ZlibException -- | Some constants for the error codes, used internally zStreamEnd :: CInt zStreamEnd = 1 zNeedDict :: CInt zNeedDict = 2 zBufError :: CInt zBufError = -5 -- | Initialize an inflation process with the given 'WindowBits'. You will need -- to call 'feedInflate' to feed compressed data to this and -- 'finishInflate' to extract the final chunk of decompressed data. initInflate :: WindowBits -> IO Inflate initInflate w = do zstr <- zstreamNew inflateInit2 zstr w fzstr <- newForeignPtr c_free_z_stream_inflate zstr fbuff <- mallocForeignPtrBytes defaultChunkSize withForeignPtr fbuff $ \buff -> c_set_avail_out zstr buff $ fromIntegral defaultChunkSize lastBS <- newIORef S.empty complete <- newIORef False return $ Inflate (fzstr, fbuff) lastBS complete Nothing -- | Initialize an inflation process with the given 'WindowBits'. -- Unlike initInflate a dictionary for inflation is set which must -- match the one set during compression. initInflateWithDictionary :: WindowBits -> S.ByteString -> IO Inflate initInflateWithDictionary w bs = do zstr <- zstreamNew inflateInit2 zstr w fzstr <- newForeignPtr c_free_z_stream_inflate zstr fbuff <- mallocForeignPtrBytes defaultChunkSize withForeignPtr fbuff $ \buff -> c_set_avail_out zstr buff $ fromIntegral defaultChunkSize lastBS <- newIORef S.empty complete <- newIORef False return $ Inflate (fzstr, fbuff) lastBS complete (Just bs) -- | Initialize a deflation process with the given compression level and -- 'WindowBits'. You will need to call 'feedDeflate' to feed uncompressed -- data to this and 'finishDeflate' to extract the final chunks of compressed -- data. initDeflate :: Int -- ^ Compression level -> WindowBits -> IO Deflate initDeflate level w = do zstr <- zstreamNew deflateInit2 zstr level w 8 StrategyDefault fzstr <- newForeignPtr c_free_z_stream_deflate zstr fbuff <- mallocForeignPtrBytes defaultChunkSize withForeignPtr fbuff $ \buff -> c_set_avail_out zstr buff $ fromIntegral defaultChunkSize return $ Deflate (fzstr, fbuff) -- | Initialize an deflation process with the given compression level and -- 'WindowBits'. -- Unlike initDeflate a dictionary for deflation is set. initDeflateWithDictionary :: Int -- ^ Compression level -> S.ByteString -- ^ Deflate dictionary -> WindowBits -> IO Deflate initDeflateWithDictionary level bs w = do zstr <- zstreamNew deflateInit2 zstr level w 8 StrategyDefault fzstr <- newForeignPtr c_free_z_stream_deflate zstr fbuff <- mallocForeignPtrBytes defaultChunkSize unsafeUseAsCStringLen bs $ \(cstr, len) -> do c_call_deflate_set_dictionary zstr cstr $ fromIntegral len withForeignPtr fbuff $ \buff -> c_set_avail_out zstr buff $ fromIntegral defaultChunkSize return $ Deflate (fzstr, fbuff) -- | Feed the given 'S.ByteString' to the inflater. Return a 'Popper', -- an IO action that returns the decompressed data a chunk at a time. -- The 'Popper' must be called to exhaustion before using the 'Inflate' -- object again. -- -- Note that this function automatically buffers the output to -- 'defaultChunkSize', and therefore you won't get any data from the popper -- until that much decompressed data is available. After you have fed all of -- the compressed data to this function, you can extract your final chunk of -- decompressed data using 'finishInflate'. feedInflate :: Inflate -> S.ByteString -> IO Popper feedInflate (Inflate (fzstr, fbuff) lastBS complete inflateDictionary) bs = do -- Write the BS to lastBS for use by getUnusedInflate. This is -- theoretically unnecessary, since we could just grab the pointer from the -- fzstr when needed. However, in that case, we wouldn't be holding onto a -- reference to the ForeignPtr, so the GC may decide to collect the -- ByteString in the interim. writeIORef lastBS bs withForeignPtr fzstr $ \zstr -> unsafeUseAsCStringLen bs $ \(cstr, len) -> c_set_avail_in zstr cstr $ fromIntegral len return $ drain fbuff fzstr (Just bs) inflate False where inflate zstr = do res <- c_call_inflate_noflush zstr res2 <- if (res == zNeedDict) then maybe (return zNeedDict) (\dict -> (unsafeUseAsCStringLen dict $ \(cstr, len) -> do c_call_inflate_set_dictionary zstr cstr $ fromIntegral len c_call_inflate_noflush zstr)) inflateDictionary else return res when (res2 == zStreamEnd) (writeIORef complete True) return res2 -- | An IO action that returns the next chunk of data, returning 'Nothing' when -- there is no more data to be popped. type Popper = IO PopperRes data PopperRes = PRDone | PRNext !S.ByteString | PRError !ZlibException deriving (Show, Typeable) -- | Ensure that the given @ByteString@ is not deallocated. keepAlive :: Maybe S.ByteString -> IO a -> IO a keepAlive Nothing = id keepAlive (Just bs) = unsafeUseAsCStringLen bs . const drain :: ForeignPtr CChar -> ForeignPtr ZStreamStruct -> Maybe S.ByteString -> (ZStream' -> IO CInt) -> Bool -> Popper drain fbuff fzstr mbs func isFinish = withForeignPtr fzstr $ \zstr -> keepAlive mbs $ do res <- func zstr if res < 0 && res /= zBufError then return $ PRError $ ZlibException $ fromIntegral res else do avail <- c_get_avail_out zstr let size = defaultChunkSize - fromIntegral avail toOutput = avail == 0 || (isFinish && size /= 0) if toOutput then withForeignPtr fbuff $ \buff -> do bs <- S.packCStringLen (buff, size) c_set_avail_out zstr buff $ fromIntegral defaultChunkSize return $ PRNext bs else return PRDone -- | As explained in 'feedInflate', inflation buffers your decompressed -- data. After you call 'feedInflate' with your last chunk of compressed -- data, you will likely have some data still sitting in the buffer. This -- function will return it to you. finishInflate :: Inflate -> IO S.ByteString finishInflate (Inflate (fzstr, fbuff) _ _ _) = withForeignPtr fzstr $ \zstr -> withForeignPtr fbuff $ \buff -> do avail <- c_get_avail_out zstr let size = defaultChunkSize - fromIntegral avail bs <- S.packCStringLen (buff, size) c_set_avail_out zstr buff $ fromIntegral defaultChunkSize return bs -- | Flush the inflation buffer. Useful for interactive application. -- -- This is actually a synonym for 'finishInflate'. It is provided for its more -- semantic name. -- -- Since 0.0.3 flushInflate :: Inflate -> IO S.ByteString flushInflate = finishInflate -- | Retrieve any data remaining after inflating. For more information on motivation, see: -- -- <https://github.com/fpco/streaming-commons/issues/20> -- -- Since 0.1.11 getUnusedInflate :: Inflate -> IO S.ByteString getUnusedInflate (Inflate (fzstr, _) ref _ _) = do bs <- readIORef ref len <- withForeignPtr fzstr c_get_avail_in return $ S.drop (S.length bs - fromIntegral len) bs -- | Returns True if the inflater has reached end-of-stream, or False if -- it is still expecting more data. -- -- Since 0.1.18 isCompleteInflate :: Inflate -> IO Bool isCompleteInflate (Inflate _ _ complete _) = readIORef complete -- | Feed the given 'S.ByteString' to the deflater. Return a 'Popper', -- an IO action that returns the compressed data a chunk at a time. -- The 'Popper' must be called to exhaustion before using the 'Deflate' -- object again. -- -- Note that this function automatically buffers the output to -- 'defaultChunkSize', and therefore you won't get any data from the popper -- until that much compressed data is available. After you have fed all of the -- decompressed data to this function, you can extract your final chunks of -- compressed data using 'finishDeflate'. feedDeflate :: Deflate -> S.ByteString -> IO Popper feedDeflate (Deflate (fzstr, fbuff)) bs = do withForeignPtr fzstr $ \zstr -> unsafeUseAsCStringLen bs $ \(cstr, len) -> do c_set_avail_in zstr cstr $ fromIntegral len return $ drain fbuff fzstr (Just bs) c_call_deflate_noflush False -- | As explained in 'feedDeflate', deflation buffers your compressed -- data. After you call 'feedDeflate' with your last chunk of uncompressed -- data, use this to flush the rest of the data and signal end of input. finishDeflate :: Deflate -> Popper finishDeflate (Deflate (fzstr, fbuff)) = drain fbuff fzstr Nothing c_call_deflate_finish True -- | Flush the deflation buffer. Useful for interactive application. -- Internally this passes Z_SYNC_FLUSH to the zlib library. -- -- Unlike 'finishDeflate', 'flushDeflate' does not signal end of input, -- meaning you can feed more uncompressed data afterward. -- -- Since 0.0.3 flushDeflate :: Deflate -> Popper flushDeflate (Deflate (fzstr, fbuff)) = drain fbuff fzstr Nothing c_call_deflate_flush True -- | Full flush the deflation buffer. Useful for interactive -- applications where previously streamed data may not be -- available. Using `fullFlushDeflate` too often can seriously degrade -- compression. Internally this passes Z_FULL_FLUSH to the zlib -- library. -- -- Like 'flushDeflate', 'fullFlushDeflate' does not signal end of input, -- meaning you can feed more uncompressed data afterward. -- -- Since 0.1.5 fullFlushDeflate :: Deflate -> Popper fullFlushDeflate (Deflate (fzstr, fbuff)) = drain fbuff fzstr Nothing c_call_deflate_full_flush True
phischu/fragnix
tests/packages/scotty/Data.Streaming.Zlib.hs
bsd-3-clause
12,910
0
20
2,839
2,084
1,107
977
184
3
----------------------------------------------------------------------------- -- | -- Module : Distribution.ParseUtils -- Copyright : (c) The University of Glasgow 2004 -- -- Maintainer : [email protected] -- Stability : alpha -- Portability : portable -- -- Utilities for parsing PackageDescription and InstalledPackageInfo. {- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the University nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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 UnitTest.Distribution.ParseUtils where import Distribution.ParseUtils import Distribution.Compiler (CompilerFlavor, parseCompilerFlavorCompat) import Distribution.License (License) import Distribution.Version import Distribution.Package ( parsePackageName ) import Distribution.Compat.ReadP as ReadP hiding (get) import Distribution.Simple.Utils (intercalate) import Language.Haskell.Extension (Extension) import Text.PrettyPrint hiding (braces) import Data.Char (isSpace, isUpper, toLower, isAlphaNum, isSymbol, isDigit) import Data.Maybe (fromMaybe) import Data.Tree as Tree (Tree(..), flatten) import Test.HUnit (Test(..), assertBool, Assertion, runTestTT, Counts, assertEqual) import IO import System.Environment ( getArgs ) import Control.Monad ( zipWithM_ ) ------------------------------------------------------------------------------ -- TESTING test_readFields = case readFields testFile of ParseOk _ x -> x == expectedResult _ -> False where testFile = unlines $ [ "Cabal-version: 3" , "" , "Description: This is a test file " , " with a description longer than two lines. " , "if os(windows) {" , " License: You may not use this software" , " ." , " If you do use this software you will be seeked and destroyed." , "}" , "if os(linux) {" , " Main-is: foo1 " , "}" , "" , "if os(vista) {" , " executable RootKit {" , " Main-is: DRMManager.hs" , " }" , "} else {" , " executable VistaRemoteAccess {" , " Main-is: VCtrl" , "}}" , "" , "executable Foo-bar {" , " Main-is: Foo.hs" , "}" ] expectedResult = [ F 1 "cabal-version" "3" , F 3 "description" "This is a test file\nwith a description longer than two lines." , IfBlock 5 "os(windows) " [ F 6 "license" "You may not use this software\n\nIf you do use this software you will be seeked and destroyed." ] [] , IfBlock 10 "os(linux) " [ F 11 "main-is" "foo1" ] [ ] , IfBlock 14 "os(vista) " [ Section 15 "executable" "RootKit " [ F 16 "main-is" "DRMManager.hs"] ] [ Section 19 "executable" "VistaRemoteAccess " [F 20 "main-is" "VCtrl"] ] , Section 23 "executable" "Foo-bar " [F 24 "main-is" "Foo.hs"] ] test_readFieldsCompat' = case test_readFieldsCompat of ParseOk _ fs -> mapM_ (putStrLn . show) fs x -> putStrLn $ "Failed: " ++ show x test_readFieldsCompat = readFields testPkgDesc where testPkgDesc = unlines [ "-- Required", "Name: Cabal", "Version: 0.1.1.1.1-rain", "License: LGPL", "License-File: foo", "Copyright: Free Text String", "Cabal-version: >1.1.1", "-- Optional - may be in source?", "Author: Happy Haskell Hacker", "Homepage: http://www.haskell.org/foo", "Package-url: http://www.haskell.org/foo", "Synopsis: a nice package!", "Description: a really nice package!", "Category: tools", "buildable: True", "CC-OPTIONS: -g -o", "LD-OPTIONS: -BStatic -dn", "Frameworks: foo", "Tested-with: GHC", "Stability: Free Text String", "Build-Depends: haskell-src, HUnit>=1.0.0-rain", "Other-Modules: Distribution.Package, Distribution.Version,", " Distribution.Simple.GHCPackageConfig", "Other-files: file1, file2", "Extra-Tmp-Files: file1, file2", "C-Sources: not/even/rain.c, such/small/hands", "HS-Source-Dirs: src, src2", "Exposed-Modules: Distribution.Void, Foo.Bar", "Extensions: OverlappingInstances, TypeSynonymInstances", "Extra-Libraries: libfoo, bar, bang", "Extra-Lib-Dirs: \"/usr/local/libs\"", "Include-Dirs: your/slightest, look/will", "Includes: /easily/unclose, /me, \"funky, path\\\\name\"", "Install-Includes: /easily/unclose, /me, \"funky, path\\\\name\"", "GHC-Options: -fTH -fglasgow-exts", "Hugs-Options: +TH", "Nhc-Options: ", "Jhc-Options: ", "", "-- Next is an executable", "Executable: somescript", "Main-is: SomeFile.hs", "Other-Modules: Foo1, Util, Main", "HS-Source-Dir: scripts", "Extensions: OverlappingInstances", "GHC-Options: ", "Hugs-Options: ", "Nhc-Options: ", "Jhc-Options: " ] {- test' = do h <- openFile "../Cabal.cabal" ReadMode s <- hGetContents h let r = readFields s case r of ParseOk _ fs -> mapM_ (putStrLn . show) fs x -> putStrLn $ "Failed: " ++ show x putStrLn "===================" mapM_ (putStrLn . show) $ merge . zip [1..] . lines $ s hClose h -} -- ghc -DDEBUG --make Distribution/ParseUtils.hs -o test main :: IO () main = do inputFiles <- getArgs ok <- mapM checkResult inputFiles zipWithM_ summary inputFiles ok putStrLn $ show (length (filter not ok)) ++ " out of " ++ show (length ok) ++ " failed" where summary f True = return () summary f False = putStrLn $ f ++ " failed :-(" checkResult :: FilePath -> IO Bool checkResult inputFile = do file <- readTextFile inputFile case readFields file of ParseOk _ result -> do hPutStrLn stderr $ inputFile ++ " parses ok :-)" return True ParseFailed err -> do hPutStrLn stderr $ inputFile ++ " parse failed:" hPutStrLn stderr $ show err return False
IreneKnapp/Faction
libfaction/tests/UnitTest/Distribution/ParseUtils.hs
bsd-3-clause
7,904
4
15
2,318
943
532
411
138
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Compiler -- Copyright : Isaac Jones 2003-2004 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- -- This should be a much more sophisticated abstraction than it is. Currently -- it's just a bit of data about the compiler, like it's flavour and name and -- version. The reason it's just data is because currently it has to be in -- 'Read' and 'Show' so it can be saved along with the 'LocalBuildInfo'. The -- only interesting bit of info it contains is a mapping between language -- extensions and compiler command line flags. This module also defines a -- 'PackageDB' type which is used to refer to package databases. Most compilers -- only know about a single global package collection but GHC has a global and -- per-user one and it lets you create arbitrary other package databases. We do -- not yet fully support this latter feature. module Distribution.Simple.Compiler ( -- * Haskell implementations module Distribution.Compiler, Compiler(..), showCompilerId, showCompilerIdWithAbi, compilerFlavor, compilerVersion, compilerCompatFlavor, compilerCompatVersion, compilerInfo, -- * Support for package databases PackageDB(..), PackageDBStack, registrationPackageDB, absolutePackageDBPaths, absolutePackageDBPath, -- * Support for optimisation levels OptimisationLevel(..), flagToOptimisationLevel, -- * Support for debug info levels DebugInfoLevel(..), flagToDebugInfoLevel, -- * Support for language extensions Flag, languageToFlags, unsupportedLanguages, extensionsToFlags, unsupportedExtensions, parmakeSupported, reexportedModulesSupported, renamingPackageFlagsSupported, unifiedIPIDRequired, packageKeySupported, unitIdSupported, coverageSupported, profilingSupported, backpackSupported, arResponseFilesSupported, libraryDynDirSupported, -- * Support for profiling detail levels ProfDetailLevel(..), knownProfDetailLevels, flagToProfDetailLevel, showProfDetailLevel, ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Compiler import Distribution.Version import Distribution.Text import Language.Haskell.Extension import Distribution.Simple.Utils import qualified Data.Map as Map (lookup) import System.Directory (canonicalizePath) data Compiler = Compiler { compilerId :: CompilerId, -- ^ Compiler flavour and version. compilerAbiTag :: AbiTag, -- ^ Tag for distinguishing incompatible ABI's on the same -- architecture/os. compilerCompat :: [CompilerId], -- ^ Other implementations that this compiler claims to be -- compatible with. compilerLanguages :: [(Language, Flag)], -- ^ Supported language standards. compilerExtensions :: [(Extension, Flag)], -- ^ Supported extensions. compilerProperties :: Map String String -- ^ A key-value map for properties not covered by the above fields. } deriving (Eq, Generic, Typeable, Show, Read) instance Binary Compiler showCompilerId :: Compiler -> String showCompilerId = display . compilerId showCompilerIdWithAbi :: Compiler -> String showCompilerIdWithAbi comp = display (compilerId comp) ++ case compilerAbiTag comp of NoAbiTag -> [] AbiTag xs -> '-':xs compilerFlavor :: Compiler -> CompilerFlavor compilerFlavor = (\(CompilerId f _) -> f) . compilerId compilerVersion :: Compiler -> Version compilerVersion = (\(CompilerId _ v) -> v) . compilerId -- | Is this compiler compatible with the compiler flavour we're interested in? -- -- For example this checks if the compiler is actually GHC or is another -- compiler that claims to be compatible with some version of GHC, e.g. GHCJS. -- -- > if compilerCompatFlavor GHC compiler then ... else ... -- compilerCompatFlavor :: CompilerFlavor -> Compiler -> Bool compilerCompatFlavor flavor comp = flavor == compilerFlavor comp || flavor `elem` [ flavor' | CompilerId flavor' _ <- compilerCompat comp ] -- | Is this compiler compatible with the compiler flavour we're interested in, -- and if so what version does it claim to be compatible with. -- -- For example this checks if the compiler is actually GHC-7.x or is another -- compiler that claims to be compatible with some GHC-7.x version. -- -- > case compilerCompatVersion GHC compiler of -- > Just (Version (7:_)) -> ... -- > _ -> ... -- compilerCompatVersion :: CompilerFlavor -> Compiler -> Maybe Version compilerCompatVersion flavor comp | compilerFlavor comp == flavor = Just (compilerVersion comp) | otherwise = listToMaybe [ v | CompilerId fl v <- compilerCompat comp, fl == flavor ] compilerInfo :: Compiler -> CompilerInfo compilerInfo c = CompilerInfo (compilerId c) (compilerAbiTag c) (Just . compilerCompat $ c) (Just . map fst . compilerLanguages $ c) (Just . map fst . compilerExtensions $ c) -- ------------------------------------------------------------ -- * Package databases -- ------------------------------------------------------------ -- |Some compilers have a notion of a database of available packages. -- For some there is just one global db of packages, other compilers -- support a per-user or an arbitrary db specified at some location in -- the file system. This can be used to build isloated environments of -- packages, for example to build a collection of related packages -- without installing them globally. -- data PackageDB = GlobalPackageDB | UserPackageDB | SpecificPackageDB FilePath deriving (Eq, Generic, Ord, Show, Read) instance Binary PackageDB -- | We typically get packages from several databases, and stack them -- together. This type lets us be explicit about that stacking. For example -- typical stacks include: -- -- > [GlobalPackageDB] -- > [GlobalPackageDB, UserPackageDB] -- > [GlobalPackageDB, SpecificPackageDB "package.conf.inplace"] -- -- Note that the 'GlobalPackageDB' is invariably at the bottom since it -- contains the rts, base and other special compiler-specific packages. -- -- We are not restricted to using just the above combinations. In particular -- we can use several custom package dbs and the user package db together. -- -- When it comes to writing, the top most (last) package is used. -- type PackageDBStack = [PackageDB] -- | Return the package that we should register into. This is the package db at -- the top of the stack. -- registrationPackageDB :: PackageDBStack -> PackageDB registrationPackageDB [] = error "internal error: empty package db set" registrationPackageDB dbs = last dbs -- | Make package paths absolute absolutePackageDBPaths :: PackageDBStack -> NoCallStackIO PackageDBStack absolutePackageDBPaths = traverse absolutePackageDBPath absolutePackageDBPath :: PackageDB -> NoCallStackIO PackageDB absolutePackageDBPath GlobalPackageDB = return GlobalPackageDB absolutePackageDBPath UserPackageDB = return UserPackageDB absolutePackageDBPath (SpecificPackageDB db) = SpecificPackageDB `liftM` canonicalizePath db -- ------------------------------------------------------------ -- * Optimisation levels -- ------------------------------------------------------------ -- | Some compilers support optimising. Some have different levels. -- For compilers that do not the level is just capped to the level -- they do support. -- data OptimisationLevel = NoOptimisation | NormalOptimisation | MaximumOptimisation deriving (Bounded, Enum, Eq, Generic, Read, Show) instance Binary OptimisationLevel flagToOptimisationLevel :: Maybe String -> OptimisationLevel flagToOptimisationLevel Nothing = NormalOptimisation flagToOptimisationLevel (Just s) = case reads s of [(i, "")] | i >= fromEnum (minBound :: OptimisationLevel) && i <= fromEnum (maxBound :: OptimisationLevel) -> toEnum i | otherwise -> error $ "Bad optimisation level: " ++ show i ++ ". Valid values are 0..2" _ -> error $ "Can't parse optimisation level " ++ s -- ------------------------------------------------------------ -- * Debug info levels -- ------------------------------------------------------------ -- | Some compilers support emitting debug info. Some have different -- levels. For compilers that do not the level is just capped to the -- level they do support. -- data DebugInfoLevel = NoDebugInfo | MinimalDebugInfo | NormalDebugInfo | MaximalDebugInfo deriving (Bounded, Enum, Eq, Generic, Read, Show) instance Binary DebugInfoLevel flagToDebugInfoLevel :: Maybe String -> DebugInfoLevel flagToDebugInfoLevel Nothing = NormalDebugInfo flagToDebugInfoLevel (Just s) = case reads s of [(i, "")] | i >= fromEnum (minBound :: DebugInfoLevel) && i <= fromEnum (maxBound :: DebugInfoLevel) -> toEnum i | otherwise -> error $ "Bad debug info level: " ++ show i ++ ". Valid values are 0..3" _ -> error $ "Can't parse debug info level " ++ s -- ------------------------------------------------------------ -- * Languages and Extensions -- ------------------------------------------------------------ unsupportedLanguages :: Compiler -> [Language] -> [Language] unsupportedLanguages comp langs = [ lang | lang <- langs , isNothing (languageToFlag comp lang) ] languageToFlags :: Compiler -> Maybe Language -> [Flag] languageToFlags comp = filter (not . null) . catMaybes . map (languageToFlag comp) . maybe [Haskell98] (\x->[x]) languageToFlag :: Compiler -> Language -> Maybe Flag languageToFlag comp ext = lookup ext (compilerLanguages comp) -- |For the given compiler, return the extensions it does not support. unsupportedExtensions :: Compiler -> [Extension] -> [Extension] unsupportedExtensions comp exts = [ ext | ext <- exts , isNothing (extensionToFlag comp ext) ] type Flag = String -- |For the given compiler, return the flags for the supported extensions. extensionsToFlags :: Compiler -> [Extension] -> [Flag] extensionsToFlags comp = nub . filter (not . null) . catMaybes . map (extensionToFlag comp) extensionToFlag :: Compiler -> Extension -> Maybe Flag extensionToFlag comp ext = lookup ext (compilerExtensions comp) -- | Does this compiler support parallel --make mode? parmakeSupported :: Compiler -> Bool parmakeSupported = ghcSupported "Support parallel --make" -- | Does this compiler support reexported-modules? reexportedModulesSupported :: Compiler -> Bool reexportedModulesSupported = ghcSupported "Support reexported-modules" -- | Does this compiler support thinning/renaming on package flags? renamingPackageFlagsSupported :: Compiler -> Bool renamingPackageFlagsSupported = ghcSupported "Support thinning and renaming package flags" -- | Does this compiler have unified IPIDs (so no package keys) unifiedIPIDRequired :: Compiler -> Bool unifiedIPIDRequired = ghcSupported "Requires unified installed package IDs" -- | Does this compiler support package keys? packageKeySupported :: Compiler -> Bool packageKeySupported = ghcSupported "Uses package keys" -- | Does this compiler support unit IDs? unitIdSupported :: Compiler -> Bool unitIdSupported = ghcSupported "Uses unit IDs" -- | Does this compiler support Backpack? backpackSupported :: Compiler -> Bool backpackSupported = ghcSupported "Support Backpack" -- | Does this compiler support a package database entry with: -- "dynamic-library-dirs"? libraryDynDirSupported :: Compiler -> Bool libraryDynDirSupported comp = case compilerFlavor comp of GHC -> -- Not just v >= mkVersion [8,0,1,20161022], as there -- are many GHC 8.1 nightlies which don't support this. ((v >= mkVersion [8,0,1,20161022] && v < mkVersion [8,1]) || v >= mkVersion [8,1,20161021]) _ -> False where v = compilerVersion comp -- | Does this compiler's "ar" command supports response file -- arguments (i.e. @file-style arguments). arResponseFilesSupported :: Compiler -> Bool arResponseFilesSupported = ghcSupported "ar supports at file" -- | Does this compiler support Haskell program coverage? coverageSupported :: Compiler -> Bool coverageSupported comp = case compilerFlavor comp of GHC -> True GHCJS -> True _ -> False -- | Does this compiler support profiling? profilingSupported :: Compiler -> Bool profilingSupported comp = case compilerFlavor comp of GHC -> True GHCJS -> True LHC -> True _ -> False -- | Utility function for GHC only features ghcSupported :: String -> Compiler -> Bool ghcSupported key comp = case compilerFlavor comp of GHC -> checkProp GHCJS -> checkProp _ -> False where checkProp = case Map.lookup key (compilerProperties comp) of Just "YES" -> True _ -> False -- ------------------------------------------------------------ -- * Profiling detail level -- ------------------------------------------------------------ -- | Some compilers (notably GHC) support profiling and can instrument -- programs so the system can account costs to different functions. There are -- different levels of detail that can be used for this accounting. -- For compilers that do not support this notion or the particular detail -- levels, this is either ignored or just capped to some similar level -- they do support. -- data ProfDetailLevel = ProfDetailNone | ProfDetailDefault | ProfDetailExportedFunctions | ProfDetailToplevelFunctions | ProfDetailAllFunctions | ProfDetailOther String deriving (Eq, Generic, Read, Show) instance Binary ProfDetailLevel flagToProfDetailLevel :: String -> ProfDetailLevel flagToProfDetailLevel "" = ProfDetailDefault flagToProfDetailLevel s = case lookup (lowercase s) [ (name, value) | (primary, aliases, value) <- knownProfDetailLevels , name <- primary : aliases ] of Just value -> value Nothing -> ProfDetailOther s knownProfDetailLevels :: [(String, [String], ProfDetailLevel)] knownProfDetailLevels = [ ("default", [], ProfDetailDefault) , ("none", [], ProfDetailNone) , ("exported-functions", ["exported"], ProfDetailExportedFunctions) , ("toplevel-functions", ["toplevel", "top"], ProfDetailToplevelFunctions) , ("all-functions", ["all"], ProfDetailAllFunctions) ] showProfDetailLevel :: ProfDetailLevel -> String showProfDetailLevel dl = case dl of ProfDetailNone -> "none" ProfDetailDefault -> "default" ProfDetailExportedFunctions -> "exported-functions" ProfDetailToplevelFunctions -> "toplevel-functions" ProfDetailAllFunctions -> "all-functions" ProfDetailOther other -> other
themoritz/cabal
Cabal/Distribution/Simple/Compiler.hs
bsd-3-clause
15,692
0
16
3,523
2,394
1,345
1,049
230
6
{-# LANGUAGE Safe #-} ----------------------------------------------------------------------------- -- | -- Module : Text.ParserCombinators.Parsec.Char -- Copyright : (c) Paolo Martini 2007 -- License : BSD-style (see the LICENSE file) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Parsec compatibility module -- ----------------------------------------------------------------------------- module Text.ParserCombinators.Parsec.Char ( CharParser, spaces, space, newline, tab, upper, lower, alphaNum, letter, digit, hexDigit, octDigit, char, string, anyChar, oneOf, noneOf, satisfy ) where import Text.Parsec.Char import Text.Parsec.String type CharParser st = GenParser Char st
aslatter/parsec
src/Text/ParserCombinators/Parsec/Char.hs
bsd-2-clause
870
0
5
215
102
72
30
23
0
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="bs-BA"> <title>Advanced SQLInjection Scanner</title> <maps> <homeID>sqliplugin</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/sqliplugin/src/main/javahelp/help_bs_BA/helpset_bs_BA.hs
apache-2.0
981
77
66
157
409
207
202
-1
-1
{- Refactoring: move the definiton 'fringe' to module C1. This example aims to test the moving of the definition and the modification of export/import -} module D1(fringe, sumSquares) where import C1 fringe :: Tree a -> [a] fringe p |isLeaf p = [(leaf1 p)] fringe p |isBranch p = fringe (branch1 p) ++ fringe (branch2 p) sumSquares (x:xs) = sq x + sumSquares xs sumSquares [] = 0 sq x = x ^pow pow = 2
kmate/HaRe
old/testing/fromConcreteToAbstract/D1_TokOut.hs
bsd-3-clause
481
0
9
153
148
74
74
11
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Fix -- Copyright : (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology, 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Monadic fixpoints. -- -- For a detailed discussion, see Levent Erkok's thesis, -- /Value Recursion in Monadic Computations/, Oregon Graduate Institute, 2002. -- ----------------------------------------------------------------------------- module Control.Monad.Fix ( MonadFix(mfix), fix ) where import Data.Either import Data.Function ( fix ) import Data.Maybe import Data.Monoid ( Dual(..), Sum(..), Product(..) , First(..), Last(..), Alt(..) ) import GHC.Base ( Monad, error, (.) ) import GHC.List ( head, tail ) import GHC.ST import System.IO -- | Monads having fixed points with a \'knot-tying\' semantics. -- Instances of 'MonadFix' should satisfy the following laws: -- -- [/purity/] -- @'mfix' ('return' . h) = 'return' ('fix' h)@ -- -- [/left shrinking/ (or /tightening/)] -- @'mfix' (\\x -> a >>= \\y -> f x y) = a >>= \\y -> 'mfix' (\\x -> f x y)@ -- -- [/sliding/] -- @'mfix' ('Control.Monad.liftM' h . f) = 'Control.Monad.liftM' h ('mfix' (f . h))@, -- for strict @h@. -- -- [/nesting/] -- @'mfix' (\\x -> 'mfix' (\\y -> f x y)) = 'mfix' (\\x -> f x x)@ -- -- This class is used in the translation of the recursive @do@ notation -- supported by GHC and Hugs. class (Monad m) => MonadFix m where -- | The fixed point of a monadic computation. -- @'mfix' f@ executes the action @f@ only once, with the eventual -- output fed back as the input. Hence @f@ should not be strict, -- for then @'mfix' f@ would diverge. mfix :: (a -> m a) -> m a -- Instances of MonadFix for Prelude monads instance MonadFix Maybe where mfix f = let a = f (unJust a) in a where unJust (Just x) = x unJust Nothing = error "mfix Maybe: Nothing" instance MonadFix [] where mfix f = case fix (f . head) of [] -> [] (x:_) -> x : mfix (tail . f) instance MonadFix IO where mfix = fixIO instance MonadFix ((->) r) where mfix f = \ r -> let a = f a r in a instance MonadFix (Either e) where mfix f = let a = f (unRight a) in a where unRight (Right x) = x unRight (Left _) = error "mfix Either: Left" instance MonadFix (ST s) where mfix = fixST -- Instances of Data.Monoid wrappers instance MonadFix Dual where mfix f = Dual (fix (getDual . f)) instance MonadFix Sum where mfix f = Sum (fix (getSum . f)) instance MonadFix Product where mfix f = Product (fix (getProduct . f)) instance MonadFix First where mfix f = First (mfix (getFirst . f)) instance MonadFix Last where mfix f = Last (mfix (getLast . f)) instance MonadFix f => MonadFix (Alt f) where mfix f = Alt (mfix (getAlt . f))
urbanslug/ghc
libraries/base/Control/Monad/Fix.hs
bsd-3-clause
3,227
0
12
829
701
390
311
49
0
{-# LANGUAGE MagicHash #-} module ShouldFail where import GHC.Base my_undefined :: a -- This one has kind *, not OpenKind my_undefined = undefined die :: Int -> ByteArray# die _ = my_undefined
urbanslug/ghc
testsuite/tests/typecheck/should_fail/tcfail090.hs
bsd-3-clause
198
0
5
37
38
23
15
7
1
module Main where newtype T = C { f :: String } {- hugs (Sept 2006) gives "bc" Program error: Prelude.undefined hugs trac #48 -} main = do print $ case C "abc" of C { f = v } -> v print $ case undefined of C {} -> True
olsner/ghc
testsuite/tests/codeGen/should_run/cgrun062.hs
bsd-3-clause
270
0
13
102
73
40
33
6
1
{-| Module: Itchy.Routes Description: Web app routes License: MIT -} {-# LANGUAGE BangPatterns, LambdaCase, MultiParamTypeClasses, OverloadedLists, OverloadedStrings, QuasiQuotes, RankNTypes, TemplateHaskell, TypeFamilies, ViewPatterns #-} module Itchy.Routes ( App(..) ) where import Control.Monad import Control.Monad.IO.Class import Data.Bits import qualified Data.ByteArray.Encoding as BA import qualified Data.HashMap.Strict as HM import Data.Int import Data.List import qualified Data.Map.Strict as M import Data.Maybe import qualified Data.Serialize as S import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as TL import qualified Data.Vector as V import Data.Word import Foreign.C.Types import qualified Network.HTTP.Types as HT import System.Posix.Time import qualified Text.Blaze.Html5 as H import Text.Blaze.Html5((!)) import qualified Text.Blaze.Html5.Attributes as A import qualified Text.Blaze.Html.Renderer.Text as H(renderHtml) import qualified Wai.Routes as W import qualified Web.Cookie as W import Itchy.ItchInvestigator import Itchy.Itch import Itchy.ItchCache import Itchy.Localization import Itchy.Localization.En import Itchy.Localization.RichText import Itchy.Localization.Ru import Itchy.Report import Itchy.Report.Analysis import Itchy.Report.Record import Itchy.Static data App = App { appItchApi :: !ItchApi , appItchCache :: !ItchCache , appItchInvestigator :: !ItchInvestigator , appItchInvestigationStalePeriod :: {-# UNPACK #-} !Int64 } localizations :: [(T.Text, Localization)] localizations = [ ("en", localizationEn) , ("ru", localizationRu) ] getLocalization :: W.HandlerM App master Localization getLocalization = do maybeNewLocale <- W.getParam "locale" locale <- case maybeNewLocale of Just newLocale -> do W.setCookie W.def { W.setCookieName ="locale" , W.setCookieValue = T.encodeUtf8 newLocale , W.setCookiePath = Just "/" , W.setCookieMaxAge = Just $ 365 * 24 * 3600 } return newLocale Nothing -> fromMaybe "en" <$> W.getCookie "locale" return $ fromMaybe localizationEn $ lookup locale localizations W.mkRoute "App" [W.parseRoutes| / HomeR GET /game/#Word64 GameR GET /upload/#Word64 UploadR GET /upload/#Word64/download UploadDownloadR GET /investigateUpload/#Word64 InvestigateUploadR POST /auth AuthR POST /search SearchR GET /gamebyurl GameByUrlR GET |] getHomeR :: W.Handler App getHomeR = W.runHandlerM $ do showRoute <- W.showRouteSub loc <- getLocalization page (locHome loc) [(locHome loc, HomeR)] $ do H.p $ H.toHtml $ locWelcome loc H.form ! A.method "GET" ! A.action (H.toValue $ showRoute SearchR) $ do H.label ! A.type_ "text" ! A.for "searchtext" $ H.toHtml $ locSearchGameByName loc H.br H.input ! A.type_ "text" ! A.id "searchtext" ! A.name "s" H.input ! A.type_ "submit" ! A.value (H.toValue $ locSearch loc) H.form ! A.method "GET" ! A.action (H.toValue $ showRoute GameByUrlR) $ do H.label ! A.type_ "text" ! A.for "urltext" $ H.toHtml $ locGoToGameByUrl loc H.br H.input ! A.type_ "text" ! A.id "urltext" ! A.name "url" ! A.placeholder "[https://]creator[.itch.io]/game[/]" H.input ! A.type_ "submit" ! A.value (H.toValue $ locGo loc) getGameR :: Word64 -> W.Handler App getGameR gameId = W.runHandlerM $ do App { appItchCache = itchCache , appItchInvestigator = itchInvestigator , appItchInvestigationStalePeriod = investigationStalePeriod } <- W.sub showRoute <- W.showRouteSub loc <- getLocalization maybeGameWithUploads <- liftIO $ itchCacheGetGame itchCache (ItchGameId gameId) case maybeGameWithUploads of Just (game@ItchGame { itchGame_title = gameTitle , itchGame_url = gameUrl , itchGame_cover_url = maybeGameCoverUrl , itchGame_user = ItchUser { itchUser_username = creatorUserName } , itchGame_can_be_bought = gameCanBeBought , itchGame_in_press_system = gameInPressSystem , itchGame_short_text = fromMaybe "" -> gameShortText , itchGame_has_demo = gameHasDemo , itchGame_min_price = ((* (0.01 :: Float)) . fromIntegral) -> gameMinPrice , itchGame_p_windows = gameWindows , itchGame_p_linux = gameLinux , itchGame_p_osx = gameMacOS , itchGame_p_android = gameAndroid }, gameUploads) -> do let gameByAuthor = locGameByAuthor loc gameTitle creatorUserName let uploadsById = HM.fromList $ V.toList $ flip fmap gameUploads $ \(upload@ItchUpload { itchUpload_id = uploadId }, _maybeBuild) -> (uploadId, upload) let uploadName uploadId = case HM.lookup uploadId uploadsById of Just ItchUpload { itchUpload_display_name = maybeDisplayName , itchUpload_filename = fileName } -> Just $ fromMaybe fileName maybeDisplayName Nothing -> Nothing investigations <- liftIO $ forM gameUploads $ \(ItchUpload { itchUpload_id = uploadId , itchUpload_filename = uploadFileName }, _maybeBuild) -> investigateItchUpload itchInvestigator uploadId uploadFileName False CTime currentTime <- liftIO epochTime let reinvestigateTimeCutoff = currentTime - investigationStalePeriod page gameByAuthor [(locHome loc, HomeR), (gameByAuthor, GameR gameId)] $ H.div ! A.class_ "game_info" $ do case maybeGameCoverUrl of Just coverUrl -> H.img ! A.class_ "cover" ! A.src (H.toValue coverUrl) Nothing -> mempty H.p $ H.toHtml $ locLink loc gameUrl H.p $ H.toHtml $ locDescription loc gameShortText H.p $ H.toHtml (locPlatforms loc) <> ": " <> (if gameWindows then H.span ! A.class_ "tag" $ "windows" else mempty) <> (if gameLinux then H.span ! A.class_ "tag" $ "linux" else mempty) <> (if gameMacOS then H.span ! A.class_ "tag" $ "macos" else mempty) <> (if gameAndroid then H.span ! A.class_ "tag" $ "android" else mempty) H.p $ H.toHtml $ if gameHasDemo then locHasDemo loc else locNoDemo loc H.p $ H.toHtml $ if gameCanBeBought then if gameMinPrice <= 0 then locFreeDonationsAllowed loc else locMinimumPrice loc <> ": $" <> T.pack (show gameMinPrice) else locFreePaymentsDisabled loc H.p $ H.toHtml $ if gameInPressSystem then locOptedInPressSystem loc else locNotOptedInPressSystem loc H.h2 $ H.toHtml $ locUploads loc H.table $ do H.tr $ do H.th $ H.toHtml $ locDisplayName loc H.th $ H.toHtml $ locFileName loc H.th $ H.toHtml $ locSize loc H.th $ H.toHtml $ locTags loc H.th "Butler" H.th $ H.toHtml $ locReportStatus loc forM_ (V.zip gameUploads investigations) $ \((ItchUpload { itchUpload_id = ItchUploadId uploadId , itchUpload_display_name = fromMaybe "" -> uploadDisplayName , itchUpload_filename = uploadFileName , itchUpload_demo = uploadDemo , itchUpload_preorder = uploadPreorder , itchUpload_size = uploadSize , itchUpload_p_windows = uploadWindows , itchUpload_p_linux = uploadLinux , itchUpload_p_osx = uploadMacOS , itchUpload_p_android = uploadAndroid }, maybeBuild), investigation) -> H.tr ! A.class_ "upload" $ do H.td ! A.class_ "name" $ H.toHtml uploadDisplayName H.td ! A.class_ "filename" $ {- a ! A.href (H.toValue $ showRoute $ UploadR uploadId) $ -} H.toHtml uploadFileName H.td $ H.toHtml $ locSizeInBytes loc uploadSize H.td $ do if uploadWindows then H.span ! A.class_ "tag" $ "windows" else mempty if uploadLinux then H.span ! A.class_ "tag" $ "linux" else mempty if uploadMacOS then H.span ! A.class_ "tag" $ "macos" else mempty if uploadAndroid then H.span ! A.class_ "tag" $ "android" else mempty if uploadDemo then H.span ! A.class_ "tag" $ "demo" else mempty if uploadPreorder then H.span ! A.class_ "tag" $ "preorder" else mempty H.td $ case maybeBuild of Just ItchBuild { itchBuild_version = T.pack . show -> buildVersion , itchBuild_user_version = fromMaybe (locNoUserVersion loc) -> buildUserVersion } -> H.toHtml $ locBuildVersion loc buildVersion buildUserVersion Nothing -> H.toHtml $ locDoesntUseButler loc H.td $ case investigation of ItchStartedInvestigation -> H.toHtml $ locInvestigationStarted loc ItchQueuedInvestigation n -> H.toHtml $ locInvestigationQueued loc $ n + 1 ItchProcessingInvestigation -> H.toHtml $ locInvestigationProcessing loc ItchInvestigation { itchInvestigationMaybeReport = maybeReport , itchInvestigationTime = t } -> do if isJust maybeReport then H.a ! A.href (H.toValue $ showRoute $ UploadR uploadId) ! A.target "_blank" $ H.toHtml $ locInvestigationSucceeded loc else H.toHtml $ locInvestigationFailed loc when (t < reinvestigateTimeCutoff) $ H.form ! A.class_ "formreprocess" ! A.action (H.toValue $ showRoute $ InvestigateUploadR uploadId) ! A.method "POST" $ H.input ! A.type_ "submit" ! A.value (H.toValue $ locReinvestigate loc) H.h2 $ H.toHtml $ locReport loc let reportsCount = foldr (\investigation !c -> case investigation of ItchInvestigation {} -> c + 1 _ -> c ) 0 investigations in when (reportsCount < V.length gameUploads) $ H.p $ (H.toHtml $ locReportNotComplete loc reportsCount (V.length gameUploads)) <> " " <> (H.a ! A.href (H.toValue $ showRoute $ GameR gameId) $ H.toHtml $ locRefresh loc) let AnalysisGame { analysisGame_uploads = analysisUploads , analysisGame_release = AnalysisUploadGroup { analysisUploadGroup_records = releaseGroupRecords } , analysisGame_preorder = AnalysisUploadGroup { analysisUploadGroup_records = preorderGroupRecords } , analysisGame_demo = AnalysisUploadGroup { analysisUploadGroup_records = demoGroupRecords } , analysisGame_records = gameRecords } = analyseGame loc game $ concat $ flip fmap (V.toList $ V.zip gameUploads investigations) $ \((u, _), inv) -> case inv of ItchInvestigation { itchInvestigationMaybeReport = Just r } -> [(u, r)] _ -> [] let uploadsRecords = concat $ Prelude.map analysisUpload_records analysisUploads let records = flip sortOn ( gameRecords <> releaseGroupRecords <> preorderGroupRecords <> demoGroupRecords <> uploadsRecords ) $ \Record { recordScope = scope , recordSeverity = severity , recordName = name , recordMessage = message } -> (severity, scope, name, message) H.table $ do H.tr $ do H.th $ H.toHtml $ locRecordSeverity loc H.th ! A.class_ "scope" $ H.toHtml $ locRecordScope loc H.th ! A.class_ "name" $ H.toHtml $ locRecordName loc H.th ! A.class_ "name" $ H.toHtml $ locRecordMessage loc forM_ records $ \Record { recordScope = scope , recordSeverity = severity , recordName = name , recordMessage = message } -> let (cls, ttl) = case severity of SeverityOk -> ("ok", locSeverityOk loc) SeverityInfo -> ("info", locSeverityInfo loc) SeverityTip -> ("tip", locSeverityTip loc) SeverityWarn -> ("warn", locSeverityWarn loc) SeverityBad -> ("bad", locSeverityBad loc) SeverityErr -> ("err", locSeverityErr loc) in H.tr ! A.class_ cls $ do H.td ! A.class_ "status" $ H.div $ H.toHtml ttl H.td $ H.toHtml $ case scope of ProjectScope -> locScopeProject loc UploadGroupScope uploadGroup -> locScopeUploadGroup loc uploadGroup UploadScope uploadId -> locScopeUpload loc (uploadName uploadId) EntryScope uploadId entryPath -> locScopeEntry loc (uploadName uploadId) (T.intercalate "/" entryPath) H.td $ H.div ! A.class_ "record" $ H.toHtml name H.td $ unless (message == RichText []) $ H.div ! A.class_ "message" $ H.toHtml message Nothing -> do let gameByAuthor = locUnknownGame loc W.header "Refresh" "3" page gameByAuthor [(locHome loc, HomeR), (gameByAuthor, GameR gameId)] $ do H.p $ H.toHtml $ locGameNotCached loc H.p $ H.a ! A.href (H.toValue $ showRoute $ GameR gameId) $ H.toHtml $ locRefresh loc getUploadR :: Word64 -> W.Handler App getUploadR uploadId = W.runHandlerM $ do App { appItchCache = itchCache , appItchInvestigator = itchInvestigator } <- W.sub loc <- getLocalization maybeUpload <- liftIO $ itchCacheGetUpload itchCache $ ItchUploadId uploadId case maybeUpload of Just (ItchUpload { itchUpload_filename = uploadFileName , itchUpload_game_id = ItchGameId gameId }, _maybeBuild) -> do maybeGameWithUploads <- liftIO $ itchCacheGetGame itchCache $ ItchGameId gameId case maybeGameWithUploads of Just (ItchGame { itchGame_title = gameTitle , itchGame_user = ItchUser { itchUser_username = creatorUserName } }, _) -> do let gameByAuthor = locGameByAuthor loc gameTitle creatorUserName investigation <- liftIO $ investigateItchUpload itchInvestigator (ItchUploadId uploadId) uploadFileName False case investigation of ItchInvestigation { itchInvestigationMaybeReport = maybeReport } -> page uploadFileName [(locHome loc, HomeR), (gameByAuthor, GameR gameId), (uploadFileName, UploadR uploadId)] $ do case maybeReport of Just Report { report_unpack = ReportUnpack_succeeded rootEntries } -> H.table ! A.class_ "entries" $ do H.tr $ do H.th $ H.toHtml $ locFileName loc H.th $ H.toHtml $ locSize loc H.th $ H.toHtml $ locAccessMode loc H.th $ H.toHtml $ locTags loc let tag = H.span ! A.class_ "tag" tagArch = \case ReportArch_unknown -> mempty ReportArch_x86 -> tag "x86" ReportArch_x64 -> tag "x64" printEntries level = mapM_ (printEntry level) . M.toAscList printEntry level (entryName, entry) = do H.tr $ do H.td ! A.style ("padding-left: " <> (H.toValue $ 5 + level * 20) <> "px") $ H.toHtml entryName H.td $ case entry of ReportEntry_file { reportEntry_size = entrySize } -> H.toHtml $ locSizeInBytes loc $ toInteger entrySize _ -> mempty H.td $ do let entryMode = reportEntry_mode entry let isDir = case entry of ReportEntry_directory {} -> True _ -> False tag $ H.toHtml $ (if isDir then 'd' else '.') : (if (entryMode .&. 0x100) > 0 then 'r' else '.') : (if (entryMode .&. 0x80) > 0 then 'w' else '.') : (if (entryMode .&. 0x40) > 0 then 'x' else '.') : (if (entryMode .&. 0x20) > 0 then 'r' else '.') : (if (entryMode .&. 0x10) > 0 then 'w' else '.') : (if (entryMode .&. 0x8) > 0 then 'x' else '.') : (if (entryMode .&. 0x4) > 0 then 'r' else '.') : (if (entryMode .&. 0x2) > 0 then 'w' else '.') : (if (entryMode .&. 0x1) > 0 then 'x' else '.') : [] H.td $ case entry of ReportEntry_unknown {} -> mempty ReportEntry_file { reportEntry_parses = entryParses } -> forM_ entryParses $ \case ReportParse_itchToml {} -> tag ".itch.toml" ReportParse_binaryPe ReportBinaryPe { reportBinaryPe_arch = arch , reportBinaryPe_isCLR = isCLR } -> do tag "PE" when isCLR $ tag "CLR" tagArch arch ReportParse_binaryElf ReportBinaryElf { reportBinaryElf_arch = arch } -> do tag "ELF" tagArch arch ReportParse_binaryMachO ReportBinaryMachO { reportBinaryMachO_binaries = subBinaries } -> do tag "Mach-O" forM_ subBinaries $ \ReportMachOSubBinary { reportMachoSubBinary_arch = arch } -> tagArch arch ReportParse_archive {} -> mempty ReportParse_msi {} -> tag "msi" ReportEntry_directory {} -> mempty ReportEntry_symlink { reportEntry_link = entryLink } -> do tag $ H.toHtml $ locSymlink loc H.toHtml entryLink case entry of ReportEntry_file { reportEntry_parses = parses } -> forM_ parses $ \case ReportParse_archive ReportArchive { reportArchive_entries = entryEntries } -> printEntries (level + 1) entryEntries ReportParse_msi ReportMsi { reportMsi_entries = entryEntries } -> printEntries (level + 1) entryEntries _ -> mempty ReportEntry_directory { reportEntry_entries = entryEntries } -> printEntries (level + 1) entryEntries _ -> mempty printEntries (0 :: Int) rootEntries _ -> return () _ -> W.status HT.notFound404 Nothing -> W.status HT.notFound404 Nothing -> W.status HT.notFound404 getUploadDownloadR :: Word64 -> W.Handler App getUploadDownloadR (ItchUploadId -> uploadId) = W.runHandlerM $ do App { appItchApi = itchApi } <- W.sub maybeDownloadKeyId <- W.getParam "downloadKey" url <- liftIO $ itchDownloadUpload itchApi uploadId (ItchDownloadKeyId . read . T.unpack <$> maybeDownloadKeyId) W.header "Location" $ T.encodeUtf8 url W.status HT.seeOther303 postInvestigateUploadR :: Word64 -> W.Handler App postInvestigateUploadR (ItchUploadId -> uploadId) = W.runHandlerM $ do App { appItchCache = itchCache , appItchInvestigator = itchInvestigator } <- W.sub showRoute <- W.showRouteSub maybeUpload <- liftIO $ itchCacheGetUpload itchCache uploadId case maybeUpload of Just (ItchUpload { itchUpload_filename = uploadFileName , itchUpload_game_id = ItchGameId gameId }, _maybeBuild) -> do void $ liftIO $ investigateItchUpload itchInvestigator uploadId uploadFileName True W.header "Location" (T.encodeUtf8 $ showRoute $ GameR gameId) W.status HT.seeOther303 Nothing -> W.status HT.notFound404 postAuthR :: W.Handler App postAuthR = W.runHandlerM $ do App { appItchApi = itchApi } <- W.sub maybeToken <- W.getPostParam "token" maybeUser <- case maybeToken of Just token -> liftIO $ Just <$> itchJwtMe itchApi token Nothing -> return Nothing case maybeUser of Just user -> do W.setCookie W.def { W.setCookieName = "user" , W.setCookieValue = BA.convertToBase BA.Base64URLUnpadded $ S.encode user , W.setCookiePath = Just "/" } showRoute <- W.showRouteSub W.header "Location" (T.encodeUtf8 $ showRoute HomeR) W.status HT.seeOther303 Nothing -> W.status HT.notFound404 getSearchR :: W.Handler App getSearchR = W.runHandlerM $ do App { appItchApi = itchApi } <- W.sub showRoute <- W.showRouteSub loc <- getLocalization searchText <- fromMaybe "" <$> W.getParam "s" Right games <- if T.null searchText then return $ Right V.empty else liftIO $ itchSearchGame itchApi searchText page (locSearch loc) [(locHome loc, HomeR), (locSearch loc, SearchR)] $ do H.form ! A.method "GET" ! A.action (H.toValue $ showRoute SearchR) $ do H.input ! A.type_ "text" ! A.name "s" ! A.value (H.toValue searchText) H.input ! A.type_ "submit" ! A.value (H.toValue $ locSearch loc) H.div ! A.class_ "searchresults" $ forM_ games $ \ItchGameShort { itchGameShort_id = ItchGameId gameId , itchGameShort_title = gameTitle , itchGameShort_cover_url = maybeGameCoverUrl } -> H.a ! A.class_ "game" ! A.href (H.toValue $ showRoute $ GameR gameId) ! A.target "_blank" $ do case maybeGameCoverUrl of Just gameCoverUrl -> H.img ! A.src (H.toValue gameCoverUrl) Nothing -> mempty H.span $ H.toHtml gameTitle getGameByUrlR :: W.Handler App getGameByUrlR = W.runHandlerM $ do App { appItchApi = itchApi } <- W.sub showRoute <- W.showRouteSub searchText <- fromMaybe "" <$> W.getParam "url" -- strip various stuff, and parse let pref p s = fromMaybe s $ T.stripPrefix p s suf q s = fromMaybe s $ T.stripSuffix q s case T.splitOn "/" $ T.replace ".itch.io/" "/" $ suf "/" $ pref "https://" $ pref "http://" $ searchText of [creator, game] -> do maybeGameId <- liftIO $ itchGameGetByUrl itchApi creator game case maybeGameId of Just (ItchGameId gameId) -> do W.header "Location" $ T.encodeUtf8 $ showRoute $ GameR gameId W.status HT.seeOther303 Nothing -> W.status HT.notFound404 _ -> W.status HT.notFound404 page :: W.RenderRoute master => T.Text -> [(T.Text, W.Route App)] -> H.Html -> W.HandlerM App master () page titleText pieces bodyHtml = do W.header HT.hCacheControl "public, max-age=1" maybeUserCookie <- W.getCookie "user" let maybeUser = case maybeUserCookie of Just (BA.convertFromBase BA.Base64URLUnpadded . T.encodeUtf8 -> Right (S.decode -> Right user)) -> Just user _ -> Nothing showRoute <- W.showRouteSub loc <- getLocalization W.html $ TL.toStrict $ H.renderHtml $ H.docTypeHtml $ do H.head $ do H.meta ! A.charset "utf-8" H.meta ! A.name "robots" ! A.content "index,follow" H.link ! A.rel "stylesheet" ! A.href [staticPath|static-stylus/itchy.css|] H.link ! A.rel "icon" ! A.type_ "image/png" ! A.href [staticPath|static/itchio.svg|] H.script ! A.src [staticPath|static/jquery-2.1.4.min.js|] $ mempty H.script ! A.src [staticPath|static-js/itchy.js|] $ mempty H.title $ H.toHtml $ titleText <> " - " <> "itch.io Developer's Sanity Keeper" H.body $ do H.div ! A.class_ "header" $ do H.div ! A.class_ "pieces" $ forM_ pieces $ \(pieceName, pieceRoute) -> do void "/ " H.a ! A.href (H.toValue $ showRoute pieceRoute) $ H.toHtml pieceName void " " case maybeUser of Just ItchUser { itchUser_username = userName , itchUser_url = userUrl , itchUser_cover_url = userMaybeCoverUrl } -> H.div ! A.class_ "user" $ do H.a ! A.href (H.toValue userUrl) $ do case userMaybeCoverUrl of Just userCoverUrl -> H.img ! A.src (H.toValue userCoverUrl) Nothing -> mempty H.toHtml userName Nothing -> mempty H.h1 $ H.toHtml titleText bodyHtml H.div ! A.class_ "footer" $ do H.div $ H.toHtml $ locNoAffiliation loc H.div $ do H.span ! A.class_ "localizations" $ forM_ localizations $ \(locale, localization) -> H.a ! A.href ("?locale=" <> H.toValue locale) $ H.toHtml $ locLanguageName localization H.span " | " H.a ! A.href "https://github.com/quyse/itchy" ! A.target "_blank" $ "Github"
quyse/itchy
Itchy/Routes.hs
mit
22,676
539
41
5,456
4,790
2,947
1,843
-1
-1
module Ch1010ex1 ( stops , vowels , nouns , verbs , allWords , allWordsPrefixP ) where import Combinatorial (comboOfN) import Data.Monoid stops :: [Char] stops = "pbtdkg" vowels :: [Char] vowels = "aeiou" nouns :: [String] nouns = ["bird", "dog", "cat", "car", "Elon Musk", "the dying of the light", "my cousin vinny"] verbs :: [String] verbs = ["hits", "runs", "starts", "stops", "kills", "shouts at", "calls", "rolls eyes at"] -- returns all three-character combinations of stop-vowel-stop -- zip all beginnings with each ending vowels allWords :: [String] allWords = comboOfN mempty (map (map return) [stops, vowels, stops]) allWordsPrefixP :: [String] allWordsPrefixP = filter (\(x:xs) -> x == 'p') allWords -- returns all sentences composed of noun-verb-noun allSentences :: [String] allSentences = comboOfN " " [nouns, verbs, nouns] -- get all combos of N lists of elements -- From Combinatorial.hs comboOfN :: Monoid a => a -> [[a]] -> [a] comboOfN sep (z:zs) = foldl ((joinCombinations .) . makeCombinations) z zs where makeCombinations x y = zip (take (length y) (repeat x)) y joinCombinations = concatMap $ \(xs, y) -> map (\x -> x <> sep <> y) xs
JoshuaGross/haskell-learning-log
Code/Haskellbook/ch10.10ex1.hs
mit
1,214
0
13
243
386
227
159
27
1
{-# LANGUAGE RecordWildCards, TypeFamilies #-} import Control.Monad import qualified Data.Map as M import Text.Printf type FieldName = String type Point = M.Map FieldName (Maybe Double) type Label = Double class DataPass a where type Init a create :: (Init a) -> a update :: a -> [(Point, Label)] -> a apply1 :: a -> Point -> Point apply :: a -> [Point] -> [Point] data MeanImputer = MI {fieldNames :: [FieldName], moments :: [(Double, Int)]} instance DataPass MeanImputer where type Init MeanImputer = [String] create = createMI update = updateMI apply datapass points = map (apply1 datapass) points apply1 = imputeMean imputeMean :: MeanImputer -> Point -> Point imputeMean mi point = foldr update point (zip (fieldNames mi) (moments mi)) where update (fname, (d, n)) pt = case M.lookup fname pt of (Just (Just v)) -> pt _ -> M.insert fname (Just (d / fromIntegral n)) pt createMI :: [FieldName] -> MeanImputer createMI fieldNames = MI fieldNames $ replicate (length fieldNames) (0.0, 0) updateMI1 :: MeanImputer -> (Point, Label) -> MeanImputer updateMI1 mi@(MI {..}) (point, _) = mi {moments = moments'} where moments' = zipWith update fieldNames moments update fname (d, n) = case M.lookup fname point of Just (Just value) -> (d + value, n + 1) _ -> (d , n) updateMI :: MeanImputer -> [(Point, Label)] -> MeanImputer updateMI mi labeledPoints = foldl updateMI1 mi labeledPoints testData :: [Point] testData = [M.fromList [("A", Just 0), ("B", Just 1), ("C", Nothing), ("D", Just 4)], M.fromList [("A", Nothing), ("B", Just 2), ("C", Just 14), ("D", Just 8)], M.fromList [("A", Just 1), ("B", Nothing), ("C", Nothing) ], M.fromList [("A", Nothing), ("B", Just 4), ("C", Just 22), ("D", Just 3)], M.fromList [("A", Just 0), ("B", Just 5), ("C", Just 11), ("D", Just 1)]] testDataWithLabels :: [(Point, Label)] testDataWithLabels = zip testData (repeat 0.0) -- labels not used here. printDF :: [Point] -> IO () printDF = mapM_ printPoint where printPoint pt = line pt >> putStrLn "" line pt = forM_ (M.toList pt) $ \(fname, maybeVal) -> do putStr $ fname ++ "= " case maybeVal of Just v -> printf "%6.2f" v Nothing -> putStr " NA " putStr "; " demo :: IO () demo = do let dpEmpty = create ["A", "B", "D"] :: MeanImputer dpFull = update dpEmpty testDataWithLabels putStrLn "Before imputation:" printDF testData putStrLn "After imputation: " printDF $ apply dpFull testData main :: IO () main = demo
michaelochurch/stats-haskell-talk-201509
Main.hs
mit
2,739
0
15
742
1,093
594
499
68
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Test.Unit.Connection where import qualified Test.Framework as Framework import Test.Framework import Test.HUnit import Test.Framework.Providers.HUnit import Web.SocketIO.Server import Web.SocketIO.Types import Web.SocketIO.Channel import Web.SocketIO.Connection -------------------------------------------------------------------------------- testConfig :: Configuration testConfig = defaultConfig { transports = [XHRPolling] , logLevel = 3 , logTo = stderr , heartbeats = True , closeTimeout = 2 , heartbeatTimeout = 60 , heartbeatInterval = 25 , pollingDuration = 20 } makeEnvironment :: IO Env makeEnvironment = do tableRef <- newSessionTableRef let handler = return () logChhannel <- newLogChannel globalChannel <- newGlobalChannel return $ Env tableRef handler testConfig logChhannel globalChannel -------------------------------------------------------------------------------- testHandshake :: Assertion testHandshake = do env <- makeEnvironment MsgHandshake _ a b t <- runConnection env Handshake assertEqual "respond with " (expectedResponse env) (MsgHandshake "" a b t) where expectedResponse env = MsgHandshake "" heartbeatTimeout' closeTimeout' transports' where config = envConfiguration env heartbeatTimeout' = if heartbeats config then heartbeatTimeout config else 0 closeTimeout' = closeTimeout config transports' = transports config -------------------------------------------------------------------------------- testConnect :: Assertion testConnect = do env <- makeEnvironment MsgHandshake sessionID _ _ _ <- runConnection env Handshake res <- runConnection env (Connect sessionID) assertEqual "respond with (MsgConnect NoEndpoint)" (MsgConnect NoEndpoint) res -------------------------------------------------------------------------------- testRequest :: Assertion testRequest = do env <- makeEnvironment MsgHandshake sessionID _ _ _ <- runConnection env Handshake runConnection env (Connect sessionID) res <- runConnection env (Request sessionID (MsgEvent NoID NoEndpoint (Event "event name" (Payload ["payload"])))) assertEqual "respond with (MsgConnect NoEndpoint)" (MsgConnect NoEndpoint) (res) -------------------------------------------------------------------------------- testDisconnect :: Assertion testDisconnect = do env <- makeEnvironment MsgHandshake sessionID _ _ _ <- runConnection env Handshake runConnection env (Connect sessionID) res <- runConnection env (Disconnect sessionID) assertEqual "respond with MsgNoop" MsgNoop res -------------------------------------------------------------------------------- test :: Framework.Test test = testGroup "Connection" [ testCase "Handshake" testHandshake , testCase "Connect" testConnect , testCase "Request" testRequest , testCase "Disconnect" testDisconnect ]
banacorn/socket.io-haskell
test/Test/Unit/Connection.hs
mit
3,318
0
17
760
643
331
312
67
2
module StupidBot.Bot (stupidBot) where import Vindinium.Types import Utils import StupidBot.Goal import qualified Data.Graph.AStar as AS import Data.Maybe (fromMaybe, fromJust) import Data.List (find) stupidBot :: Bot stupidBot = directionTo whereToGo directionTo :: GPS -> State -> Dir directionTo gps s = let from = heroPos $ stateHero s path = shortestPathTo s $ gps s in case path of (p:_) -> dirFromPos from p [] -> Stay shortestPathTo :: State -> Goal -> [Pos] shortestPathTo s goal = let board = gameBoard $ stateGame s hero = stateHero s path = AS.aStar (adjacentTiles board) (stepCost s goal) (distanceEstimateTo goal s) (isGoal goal s) (heroPos hero) in fromMaybe [] path distanceEstimateTo :: Goal -> State -> Pos -> Int distanceEstimateTo Heal s pos = minimum $ map (manhattan pos) (taverns (gameBoard $ stateGame s)) distanceEstimateTo (Capture _) s pos = let board = gameBoard $ stateGame s in minimum $ map (\p -> let heroid = heroId $ stateHero s Just m = tileAt board p in if canCaptureMine m heroid then manhattan pos p else 999) (mines board) distanceEstimateTo (Kill hid) s pos = let heroes = gameHeroes $ stateGame s Just h = find (\e -> heroId e == hid) heroes in manhattan pos $ heroPos h distanceEstimateTo Survive _ _ = 1 distanceEstimateTo _ _ _ = error "not implemented!" stepCost :: State -> Goal -> Distance stepCost s goal from to = let board = gameBoard $ stateGame s in case fromJust $ tileAt board to of FreeTile -> dangerLevelWithin 3 s from to _ -> if isGoal goal s to then 1 else 999
flyrry/phonypony
src/StupidBot/Bot.hs
mit
1,712
0
16
459
633
317
316
47
3
{-# LANGUAGE MonadComprehensions #-} module Main where import Data.Foldable (traverse_) import Data.Maybe (fromMaybe, listToMaybe, maybe) import System.Environment (getArgs) fizzbuzz :: (Integral a, Show a) => a -> String fizzbuzz i = fromMaybe (show i) $ [ "fizz" | i `rem` 3 == 0 ] <> [ "buzz" | i `rem` 5 == 0 ] <> [ "bazz" | i `rem` 7 == 0 ] main :: IO () main = do upTo <- fmap (maybe 100 read . listToMaybe) getArgs traverse_ putStrLn [ fizzbuzz i | i <- [1 .. upTo] ]
genos/Programming
workbench/fizzbuzzMonadComprehensions.hs
mit
511
0
11
128
212
116
96
15
1
{-# LANGUAGE ImplicitParams #-} -- | Based on Cruise control system from -- http://www.cds.caltech.edu/~murray/amwiki/index.php/Cruise_control module CruiseControl where import Zelus data Gear = One | Two | Three | Four | Five deriving (Eq, Show) run :: Double -- ^ Initial speed, m/s -> S Double -- ^ Cruise control speed setting, m/s -> S Double -- ^ Road slope (disturbance), rad -> S Double -- ^ Resulting speed,m/s run v0 ref road_slope = let (u_a, u_b) = controller (pre v_stable) ref acc = vehicle (pre v_stable) u_a u_b road_slope v = integ (acc `in1t` val v0) v_stable = (v <? 0.005) ? (0,v) in v_stable where ?h = 0.01 vehicle :: S Double -- ^ Velocity, m/s -> S Double -- ^ Accelerator ratio, [0, 1] -> S Double -- ^ Decelerator ratio, [0, 1] -> S Double -- ^ Road slope, rad -> S Double -- ^ Resulting acceleration, m/s^2 vehicle v u_a u_b road_slope = acc where t_m = 400 -- engine torque constant, Nm omega_m = 400 -- peak torque rate, rad/sec beta = 0.4 -- torque coefficient cr = 0.03 -- coefficient of rolling friction rho = 1.29 -- density of air, kg/m^3 cd = 0.28 -- drag coefficient a = 2.8 -- car area, m^2 g = 9.81 -- gravitational constant m = 1700 -- vehicle mass, kg t_m_b = 2800 -- maximum brake torque, Nm wheel_radius = 0.381 -- m gear_ratio One = 13.52 gear_ratio Two = 7.6 gear_ratio Three = 5.08 gear_ratio Four = 3.8 gear_ratio Five = 3.08 -- engine speed, rad/s omega = (v * map gear_ratio gear) / (wheel_radius * pi) * 60 / 9.55 t_e = u_a * t_m * (1 - beta*(omega/omega_m - 1)^2) -- engine tourque t_b = u_b * t_m_b -- brake tourque -- friction f_fric = ((t_e * map gear_ratio gear) - (t_b * signum v)) / wheel_radius f_g = m * g * sin road_slope -- gravitation f_r = m * g * cr * signum v -- rolling resistance f_a = 0.5 * rho * cd * a * v^2 -- air drag acc = (f_fric - f_g - f_r - f_a) / m up_shift = 3000 / 9.55 -- rad/s down_shift = 1000 / 9.55 -- rad/s gear = automaton [ One >-- omega >? up_shift --> Two , Two >-- omega <? down_shift --> One , Two >-- omega >? up_shift --> Three , Three >-- omega <? down_shift --> Two , Three >-- omega >? up_shift --> Four , Four >-- omega <? down_shift --> Three , Four >-- omega >? up_shift --> Five , Five >-- omega <? down_shift --> Four ] controller :: (?h :: Double) => S Double -> S Double -> (S Double, S Double) controller v ref = (u_a, u_b) where kp = 0.8 ki = 0.04 kd = 0.0 err = ref - v i_err = integ $ ((abs (pre pid) >? 1) ? (0, err)) `in1t` 0 d_err = deriv err pid = kp*err + ki*i_err + kd*d_err -- accelerate when positive and break when negative u_a = pid >? 0 ? (mn pid 1, 0) u_b = pid <? 0 ? (mn (-pid) 1, 0)
koengit/cyphy
src/CruiseControl.hs
mit
2,996
0
15
924
918
506
412
68
5
{-# LANGUAGE OverloadedStrings #-} module Network.API.Mandrill.SubaccountsSpec where import Test.Hspec import Test.Hspec.Expectations.Contrib import Network.API.Mandrill.Types import Network.API.Mandrill.Utils import qualified Data.Text as Text import qualified Network.API.Mandrill.Subaccounts as Subaccounts import System.Environment spec :: Spec spec = do test_list test_add test_info test_update test_delete test_pause test_resume test_resume :: Spec test_resume = describe "/subaccounts/resume.json" $ it "should resume a paused subaccount" $ do raw <- getEnv "MANDRILL_API_KEY" resp <- runMandrill (ApiKey $ Text.pack raw) $ do _ <- Subaccounts.add "acc-1" "My Acc" "yes, indeed." 50 Subaccounts.resume "acc-1" resp `shouldSatisfy` isRight test_pause :: Spec test_pause = describe "/subaccounts/pause.json" $ it "should pause a subaccount" $ do raw <- getEnv "MANDRILL_API_KEY" resp <- runMandrill (ApiKey $ Text.pack raw) $ do _ <- Subaccounts.add "acc-1" "My Acc" "yes, indeed." 50 Subaccounts.pause "acc-1" resp `shouldSatisfy` isRight test_delete :: Spec test_delete = describe "/subaccounts/delete.json" $ it "should delete a subaccount" $ do raw <- getEnv "MANDRILL_API_KEY" resp <- runMandrill (ApiKey $ Text.pack raw) $ Subaccounts.delete "acc-1" resp `shouldSatisfy` isRight test_update :: Spec test_update = describe "/subaccounts/update.json" $ it "update a subaccount" $ do raw <- getEnv "MANDRILL_API_KEY" resp <- runMandrill (ApiKey $ Text.pack raw) $ Subaccounts.update "acc-1" "My Acc" "yes, indeed." 50 resp `shouldSatisfy` isRight test_info :: Spec test_info = describe "/subaccounts/info.json" $ it "should return some info about a subaccount" $ do raw <- getEnv "MANDRILL_API_KEY" resp <- runMandrill (ApiKey $ Text.pack raw) $ do _ <- Subaccounts.add "acc-1" "My Acc" "yes, indeed." 50 Subaccounts.info "acc-1" resp `shouldSatisfy` isRight test_add :: Spec test_add = describe "/subaccounts/add.json" $ it "should add a subaccount" $ do raw <- getEnv "MANDRILL_API_KEY" resp <- runMandrill (ApiKey $ Text.pack raw) $ Subaccounts.add "acc-1" "My Acc" "yes, indeed." 50 resp `shouldSatisfy` isRight test_list :: Spec test_list = describe "/subaccounts/list.json" $ it "should list all subaccounts" $ do raw <- getEnv "MANDRILL_API_KEY" resp <- runMandrill (ApiKey $ Text.pack raw) $ Subaccounts.list "acc-1" resp `shouldSatisfy` isRight
krgn/hamdrill
test/Network/API/Mandrill/SubaccountsSpec.hs
mit
2,692
0
14
637
682
333
349
77
1
{-# LANGUAGE ScopedTypeVariables #-} {-| Module : Labyrinth.Machine2d Description : labyrinth state machine Copyright : (c) deweyvm 2014 License : MIT Maintainer : deweyvm Stability : experimental Portability : unknown 2d state machine automata generating functions. -} module Labyrinth.Machine2d( (<.>), occuCount, negate, vertStrip, clearBorder ) where import Prelude hiding(foldr, negate) import Data.Maybe import Data.Foldable import Control.Applicative import Labyrinth.Data.Array2d import Labyrinth.Util -- | Apply a list of endomorphisms to an initial value (<.>) :: Foldable t => a -> t (a -> a) -> a (<.>) = flip (foldr (.) id) getOccupants :: Array2d a -> Point -> [a] getOccupants arr (i, j) = extract [ (i + x, j + y) | x <- [-1..1], y <- [-1..1] ] where extract = catMaybes . map (geti arr) countOccupants :: (a -> Bool) -> Array2d a -> Point -> Int countOccupants f = (count f) .: (getOccupants) -- | Maps to True iff the number of occupants of a given node is >= k. occuCount :: Int -> Array2d Bool -> Array2d Bool occuCount k arr = (\pt _ -> (countOccupants id arr pt) >= k) <$*> arr -- | Negates the entire array. negate :: Array2d Bool -> Array2d Bool negate = (<$>) not -- | Clears vertical strips with a regular spacing. vertStrip :: Bool -> Int -> Array2d Bool -> Array2d Bool vertStrip b mods = (<$*>) (\(i, j) p -> select p b (modZero i || modZero j)) where modZero k = k `mod` mods == 0 -- | Clears a border around the edge of the array. clearBorder :: Int -> Array2d Bool -> Array2d Bool clearBorder thick arr@(Array2d cols rows _) = (\(i, j) p -> i < thick || j < thick || i > cols - thick - 1 || j > rows - thick - 1 || p) <$*> arr
deweyvm/labyrinth
src/Labyrinth/Machine2d.hs
mit
1,724
0
19
373
561
306
255
32
1
module Main where import System.Environment import Text.ParserCombinators.Parsec hiding (spaces) main :: IO() main = do args <- getArgs putStrLn (readExpr (args !! 0)) symbol :: Parser Char symbol = oneOf "!$%&|*+-/:<=?>@^_~#" readExpr :: String -> String readExpr input = case parse (spaces >> symbol) "lisp" input of Left err -> "No match: " ++ show err Right val -> "Found value" spaces :: Parser () spaces = skipMany1 space
brianj-za/wyas
simpleparser1.hs
mit
440
0
11
81
156
80
76
15
2
{-| Module : Language.GoLite.Monad.Traverse Description : Traversing annotated syntax trees with class Copyright : (c) Jacob Errington and Frederic Lafrance, 2016 License : MIT Maintainer : [email protected] Stability : experimental Defines a type family based approach for traversing general annotated syntax trees. -} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} module Language.Common.Monad.Traverse ( module Control.Monad.Except , module Control.Monad.Identity , module Control.Monad.State , MonadTraversal (..) , Traversal (..) ) where import Control.Monad.Except import Control.Monad.Identity import Control.Monad.State -- | The class of monads that perform traversals of syntax trees. class ( Monad m , MonadState (TraversalState m) m , MonadError (TraversalException m) m ) => MonadTraversal m where -- | Fatal errors that can occur during the traversal. type TraversalException m :: * -- | Non-fatal errors that can occur during the traversal. type TraversalError m :: * -- | The state of the traversal. type TraversalState m :: * -- | Issues a non-fatal error, but continues the traversal. -- -- The non-fatal errors are accumulated in the state. reportError :: TraversalError m -> m () -- | Extracts the non-fatal errors from the traversal state. getErrors :: TraversalState m -> [TraversalError m] -- | Helper for common types of traversals. newtype Traversal e s a = Traversal { runTraversal :: ExceptT e ( StateT s Identity ) a -- ^ Extract the transformer stack from the 'Traversal' wrapper. } deriving ( Functor , Applicative , Monad , MonadError e , MonadState s )
djeik/goto
libgoto/Language/Common/Monad/Traverse.hs
mit
1,882
0
9
479
237
146
91
35
0
{- H-99 Problems Copyright 2015 (c) Adrian Nwankwo (Arcaed0x) Problem : 14 Description : Duplicate the elements of a list. License : MIT (See LICENSE file) -} copyTwice :: [a] -> [a] copyTwice [] = [] copyTwice (x:xs) = x : x : copyTwice xs
Arcaed0x/H-99-Solutions
src/prob14.hs
mit
274
0
7
78
55
29
26
3
1
module Parser where import Lambda import Type import Control.Monad import Data.Char import Text.Parsec import Text.Parsec.Expr import Text.Parsec.Language import qualified Text.Parsec.Token as Token lexer = Token.makeTokenParser style where operators = ["+", "-", "*", "/", "==", ">=", "<=", "<", ">", "/=", ","] words = ["if", "then", "else", "case", "of", "true", "false", "-|>", "let", "in"] style = haskellStyle {Token.reservedOpNames = operators, Token.reservedNames = words} reservedWords = Token.reserved lexer reservedOpera = Token.reservedOp lexer identifiers = Token.identifier lexer parens = Token.parens lexer idNumbers = Token.natural lexer wSpace x = do Token.whiteSpace lexer r <- x eof return r expLambda = do reservedOpera "\\" lam <- many1 identifiers reservedOpera "." ex1 <- build return $ foldr Lam ex1 lam variable = do x <- identifiers return (Var x) variable2 = do x <- identifiers return x numbers = do n <- idNumbers return (Lit (LInt (fromIntegral n))) boolean = do reservedWords "true" return (Lit (LBool True)) <|> do reservedWords "false" return (Lit (LBool False)) ifTE = do reservedWords "if" ex1 <- build reservedWords "then" ex2 <- build reservedWords "else" ex3 <- build return (If ex1 ex2 ex3) caOf = do reservedWords "case" ex1 <- build reservedWords "of" pats <- sepBy aPats $ reservedOpera ";" return (Case ex1 pats) aPats = do pat1 <- patterns reservedWords "-|>" ex2 <- build return (pat1, ex2) <|> do pat2 <- patterns reservedWords "-|>" ex3 <- build return (pat2, ex3) patterns = do xxx <- parens bPats return xxx <|> do x <- variable2 return (PVar x) <|> do n <- idNumbers return (PLit (LInt (fromIntegral n))) <|> do reservedWords "true" return (PLit (LBool True)) <|> do reservedWords "false" return (PLit (LBool False)) bPats = do x <- identifC patx <- many patterns return (PCon x patx) identifC = do a <- upper id <- variable2 return $ (a:id) operator = [[Postfix ((reservedOpera "+") >> return (App (Var "+")))], [Postfix ((reservedOpera "-") >> return (App (Var "-")))], [Postfix ((reservedOpera "*") >> return (App (Var "*")))], [Postfix ((reservedOpera "/") >> return (App (Var "/")))], [Postfix ((reservedOpera "<") >> return (App (Var "<")))], [Postfix ((reservedOpera ">") >> return (App (Var ">")))], [Postfix ((reservedOpera "==") >> return (App (Var "==")))], [Postfix ((reservedOpera "=<") >> return (App (Var "=<")))], [Postfix ((reservedOpera "=>") >> return (App (Var "=>")))], [Postfix ((reservedOpera "/=") >> return (App (Var "/=")))], [Infix (return ((App))) AssocNone]] build = buildExpressionParser operator build2 build2 = parens build <|> boolean <|> ifTE <|> variable <|> numbers <|> expLambda <|> caOf convert = destroy . parsing parsing iN = parse (wSpace build) "error" iN destroy (Right o) = o destroy (Left o) = error "verify the syntax of the expression"
LeonardoRigon/TypeInfer-LambdaExpressions-in-Haskell
Parser.hs
mit
4,099
0
16
1,700
1,312
647
665
106
1
module Nodes.Expression where import Data.Tree (Tree (Node)) import Nodes data Expr = Op { operator :: String, left :: Expr, right :: Expr } | StrLit { str :: String } | IntLit { int :: Int } | FloatLit { float :: Double } instance AstNode Expr where ast (Op operator left right) = Node operator [ast left, ast right] ast (StrLit str) = Node ("\"" ++ str ++ "\"") [] ast (IntLit int) = Node (show int) [] ast (FloatLit float) = Node (show float) []
milankinen/cbhs
src/nodes/Expression.hs
mit
507
0
9
146
212
116
96
13
0
{-# OPTIONS_GHC -fno-warn-orphans #-} import Application.Types import Handler.Admin import Handler.Block import Handler.Room import Handler.Snapshot import Handler.Socket import Handler.Instances import Import import Control.Concurrent.STM import Control.Monad.Logger (runStderrLoggingT) import Control.Monad.Trans.Resource (runResourceT) import Data.Map import Database.Persist.Postgresql import Yesod.Static mkYesodDispatch "App" resourcesApp openConnectionCount :: Int openConnectionCount = 10 connectionString :: ConnectionString connectionString = "host=localhost port=5432 user=creek dbname=creek password=creek" main :: IO () main = runStderrLoggingT $ withPostgresqlPool connectionString openConnectionCount $ \pool -> liftIO $ do runResourceT $ flip runSqlPool pool $ runMigration migrateAll state <- atomically $ newTVar myState channel <- atomically newBroadcastTChan socketStates' <- atomically $ newTVar $ singleton (InstanceId "0") (SocketState state channel) s <- static "static" --warpEnv requires $PORT to be set warpEnv $ App pool socketStates' s
kRITZCREEK/FROST-Backend
src/Main.hs
mit
1,248
0
14
299
252
132
120
-1
-1
module HaskovSpec where import Haskov (fromList,imap,hmatrix,walk,walkFrom,steady,steadyState,statesI) import System.Random import Test.Hspec import qualified Data.Set as Set import qualified Numeric.LinearAlgebra.Data as Dat import Data.List (intercalate) import Control.Monad (unless,when) testTransitions = [ (("A", "B"), 0.3) , (("A", "A"), 0.7) , (("B", "C"), 1.0) , (("C", "A"), 1.0) ] spec :: Spec spec = describe "haskov" $ do -- describe "steadyState" $ do -- -- it "should always contain positive numbers" $ do -- let -- transitions = [ (("A", "B"), 1.0), (("B", "C"), 1.0), (("C", "A"), 1.0)] -- haskov = fromList transitions -- s = steadyState haskov -- --mapM (\(s, p) -> s `shouldSatisfy` (> 0)) -- print s -- True `shouldBe` True describe "A haskov walk" $ do -- could use quickcheck for better tests it "should never do invalid transitions when transitions are ordered" $ do let transitions = [(("A", "B"), 1.0), (("B", "C"), 1.0), (("C", "A"), 1.0)] valid = map fst transitions markov = fromList transitions gen <- getStdGen res <- walk 10 markov gen expectOnlyValidTransitions transitions res it "should never do invalid transitions when transtions are not ordered" $ do let transitions = [ (("C", "A"), 1.0), (("A", "B"), 1.0), (("B", "C"), 1.0)] valid = map fst transitions haskov = fromList transitions gen <- getStdGen res <- walk 3 haskov gen expectOnlyValidTransitions transitions res describe "A haskov walkFrom" $ do it "starts with the head initial state" $ do let markov = fromList testTransitions gen <- getStdGen res <- walkFrom "B" 10 markov gen head res `shouldBe` "B" it "just some test" $ do let markov = fromList testTransitions index = imap markov matrix = hmatrix markov start = "A" gen <- getStdGen res <- walkFrom "B" 10 markov gen --putStrLn $ "index: " ++ ( show index) --putStrLn $ "matrix: " ++ ( show matrix) --putStrLn $ "result from " ++ start ++ ": " ++ ( show res) return () expectTrue :: HasCallStack => String -> Bool -> Expectation expectTrue msg b = unless b (expectationFailure msg) expectOnlyValidTransitions transitions actual = do let valid = map fst transitions actualTransitions = zip actual (drop 1 actual) actualUnique = Set.fromList actualTransitions invalid = Set.filter (\e -> not $ elem e valid) actualUnique len = length invalid invalidMsg inv = "invalid transitions encountered: " ++ ( intercalate ", " (Set.toList (Set.map (\(a,b) -> a ++ "->" ++ b) inv))) expectTrue (invalidMsg invalid) $ len == 0
mazuschlag/haskov
test/HaskovSpec.hs
mit
2,899
0
20
828
760
409
351
-1
-1
-- The solution of exercise 1.12 -- The following pattern of numbers is called Pascal's triangle. -- -- 1 -- 1 1 -- 1 2 1 -- 1 3 3 1 -- 1 4 6 4 1 -- -- The numbers at the edge of the triangle are all 1, and each number -- inside the triangle is the sum of the two numbers above it. Write a -- procedure that computes elements of Pascal's triangle by means of a -- recursive process. -- -- Run 'cabal install vector' first! import qualified Data.Vector as V -- Compute combinarotial number by means of a recursive process recursive_pascal :: (Eq a, Integral a) => a -> a -> a recursive_pascal m 0 = 1 recursive_pascal m n | m < 0 || n < 0 || m < n = error "wrong number in pascal triangle." | n == m = 1 | otherwise = recursive_pascal (m - 1) (n - 1) + recursive_pascal (m - 1) n -- The procedure computes factorial numbers by means of an iterative -- process, with linear complexity. fact_iter product counter maxc = if counter > maxc then product else fact_iter (counter * product) (counter + 1) maxc factorial n = fact_iter 1 1 n -- -- We can use the mathematical definition of combinatorial numbers to -- simply computes them: -- -- m! factorial(m) -- C(m, n) = ------------- = ------------------------------- -- n! (m - n)! factorial(n) * factorial(m - n) -- -- m * (m - 1) * ... * (m - n + 1) -- = --------------------------------- -- factorial(n) -- -- Thus we can write a new procedure in scheme and it is very simple. -- Notice that: -- -- fact_iter 1 a b = a * (a + 1) * ... * (b - 1) * b -- -- We have: C(m, n) = fact-iter(1, m - n + 1, m) / fact-iter(1, 1, n) -- This formula only does (2 * n - 1) times of multiplication / division. -- -- Computes the combinatorial numbers combinatorial :: (Eq a, Integral a) => a -> a -> a combinatorial m n = if (n * 2) > m then (fact_iter 1 (n + 1) m) `div` (fact_iter 1 1 (m - n)) else (fact_iter 1 (m - n + 1) m) `div` (fact_iter 1 1 n) -- -- There also exists another algorithm, according to the formula given by -- the Pascal's triangle: -- -- C(m, n) = C(m - 1, n - 1) + C(m - 1, n) (m, n >= 1) -- -- We make a vector v with init value #(1, 0, 0, ... , 0) with length = -- n + 1. and then make a new vector v': -- -- v'(n) = v(n) + v(n - 1) (1 <= n <= count) -- -- where the variable `count` means the number of non-zero elements in the -- vector v. After this operation, we get v' = #(1, 1, 0, ... , 0) with -- length = n + 1. Continue doing such an operation on v', we get v'' = -- #(1, 2, 1, ... , 0) and v''' = #(1, 3, 3, 1, ... , 0). We can get all -- the elements on m th row in Pascal's triangle, using this algorithm. -- Besides, the algorithm behaves well on complexity analysis, for we only -- do O(m ^ 2) times of addition to compute all numbers C(m, k). -- -- Now we realize this algorithm in Haskell... -- -- _ _____ _____ _____ _ _ _____ ___ ___ _ _ -- / \|_ _|_ _| ____| \ | |_ _|_ _/ _ \| \ | | -- / _ \ | | | | | _| | \| | | | | | | | | \| | -- / ___ \| | | | | |___| |\ | | | | | |_| | |\ | -- /_/ \_\_| |_| |_____|_| \_| |_| |___\___/|_| \_| -- -- The vector package is needed here! Run -- -- cabal install vector -- -- first and use Vector package. -- -- This function computes the next line (vector) in Pascal's triangle. -- For example, it returns [1,5,10,10,5,1] if the input is [1,4,6,4,1]. pascal_updateVec :: (Eq a, Integral a) => V.Vector a -> V.Vector a pascal_updateVec vector = V.zipWith (+) (V.snoc vector 0) (V.cons 0 vector) -- This function computes the (n+1)-th line (vector) in Pascal's Triangle. -- For example, it returns [1,5,10,10,5,1] if the input is 5. pascalList :: (Eq a, Integral a) => a -> V.Vector a pascalList n = let nextVec vector 0 = vector nextVec vector count = nextVec (pascal_updateVec vector) (count - 1) v0 = V.fromList [1 :: Integral a => a] in nextVec v0 n -- The pascal number pascal n m = (pascalList n) V.! m
perryleo/sicp
ch1/sicpc1e12.hs
mit
4,245
0
12
1,235
618
355
263
33
2
import Data.Numbers.Primes import Data.List primeFactors' = map (\all@(x:xs) -> (x, (length all))) . group . primeFactors sumOfFactors :: (Integral a, Eq a) => (a, a) -> a sumOfFactors (_, 0) = 1 sumOfFactors (x, y) = (x^y) + (sumOfFactors (x, (y - 1))) sumOfProperDivisors n = (product $ map sumOfFactors (primeFactors' n)) - n isAbundant n = (sumOfProperDivisors n) > n isNotAbundant = not . isAbundant abundants = [x | x <- [12..14062], isAbundant x]
t00n/ProjectEuler
23.hs
epl-1.0
460
0
12
81
231
127
104
10
1
{-# language FlexibleContexts #-} module NFA.Roll where -- $Id$ import Autolib.NFA import Autolib.NFA.Some import NFA.Property roll :: NFAC c Int => [ Property c ] -> IO ( NFA c Int ) roll props = do let [ alpha ] = do Alphabet alpha <- props ; return alpha let [ s ] = do Max_Size s <- props ; return s nontrivial alpha s
marcellussiegburg/autotool
collection/src/NFA/Roll.hs
gpl-2.0
356
0
13
98
135
66
69
11
1
module SimpleClass where data Color a = Red a | Blue a data MyList a = MyNil | MyCons a (MyList a) data MPList a b = MPNil | MPCons a b (MPList a b) myEqual :: Eq a => a -> a -> Bool myEqual x y = if x == y then True else False instance Eq a => Eq (Color a) instance Eq a => Eq (MyList a) class Joker a where methodOne :: a -> a -> Bool methodTwo :: a -> Bool -> Color a instance (Joker a, Eq a) => Joker (Color a) where methodOne = myEqual instance (Joker a, Eq a) => Joker (MyList a) where methodOne = myEqual methodTwo x y = if y == True then Red x else Blue x instance (Joker a, Eq a, Eq b) => Joker (MPList a b)
nevrenato/Hets_Fork
Haskell/test/HOL/ex_class.hs
gpl-2.0
646
0
9
171
318
166
152
17
2
#!/usr/bin/runhugs -- created on 2009-01-21 --does simple HTML escaping on a main body text import System.Environment(getArgs) import Data.List(groupBy) flatmap f = concat . map f toHtml = flatmap code where code '&' = "&amp;" code '<' = "&lt;" code '>' = "&gt;" code c = [c] allnb = flatmap (\' ' -> "&nbsp;") multinb = flatmap inter . groupBy (==) where inter = \w -> case w of (' ':' ':_) -> allnb w _ -> w eachLine s = allnb i ++ multinb l where (i,l) = span (==' ') s tr = unlines . map eachLine . lines . toHtml where trf fi fo = do i <- readFile fi writeFile fo (tr i) main = do args <- getArgs case args of [i@(_:_),o@(_:_)] -> trf i o otherwise -> fail "params: inputfile outputfile"
google-code/bkil-open
volatile/calc/htmesc.hs
gpl-2.0
818
0
13
261
320
166
154
24
4
{-# LANGUAGE TemplateHaskell #-} module Control.Isomorphism.Partial.Constructors ( nil , cons , listCases , left , right , nothing , just ) where import Prelude () import Data.Bool (Bool, otherwise) import Data.Either (Either (Left, Right)) import Data.Eq (Eq ((==))) import Data.Maybe (Maybe (Just, Nothing)) import Control.Isomorphism.Partial.Unsafe (Iso (Iso)) import Control.Isomorphism.Partial.TH (defineIsomorphisms) nil :: Iso () [alpha] nil = Iso f g where f () = Just [] g [] = Just () g _ = Nothing cons :: Iso (alpha, [alpha]) [alpha] cons = Iso f g where f (x, xs) = Just (x : xs) g (x : xs) = Just (x, xs) g _ = Nothing listCases :: Iso (Either () (alpha, [alpha])) [alpha] listCases = Iso f g where f (Left ()) = Just [] f (Right (x, xs)) = Just (x : xs) g [] = Just (Left ()) g (x:xs) = Just (Right (x, xs)) $(defineIsomorphisms ''Either) $(defineIsomorphisms ''Maybe)
ducis/scraper-dsl-open-snapshot
partial-isomorphisms-0.2/src/Control/Isomorphism/Partial/Constructors.hs
gpl-2.0
997
0
10
266
452
253
199
34
3
{- | Module : $Header$ Copyright : (c) Klaus Hartke, Uni Bremen 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable -} module ModalCaslToCtl where import Control.Monad as Monad import Data.Maybe as Maybe import ModalCasl as Casl import Ctl as Ctl {------------------------------------------------------------------------------} {- -} {- Convert Modal CASL formulas to CTL formulas -} {- -} {------------------------------------------------------------------------------} convert :: Casl.StateFormula a -> Maybe (Ctl.Formula a) convert (Casl.Var x) = Just (Ctl.Atom x) convert (Casl.Snot phi) = liftM Ctl.Not (convert phi) convert (Casl.Sand phi psi) = liftM2 Ctl.And (convert phi) (convert psi) convert (Casl.Sor phi psi) = liftM2 Ctl.Or (convert phi) (convert psi) convert (Casl.A (Casl.X phi)) = liftM Ctl.AX (convert' phi) convert (Casl.E (Casl.X phi)) = liftM Ctl.EX (convert' phi) convert (Casl.A (Casl.G phi)) = liftM Ctl.AG (convert' phi) convert (Casl.E (Casl.G phi)) = liftM Ctl.EG (convert' phi) convert (Casl.A (Casl.F phi)) = liftM Ctl.AF (convert' phi) convert (Casl.E (Casl.F phi)) = liftM Ctl.EF (convert' phi) convert (Casl.A (Casl.W phi psi)) = convert (Casl.A ((phi `Casl.Pand` psi) `Casl.B` ((Casl.Pnot phi) `Casl.Pand` psi))) convert (Casl.E (Casl.W phi psi)) = convert (Casl.E ((phi `Casl.Pand` psi) `Casl.B` ((Casl.Pnot phi) `Casl.Pand` psi))) convert (Casl.A (Casl.U phi psi)) = convert (Casl.A (psi `Casl.Pand` ((Casl.Pnot phi) `Casl.Pand` (Casl.Pnot psi)))) convert (Casl.E (Casl.U phi psi)) = convert (Casl.E (psi `Casl.Pand` ((Casl.Pnot phi) `Casl.Pand` (Casl.Pnot psi)))) convert (Casl.A (Casl.B phi psi)) = convert (Casl.A (Casl.Pnot ((Casl.Pnot phi) `Casl.U'` psi))) convert (Casl.E (Casl.B phi psi)) = convert (Casl.E (Casl.Pnot ((Casl.Pnot phi) `Casl.U'` psi))) convert (Casl.A (Casl.W' phi psi)) = convert (Casl.A ((Casl.Pnot phi) `Casl.U'` (Casl.Pand phi psi))) convert (Casl.E (Casl.W' phi psi)) = convert (Casl.E ((Casl.Pnot phi) `Casl.U'` (Casl.Pand phi psi))) convert (Casl.A (Casl.U' phi psi)) = liftM2 Ctl.AU (convert' phi) (convert' psi) convert (Casl.E (Casl.U' phi psi)) = liftM2 Ctl.EU (convert' phi) (convert' psi) convert (Casl.A (Casl.B' phi psi)) = convert (Casl.A ((Casl.Pnot phi) `Casl.U'` (Casl.Pand phi (Casl.Pnot psi)))) convert (Casl.E (Casl.B' phi psi)) = convert (Casl.E ((Casl.Pnot phi) `Casl.U'` (Casl.Pand phi (Casl.Pnot psi)))) convert _ = Nothing convert' :: Casl.PathFormula a -> Maybe (Ctl.Formula a) convert' (State phi) = convert phi convert' (Casl.Pnot phi) = liftM Ctl.Not (convert' phi) convert' (Casl.Pand phi psi) = liftM2 Ctl.And (convert' phi) (convert' psi) convert' (Casl.Por phi psi) = liftM2 Ctl.Or (convert' phi) (convert' psi) convert' _ = Nothing {------------------------------------------------------------------------------}
nevrenato/Hets_Fork
Temporal/ModalCaslToCtl.hs
gpl-2.0
3,361
0
14
858
1,389
715
674
35
1
{- How to break a vigenere (repeating key xor) cipher -} module Vigenere where import Data.Bits(shift, xor, (.&.)) import Data.Char (ord, chr) import Data.List (sortBy, transpose) import Data.List.Split (chunksOf) import Base64 (base64Decode) import DecryptXor import XorEncrypt import Plaintext import Crypto maxKeyLength = 40 {- Hamming Distance -} bitcount :: Int -> Int bitcount 0 = 0 bitcount n = (n .&. 1) + (bitcount (shift n (-1))) hamming :: Int -> Int -> Int hamming a b = bitcount (a `xor` b) hammingDistance s1 s2 = sum $ map (\p -> hamming (fst p) (snd p)) (zip s1 s2) {- Find the keysize -} numKeys = 16 normHamming keysize ciphertext = fromIntegral (hammingDistance (take (keysize * numKeys) ciphertext) (take (keysize * numKeys) (drop (keysize * numKeys) ciphertext))) / (fromIntegral (keysize * numKeys)) checkKeyLengths cipher = sortBy (\p1 p2 -> compare (snd p1) (snd p2)) [(l, normHamming l cipher) | l <- [2..maxKeyLength]] bestKeyLength = fst.head.checkKeyLengths {- Chunk the cipher up -} transposeChunks n l = transpose $ chunksOf n l {- Find the key -} keys cipher = map findKey $ transposeChunks (bestKeyLength cipher) cipher ---Now, some manual decryption plainKeys :: [[Int]] plainKeys = [[118,55],[120],[100,111,118,55],[100,105,107,108,111,120],[102,103,107,121]] allKeys = [(a:b:c:d:e:[]) | a <- plainKeys!!0, b <- plainKeys!!1, c <- plainKeys!!2, d <- plainKeys!!3, e <- plainKeys!!4] allDecrypts = [xorEncrypt rawCipher (take (length rawCipher) (cycle k)) | k <- allKeys] likelies = [map chr pt | pt <- (filter isPlaintext allDecrypts)] ------------------------------------------ ---Ciphertext, base64 encoded------------- ------------------------------------------ ciphertext = ["HUIfTQsPAh9PE048GmllH0kcDk4TAQsHThsBFkU2AB4BSWQgVB0dQzNTTmVS", "BgBHVBwNRU0HBAxTEjwMHghJGgkRTxRMIRpHKwAFHUdZEQQJAGQmB1MANxYG", "DBoXQR0BUlQwXwAgEwoFR08SSAhFTmU+Fgk4RQYFCBpGB08fWXh+amI2DB0P", "QQ1IBlUaGwAdQnQEHgFJGgkRAlJ6f0kASDoAGhNJGk9FSA8dDVMEOgFSGQEL", "QRMGAEwxX1NiFQYHCQdUCxdBFBZJeTM1CxsBBQ9GB08dTnhOSCdSBAcMRVhI", "CEEATyBUCHQLHRlJAgAOFlwAUjBpZR9JAgJUAAELB04CEFMBJhAVTQIHAh9P", "G054MGk2UgoBCVQGBwlTTgIQUwg7EAYFSQ8PEE87ADpfRyscSWQzT1QCEFMa", "TwUWEXQMBk0PAg4DQ1JMPU4ALwtJDQhOFw0VVB1PDhxFXigLTRkBEgcKVVN4", "Tk9iBgELR1MdDAAAFwoFHww6Ql5NLgFBIg4cSTRWQWI1Bk9HKn47CE8BGwFT", "QjcEBx4MThUcDgYHKxpUKhdJGQZZVCFFVwcDBVMHMUV4LAcKQR0JUlk3TwAm", "HQdJEwATARNFTg5JFwQ5C15NHQYEGk94dzBDADsdHE4UVBUaDE5JTwgHRTkA", "Umc6AUETCgYAN1xGYlUKDxJTEUgsAA0ABwcXOwlSGQELQQcbE0c9GioWGgwc", "AgcHSAtPTgsAABY9C1VNCAINGxgXRHgwaWUfSQcJABkRRU8ZAUkDDTUWF01j", "OgkRTxVJKlZJJwFJHQYADUgRSAsWSR8KIgBSAAxOABoLUlQwW1RiGxpOCEtU", "YiROCk8gUwY1C1IJCAACEU8QRSxORTBSHQYGTlQJC1lOBAAXRTpCUh0FDxhU", "ZXhzLFtHJ1JbTkoNVDEAQU4bARZFOwsXTRAPRlQYE042WwAuGxoaAk5UHAoA", "ZCYdVBZ0ChQLSQMYVAcXQTwaUy1SBQsTAAAAAAAMCggHRSQJExRJGgkGAAdH", "MBoqER1JJ0dDFQZFRhsBAlMMIEUHHUkPDxBPH0EzXwArBkkdCFUaDEVHAQAN", "U29lSEBAWk44G09fDXhxTi0RAk4ITlQbCk0LTx4cCjBFeCsGHEETAB1EeFZV", "IRlFTi4AGAEORU4CEFMXPBwfCBpOAAAdHUMxVVUxUmM9ElARGgZBAg4PAQQz", "DB4EGhoIFwoKUDFbTCsWBg0OTwEbRSonSARTBDpFFwsPCwIATxNOPBpUKhMd", "Th5PAUgGQQBPCxYRdG87TQoPD1QbE0s9GkFiFAUXR0cdGgkADwENUwg1DhdN", "AQsTVBgXVHYaKkg7TgNHTB0DAAA9DgQACjpFX0BJPQAZHB1OeE5PYjYMAg5M", "FQBFKjoHDAEAcxZSAwZOBREBC0k2HQxiKwYbR0MVBkVUHBZJBwp0DRMDDk5r", "NhoGACFVVWUeBU4MRREYRVQcFgAdQnQRHU0OCxVUAgsAK05ZLhdJZChWERpF", "QQALSRwTMRdeTRkcABcbG0M9Gk0jGQwdR1ARGgNFDRtJeSchEVIDBhpBHQlS", "WTdPBzAXSQ9HTBsJA0UcQUl5bw0KB0oFAkETCgYANlVXKhcbC0sAGgdFUAIO", "ChZJdAsdTR0HDBFDUk43GkcrAAUdRyonBwpOTkJEUyo8RR8USSkOEENSSDdX", "RSAdDRdLAA0HEAAeHQYRBDYJC00MDxVUZSFQOV1IJwYdB0dXHRwNAA9PGgMK", "OwtTTSoBDBFPHU54W04mUhoPHgAdHEQAZGU/OjV6RSQMBwcNGA5SaTtfADsX", "GUJHWREYSQAnSARTBjsIGwNOTgkVHRYANFNLJ1IIThVIHQYKAGQmBwcKLAwR", "DB0HDxNPAU94Q083UhoaBkcTDRcAAgYCFkU1RQUEBwFBfjwdAChPTikBSR0T", "TwRIEVIXBgcURTULFk0OBxMYTwFUN0oAIQAQBwkHVGIzQQAGBR8EdCwRCEkH", "ElQcF0w0U05lUggAAwANBxAAHgoGAwkxRRMfDE4DARYbTn8aKmUxCBsURVQf", "DVlOGwEWRTIXFwwCHUEVHRcAMlVDKRsHSUdMHQMAAC0dCAkcdCIeGAxOazkA", "BEk2HQAjHA1OAFIbBxNJAEhJBxctDBwKSRoOVBwbTj8aQS4dBwlHKjUECQAa", "BxscEDMNUhkBC0ETBxdULFUAJQAGARFJGk9FVAYGGlMNMRcXTRoBDxNPeG43", "TQA7HRxJFUVUCQhBFAoNUwctRQYFDE43PT9SUDdJUydcSWRtcwANFVAHAU5T", "FjtFGgwbCkEYBhlFeFsABRcbAwZOVCYEWgdPYyARNRcGAQwKQRYWUlQwXwAg", "ExoLFAAcARFUBwFOUwImCgcDDU5rIAcXUj0dU2IcBk4TUh0YFUkASEkcC3QI", "GwMMQkE9SB8AMk9TNlIOCxNUHQZCAAoAHh1FXjYCDBsFABkOBkk7FgALVQRO", "D0EaDwxOSU8dGgI8EVIBAAUEVA5SRjlUQTYbCk5teRsdRVQcDhkDADBFHwhJ", "AQ8XClJBNl4AC1IdBghVEwARABoHCAdFXjwdGEkDCBMHBgAwW1YnUgAaRyon", "B0VTGgoZUwE7EhxNCAAFVAMXTjwaTSdSEAESUlQNBFJOZU5LXHQMHE0EF0EA", "Bh9FeRp5LQdFTkAZREgMU04CEFMcMQQAQ0lkay0ABwcqXwA1FwgFAk4dBkIA", "CA4aB0l0PD1MSQ8PEE87ADtbTmIGDAILAB0cRSo3ABwBRTYKFhROHUETCgZU", "MVQHYhoGGksABwdJAB0ASTpFNwQcTRoDBBgDUkksGioRHUkKCE5THEVCC08E", "EgF0BBwJSQoOGkgGADpfADETDU5tBzcJEFMLTx0bAHQJCx8ADRJUDRdMN1RH", "YgYGTi5jMURFeQEaSRAEOkURDAUCQRkKUmQ5XgBIKwYbQFIRSBVJGgwBGgtz", "RRNNDwcVWE8BT3hJVCcCSQwGQx9IBE4KTwwdASEXF01jIgQATwZIPRpXKwYK", "BkdEGwsRTxxDSToGMUlSCQZOFRwKUkQ5VEMnUh0BR0MBGgAAZDwGUwY7CBdN", "HB5BFwMdUz0aQSwWSQoITlMcRUILTxoCEDUXF01jNw4BTwVBNlRBYhAIGhNM", "EUgIRU5CRFMkOhwGBAQLTVQOHFkvUkUwF0lkbXkbHUVUBgAcFA0gRQYFCBpB", "PU8FQSsaVycTAkJHYhsRSQAXABxUFzFFFggICkEDHR1OPxoqER1JDQhNEUgK", "TkJPDAUAJhwQAg0XQRUBFgArU04lUh0GDlNUGwpOCU9jeTY1HFJARE4xGA4L", "ACxSQTZSDxsJSw1ICFUdBgpTNjUcXk0OAUEDBxtUPRpCLQtFTgBPVB8NSRoK", "SREKLUUVAklkERgOCwAsUkE2Ug8bCUsNSAhVHQYKUyI7RQUFABoEVA0dWXQa", "Ry1SHgYOVBFIB08XQ0kUCnRvPgwQTgUbGBwAOVREYhAGAQBJEUgETgpPGR8E", "LUUGBQgaQRIaHEshGk03AQANR1QdBAkAFwAcUwE9AFxNY2QxGA4LACxSQTZS", "DxsJSw1ICFUdBgpTJjsIF00GAE1ULB1NPRpPLF5JAgJUVAUAAAYKCAFFXjUe", "DBBOFRwOBgA+T04pC0kDElMdC0VXBgYdFkU2CgtNEAEUVBwTWXhTVG5SGg8e", "AB0cRSo+AwgKRSANExlJCBQaBAsANU9TKxFJL0dMHRwRTAtPBRwQMAAATQcB", "FlRlIkw5QwA2GggaR0YBBg5ZTgIcAAw3SVIaAQcVEU8QTyEaYy0fDE4ITlhI", "Jk8DCkkcC3hFMQIEC0EbAVIqCFZBO1IdBgZUVA4QTgUWSR4QJwwRTWM="] rawCipher = base64Decode $ unlines ciphertext
CharlesRandles/cryptoChallenge
vigenere.hs
gpl-3.0
7,051
0
14
1,515
898
519
379
103
1
{-# LANGUAGE TupleSections #-} {-# LANGUAGE ScopedTypeVariables #-} {-| Module : Hypercube.Game Description : The main game loops and start function Copyright : (c) Jaro Reinders, 2017 License : GPL-3 Maintainer : [email protected] This module contains the @start@ function, the @mainLoop@ and the @draw@ function. TODO: find a better place for the @draw@ function. -} module Hypercube.Game where import Hypercube.Chunk import Hypercube.Types import Hypercube.Config import Hypercube.Util import Hypercube.Shaders import Hypercube.Input import Hypercube.Error --import qualified Debug.Trace as D import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.State import Control.Lens import Data.Maybe import Foreign.Ptr import qualified Graphics.Rendering.OpenGL as GL import qualified Graphics.GLUtil as U import Graphics.UI.GLFW as GLFW import Linear import qualified Data.Vector.Storable as VS import qualified Data.Map.Strict as M import Control.Concurrent.STM.TChan import Control.Monad.STM import Control.Applicative import Data.Int (Int8) --import System.Mem (performMinorGC) import Data.List import Data.IORef import Foreign.Storable (sizeOf) import Foreign.C.Types (CPtrdiff (CPtrdiff)) import Data.Function import Data.MemoTrie start :: IO () start = withWindow 1280 720 "Hypercube" $ \win -> do -- Disable the cursor GLFW.setCursorInputMode win GLFW.CursorInputMode'Disabled todo <- newIORef [] chan <- newTChanIO startChunkManager todo chan -- Generate a new game world game <- Game (Camera (V3 8 15 8) 0 0 5 0.05) <$> (realToFrac . fromJust <$> GLFW.getTime) <*> (fmap realToFrac . uncurry V2 <$> GLFW.getCursorPos win) <*> pure M.empty void $ flip runStateT game $ do -- vsync liftIO $ GLFW.swapInterval 1 p <- liftIO shaders -- Get the shader uniforms [modelLoc,viewLoc,projLoc] <- liftIO $ mapM (GL.get . GL.uniformLocation p) ["model","view","projection"] liftIO $ do -- Set shader GL.currentProgram GL.$= Just p do -- Load texture & generate mipmaps (Right texture) <- U.readTexture "blocks.png" GL.textureBinding GL.Texture2D GL.$= Just texture GL.textureFilter GL.Texture2D GL.$= ((GL.Nearest,Nothing),GL.Nearest) GL.generateMipmap' GL.Texture2D -- Set clear color GL.clearColor GL.$= GL.Color4 0.2 0.3 0.3 1 GLFW.setKeyCallback win (Just keyCallback) GL.cullFace GL.$= Just GL.Back GL.depthFunc GL.$= Just GL.Less mainLoop win todo chan viewLoc projLoc modelLoc unitDodecahedron :: [(Int, V3 Float)] unitDodecahedron = zip [1..] $ [[x,y,z] | x <- [1,-1], y <- [1,-1], z <- [1,-1]] ++ ([[0,x * phi, y / phi] | x <- [1,-1], y <- [1,-1]] >>= cyclicPermutations) >>= \[x,y,z] -> return (normalize (V3 x y z)) unitIcosahedron :: [(Int,V3 Float)] unitIcosahedron = zip [1..] $ [[0, x, y * phi] | x <- [1,-1], y <- [1,-1]] >>= cyclicPermutations >>= \[x,y,z] -> return (normalize (V3 x y z)) -- golden ratio phi :: Float phi = (1 + sqrt 5) / 2 cyclicPermutations :: [a] -> [[a]] cyclicPermutations xs = let l = length xs in take l $ map (take l) $ tails (cycle xs) visibleChunks :: Int -> Int -> V3 Float -> [V3 Int] visibleChunks height width gazeVec = memo3 f height width (fst (minimumBy (compare `on` distance gazeVec . snd) unitDodecahedron)) where f :: Int -> Int -> Int -> [V3 Int] f h w n = let gazeDir = fromJust (lookup n unitDodecahedron) fov :: Float fov = pi / 4 + 0.5 viewMat :: M44 Float viewMat = let p = (- (fromIntegral chunkSize * sqrt 3) / (2 * atan (fov / 2))) *^ gazeDir halfChunk = fromIntegral chunkSize / 2 *^ 1 in lookAt (p + halfChunk) halfChunk (V3 0 1 0) proj :: M44 Float proj = perspective fov (fromIntegral w / fromIntegral h) 0.1 1000 in sortOn (distance (0 :: V3 Double) . fmap fromIntegral) $ do let r = renderDistance v <- liftA3 V3 [-r..r] [-r..r] [-r..r] let projected = proj !*! viewMat !* model model = (identity & translation .~ (fromIntegral <$> (chunkSize *^ v))) !* (1 & _xyz .~ fromIntegral chunkSize / 2) normalized = liftA2 (^/) id (^. _w) $ projected guard $ all ((<= 1) . abs) $ normalized ^. _xyz return v draw :: Int -> Int -> V3 Float -> GL.UniformLocation -> IORef [V3 Int] -> StateT Game IO () draw height width gazeVec modelLoc todo = do let render :: V3 Int -> StateT Game IO [V3 Int] render pos = do m <- use world case M.lookup pos m of Nothing -> return [pos] Just c -> do _ <- liftIO (execStateT (renderChunk pos modelLoc) c) return [] playerPos <- fmap ((`div` chunkSize) . floor) <$> use (cam . camPos) liftIO . atomicWriteIORef todo . concat =<< mapM render (map (+ playerPos) (visibleChunks height width gazeVec)) mainLoop :: GLFW.Window -> IORef [V3 Int] -> TChan (V3 Int, Chunk, VS.Vector (V4 Int8)) -> GL.UniformLocation -> GL.UniformLocation -> GL.UniformLocation -> StateT Game IO () mainLoop win todo chan viewLoc projLoc modelLoc = do shouldClose <- liftIO $ GLFW.windowShouldClose win unless shouldClose $ do liftIO GLFW.pollEvents deltaTime <- do currentFrame <- realToFrac . fromJust <$> liftIO GLFW.getTime deltaTime <- (currentFrame -) <$> use lastFrame lastFrame .= currentFrame return deltaTime liftIO $ print $ 1/deltaTime keyboard win deltaTime mouse win deltaTime -- Handle Window resize (width, height) <- liftIO $ GLFW.getFramebufferSize win liftIO $ GL.viewport GL.$= (GL.Position 0 0, GL.Size (fromIntegral width) (fromIntegral height)) -- Clear buffers liftIO $ GL.clear [GL.ColorBuffer, GL.DepthBuffer] -- Change view matrix curCamPos <- use (cam . camPos) curGaze <- use (cam . gaze) viewMat <- liftIO $ toGLmatrix $ lookAt curCamPos (curCamPos + curGaze) (V3 0 1 0) GL.uniform viewLoc GL.$= viewMat -- Change projection matrix let proj = perspective (pi / 4) (fromIntegral width / fromIntegral height) 0.1 1000 projMat <- liftIO $ toGLmatrix proj GL.uniform projLoc GL.$= projMat do let loadVbos = do -- TODO: better timeout estimate (calculate time left until next frame) t <- liftIO $ (+ 0.001) . fromJust <$> GLFW.getTime liftIO (atomically (tryReadTChan chan)) >>= maybe (return ()) (\(pos,Chunk blk _ _ _ _,v) -> do m <- use world if pos `M.member` m then loadVbos else do let len = VS.length v vao <- GL.genObjectName GL.bindVertexArrayObject GL.$= Just vao vbo <- GL.genObjectName liftIO $ when (len > 0) $ do GL.bindBuffer GL.ArrayBuffer GL.$= Just vbo VS.unsafeWith v $ \ptr -> GL.bufferData GL.ArrayBuffer GL.$= (CPtrdiff (fromIntegral (sizeOf (undefined :: V4 Int8) * len)), ptr, GL.StaticDraw) -- Associate the VAO with the data of the VBO. -- The VBO doesn't need to be bound later when using the VAO. GL.vertexAttribPointer (GL.AttribLocation 0) GL.$= (GL.KeepIntegral, GL.VertexArrayDescriptor 4 GL.Byte 0 (intPtrToPtr 0)) GL.vertexAttribArray (GL.AttribLocation 0) GL.$= GL.Enabled GL.bindBuffer GL.ArrayBuffer GL.$= Nothing GL.bindVertexArrayObject GL.$= Nothing world %= M.insert pos (Chunk blk vbo vao len False) t' <- liftIO $ fromJust <$> GLFW.getTime when (t' < t) loadVbos) loadVbos liftIO $ printErrors "At the start of the loop" draw height width curGaze modelLoc todo liftIO $ printErrors "At the end of the loop" liftIO $ GLFW.swapBuffers win --liftIO $ performMinorGC mainLoop win todo chan viewLoc projLoc modelLoc
noughtmare/hypercube
src/Hypercube/Game.hs
gpl-3.0
8,212
0
40
2,231
2,786
1,408
1,378
-1
-1
{-# LANGUAGE MonadComprehensions #-} module Main (main) where import System.Environment import Fusion import Data.Foldable as T hiding (fold) main = do --runalltests 1 20 10000 1 20 10000 --runalltests (-1000000) 4001 1000000 (-1000000) 4001 1000000 --runalltests (-2100000000) 4000001 2100000000 (-2100000000) 4000001 2100000000 [_1,_2,_3] <- getArgs let astart = read _1; astep = read _2; alim = read _3 runalltests astart astep alim astart astep alim runalltests :: Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> IO () runalltests astart astep alim bstart bstep blim = do runbench (+) (+) "(+)" astart astep alim astart astep alim runbench (-) (-) "(-)" astart astep alim astart astep alim runbench (*) (*) "(*)" astart astep alim astart astep alim runbench div div "div" astart astep alim astart astep alim runbench mod mod "mod" astart astep alim astart astep alim runbench quot quot "quot" astart astep alim astart astep alim runbench rem rem "rem" astart astep alim astart astep alim runbench gcd gcd "gcd" astart astep alim astart astep alim runbench lcm lcm "lcm" astart astep alim astart astep alim runbench (==) (==) "(==)" astart astep alim astart astep alim runbench (<) (<) "(<)" astart astep alim astart astep alim runbench (<=) (<=) "(<=)" astart astep alim astart astep alim runbench (>) (>) "(>)" astart astep alim astart astep alim runbench (>=) (>=) "(>=)" astart astep alim astart astep alim runbench :: (Integer -> Integer -> a) -> (Int -> Int -> b) -> String -> Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> IO () runbench jop iop opstr astart astep alim bstart bstep blim = do intbench iop astart astep alim astart astep alim integerbench jop astart astep alim astart astep alim integerbench :: (Integer -> Integer -> a) -> Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> IO () integerbench op astart astep alim bstart bstep blim = do seqlist ([ a `op` b | a <- freeze (enumFromThenToNu astart (astart+astep) alim) , b <- freeze (enumFromThenToNu astart (astart+astep) alim)]) return () intbench :: (Int -> Int -> a) -> Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> IO () intbench op astart astep alim bstart bstep blim = do seqlist ([ a `op` b | a <- freeze (enumFromThenToNu (fromInteger astart) (fromInteger (astart+astep)) (fromInteger alim)) , b <- freeze (enumFromThenToNu (fromInteger astart) (fromInteger (astart+astep)) (fromInteger alim))]) return () seqlist :: MuList a -> IO () seqlist = T.foldr (\ x xs -> x `seq` xs) (return ())
jyp/ControlledFusion
integer/MainFusion.hs
gpl-3.0
2,635
30
18
514
1,042
532
510
58
1
import Control.Monad.Error import Control.Monad.Trans(liftIO) import Data.IORef(IORef, newIORef, readIORef, writeIORef) import Data.List(sort) import Data.Maybe(fromJust) import Graphics.UI.Gtk import System.IO.Unsafe(unsafePerformIO) import System.Random import Paths_dsgen import Dsgen.Cards import Dsgen.GUIState import Dsgen.SetSelect -- Global variable for holding row indices which should be deleted rowsToDelete :: IORef [Int] {-# NOINLINE rowsToDelete #-} rowsToDelete = unsafePerformIO (newIORef []) main :: IO () main = do -- GUI initializations initGUI builder <- builderNew gladeFilepath <- getDataFileName "res/gui/gui.glade" builderAddFromFile builder gladeFilepath window <- builderGetObject builder castToWindow "mainWindow" on window deleteEvent (liftIO mainQuit >> return False) -- Get widgets gui <- readGUI builder -- Load cards cardFiles <- cardFileNames cardse <- runErrorT $ readCardFiles cardFiles case cardse of Left s -> startupErrorQuit $ show s Right cs -> do -- Hook up signals hookSignals gui cs -- Start the GUI loop widgetShowAll window mainGUI hookSignals :: GUI -> [Card] -> IO () hookSignals gui cs = do on (selectSetButton gui) buttonActivated $ fillSelection gui cs on (rmvManualCardsButton gui) buttonActivated $ removeCards (manualCardsTreeView gui) (manualCardsListStore gui) on (rmvVetoedCardsButton gui) buttonActivated $ removeCards (vetoedCardsTreeView gui) (vetoedCardsListStore gui) return () hookCardListDrag (randomCardsTreeView gui) (randomCardsListStore gui) hookCardListDrag (manualCardsTreeView gui) (manualCardsListStore gui) hookCardListDrag (vetoedCardsTreeView gui) (vetoedCardsListStore gui) return () where hookCardListDrag tv ls = do tm <- fromJust `liftM` treeViewGetModel tv ts <- treeViewGetSelection tv -- treeSelectionSetMode ts SelectionMultiple textAtom <- atomNew "text/plain" tl <- targetListNew targetListAdd tl textAtom [TargetSameApp] 0 treeViewEnableModelDragDest tv tl [ActionCopy, ActionMove] treeViewEnableModelDragSource tv [Button1] tl [ActionMove] on tv dragDataGet $ \_ _ _ -> do selectionList <- liftIO $ treeSelectionGetSelectedRows ts let selectedRows = sort $ map head selectionList selectedCards <- liftIO $ mapM (listStoreGetValue ls) selectedRows selectionDataSetText $ show selectedCards liftIO $ writeIORef rowsToDelete selectedRows return () on tv dragDataReceived $ \ctx _ _ time -> do text <- fromJust `liftM` selectionDataGetText let rows = read text :: [CardListRow] liftIO $ sequence_ $ map (listStoreAppend ls) rows liftIO $ dragFinish ctx True True time return () on tv dragDataDelete $ \_ -> do rows <- readIORef rowsToDelete let sortedRows = reverse $ sort rows sequence_ $ map (listStoreRemove ls) sortedRows -- | Generate a random selection of cards and display it fillSelection :: GUI -> [Card] -> IO () fillSelection gui cs = do notebookSetCurrentPage (mainNotebook gui) 1 gst <- getGUIState gui cs let ssos = mkSetSelectOptions gst cs sgre <- runErrorT $ selectSet ssos case sgre of Left e -> putStrLn e -- TODO: use status bar! Right sgr -> do let lst = randomCardsListStore gui listStoreClear lst mapM_ (cardListAppend lst) (ssrKingdomCards sgr) labelSetText (colPlatLabel gui) (if ssrUsesColPlat sgr then "Yes" else "No") labelSetText (sheltersLabel gui) (if ssrUsesShelters sgr then "Yes" else "No") -- | Remove selected cards from a 'TreeView' to another 'ListStore' removeCards :: TreeViewClass self => self -> ListStore CardListRow -> IO () removeCards tv ls = do ts <- treeViewGetSelection tv selectionList <- treeSelectionGetSelectedRows ts let selectedRows = sort $ map head selectionList sequence_ $ map (listStoreRemove ls) $ reverse $ selectedRows treeSelectionUnselectAll ts -- | Displays text in a TextView. displayOutput :: TextView -> String -> IO () displayOutput tv s = do buf <- textViewGetBuffer tv textBufferSetText buf s {- | Displays an error messagebox and then immediately ends the program once the box has been dismissed -} startupErrorQuit :: String -> IO () startupErrorQuit s = do dialog <- messageDialogNew Nothing [] MessageError ButtonsOk s on dialog response (\rid -> liftIO mainQuit) widgetShowAll dialog mainGUI -- | Displays an error message in a modal messagebox, as a child to a window. displayError :: Window -> String -> IO () displayError w s = do dialog <- messageDialogNew (Just w) [DialogModal, DialogDestroyWithParent] MessageError ButtonsOk s dialogRun dialog widgetDestroy dialog return () {- | Returns a list of filepaths to all predefined card files. This is in the 'IO' monad since it uses cabal's "getDataFileName" function, which maps source paths to their corresponding packaged location. -} cardFileNames :: IO [String] cardFileNames = mapM getPath files where getPath s = getDataFileName $ "res/cards/" ++ s ++ ".txt" files = ["dominion", "intrigue", "seaside", "alchemy", "prosperity", "cornucopia", "hinterlands", "darkAges", "guilds", "promos", "custom"]
pshendry/dsgen
src/Dsgen/MainGUI.hs
gpl-3.0
5,902
0
17
1,661
1,459
696
763
116
4
{-# LANGUAGE OverloadedStrings #-} import System.FSNotify import System.Directory import Control.Applicative((<$>)) import Control.Exception(throw) import Control.Monad(when,forM_,forever) import System.FilePath ((</>)) import Development.Shake.FilePath (splitPath , splitDirectories , takeDirectory) import Control.Concurrent (threadDelay) import Data.String import Data.Time dropPreDir preDir file = let l = length(splitPath preDir) in foldr1 (</>) (drop l (splitDirectories file)) (<<>>) path source dest = dest </> dropPreDir source path copy :: FilePath -> FilePath -> FilePath -> IO() copy source dest path = do let targetFile = dest </> dropPreDir source path print $ "Copying from: " ++ show path ++ "to: " ++ show targetFile createDirectoryIfMissing True $ takeDirectory targetFile copyFile path targetFile remove :: FilePath -> FilePath -> FilePath -> IO() remove source dest path = do let d = (<<>>) path source dest print $ "Removing: " ++ show d removeFile d rm :: FilePath -> FilePath -> FilePath -> IO() rm source dest path = do let newFileName = (<<>>) path source dest print $ "RM: " ++ newFileName removePathForcibly newFileName cpL :: FilePath -> FilePath -> FilePath -> IO() cpL sourcedir destdir path = do print $ "CP: " ++ path isDirectory <- doesDirectoryExist path if isDirectory then do let newDirName = (<<>>) path sourcedir destdir print $ "Creating Directory: " ++ newDirName createDirectory newDirName else copy sourcedir destdir path copyDir :: FilePath -> FilePath -> IO () copyDir src dst = do whenM (not <$> doesDirectoryExist src) $ throw (userError "source does not exist") dstExists <- doesDirectoryExist dst if dstExists then do removePathForcibly dst createDirectory dst else createDirectory dst content <- getDirectoryContents src let xs = filter (`notElem` [".", ".."]) content forM_ xs $ \name -> do let srcPath = src </> name let destPath = dst </> name isDirectory <- doesDirectoryExist srcPath if isDirectory then do print $ "Copying dir from: " ++ srcPath ++ " to: " ++ destPath copyDir srcPath destPath else do print $ "Copying File from: " ++ srcPath ++ " to: " ++ destPath copyFile srcPath destPath where doesFileOrDirectoryExist x = orM [doesDirectoryExist x, doesFileExist x] orM xs = or <$> sequence xs whenM s r = s >>= flip when r copyModifyingDirs :: FilePath -> FilePath -> Event -> IO() copyModifyingDirs sourcedir destination ev = case ev of Added path _ _ -> cpL sourcedir destination path Modified path _ _ -> cpL sourcedir destination path Removed path _ _ -> rm sourcedir destination path Unknown {} -> error "Unknown Event !!" main :: IO() main = do let sourcedir = "/home/jakov/vmshare/XMC1100/Generated" :: String destdir = "/home/jakov/programming/Drone/hardware/XMC1100New/Generated" :: String -- copyDir sourcedir destdir -- withManager $ \mgr -> do -- -- start a watching job (in the background) -- watchTree -- mgr -- manager -- sourcedir -- directory to watch -- (const True) -- predicate -- (copyModifyingDirs sourcedir destdir) let wconf = WatchConfig { confDebounce = Debounce (realToFrac 4.0) , confPollInterval = 4000000 , confUsePolling = True} withManagerConf wconf $ \mgr -> do -- start a watching job (in the background) watchTree mgr -- manager sourcedir -- directory to watch (const True) -- predicate (copyModifyingDirs sourcedir destdir) -- sleep forever (until interrupted) forever $ threadDelay 1000000
JackTheEngineer/Drone
scripts/fileMirrorXMC1100.hs
gpl-3.0
3,818
0
17
947
1,072
531
541
88
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.LatencyTest.Types.Product -- 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) -- module Network.Google.LatencyTest.Types.Product where import Network.Google.LatencyTest.Types.Sum import Network.Google.Prelude -- -- /See:/ 'intValue' smart constructor. data IntValue = IntValue' { _ivValue :: !(Maybe (Textual Int64)) , _ivLabel :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'IntValue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ivValue' -- -- * 'ivLabel' intValue :: IntValue intValue = IntValue' { _ivValue = Nothing , _ivLabel = Nothing } ivValue :: Lens' IntValue (Maybe Int64) ivValue = lens _ivValue (\ s a -> s{_ivValue = a}) . mapping _Coerce ivLabel :: Lens' IntValue (Maybe Text) ivLabel = lens _ivLabel (\ s a -> s{_ivLabel = a}) instance FromJSON IntValue where parseJSON = withObject "IntValue" (\ o -> IntValue' <$> (o .:? "value") <*> (o .:? "label")) instance ToJSON IntValue where toJSON IntValue'{..} = object (catMaybes [("value" .=) <$> _ivValue, ("label" .=) <$> _ivLabel]) -- -- /See:/ 'doubleValue' smart constructor. data DoubleValue = DoubleValue' { _dvValue :: !(Maybe (Textual Double)) , _dvLabel :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DoubleValue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dvValue' -- -- * 'dvLabel' doubleValue :: DoubleValue doubleValue = DoubleValue' { _dvValue = Nothing , _dvLabel = Nothing } dvValue :: Lens' DoubleValue (Maybe Double) dvValue = lens _dvValue (\ s a -> s{_dvValue = a}) . mapping _Coerce dvLabel :: Lens' DoubleValue (Maybe Text) dvLabel = lens _dvLabel (\ s a -> s{_dvLabel = a}) instance FromJSON DoubleValue where parseJSON = withObject "DoubleValue" (\ o -> DoubleValue' <$> (o .:? "value") <*> (o .:? "label")) instance ToJSON DoubleValue where toJSON DoubleValue'{..} = object (catMaybes [("value" .=) <$> _dvValue, ("label" .=) <$> _dvLabel]) -- -- /See:/ 'stringValue' smart constructor. data StringValue = StringValue' { _svValue :: !(Maybe Text) , _svLabel :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'StringValue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'svValue' -- -- * 'svLabel' stringValue :: StringValue stringValue = StringValue' { _svValue = Nothing , _svLabel = Nothing } svValue :: Lens' StringValue (Maybe Text) svValue = lens _svValue (\ s a -> s{_svValue = a}) svLabel :: Lens' StringValue (Maybe Text) svLabel = lens _svLabel (\ s a -> s{_svLabel = a}) instance FromJSON StringValue where parseJSON = withObject "StringValue" (\ o -> StringValue' <$> (o .:? "value") <*> (o .:? "label")) instance ToJSON StringValue where toJSON StringValue'{..} = object (catMaybes [("value" .=) <$> _svValue, ("label" .=) <$> _svLabel]) -- -- /See:/ 'aggregatedStatsReply' smart constructor. newtype AggregatedStatsReply = AggregatedStatsReply' { _asrTestValue :: Maybe Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AggregatedStatsReply' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asrTestValue' aggregatedStatsReply :: AggregatedStatsReply aggregatedStatsReply = AggregatedStatsReply' { _asrTestValue = Nothing } asrTestValue :: Lens' AggregatedStatsReply (Maybe Text) asrTestValue = lens _asrTestValue (\ s a -> s{_asrTestValue = a}) instance FromJSON AggregatedStatsReply where parseJSON = withObject "AggregatedStatsReply" (\ o -> AggregatedStatsReply' <$> (o .:? "testValue")) instance ToJSON AggregatedStatsReply where toJSON AggregatedStatsReply'{..} = object (catMaybes [("testValue" .=) <$> _asrTestValue]) -- -- /See:/ 'stats' smart constructor. data Stats = Stats' { _sTime :: !(Maybe (Textual Double)) , _sDoubleValues :: !(Maybe [DoubleValue]) , _sStringValues :: !(Maybe [StringValue]) , _sIntValues :: !(Maybe [IntValue]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Stats' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sTime' -- -- * 'sDoubleValues' -- -- * 'sStringValues' -- -- * 'sIntValues' stats :: Stats stats = Stats' { _sTime = Nothing , _sDoubleValues = Nothing , _sStringValues = Nothing , _sIntValues = Nothing } sTime :: Lens' Stats (Maybe Double) sTime = lens _sTime (\ s a -> s{_sTime = a}) . mapping _Coerce sDoubleValues :: Lens' Stats [DoubleValue] sDoubleValues = lens _sDoubleValues (\ s a -> s{_sDoubleValues = a}) . _Default . _Coerce sStringValues :: Lens' Stats [StringValue] sStringValues = lens _sStringValues (\ s a -> s{_sStringValues = a}) . _Default . _Coerce sIntValues :: Lens' Stats [IntValue] sIntValues = lens _sIntValues (\ s a -> s{_sIntValues = a}) . _Default . _Coerce instance FromJSON Stats where parseJSON = withObject "Stats" (\ o -> Stats' <$> (o .:? "time") <*> (o .:? "doubleValues" .!= mempty) <*> (o .:? "stringValues" .!= mempty) <*> (o .:? "intValues" .!= mempty)) instance ToJSON Stats where toJSON Stats'{..} = object (catMaybes [("time" .=) <$> _sTime, ("doubleValues" .=) <$> _sDoubleValues, ("stringValues" .=) <$> _sStringValues, ("intValues" .=) <$> _sIntValues]) -- -- /See:/ 'aggregatedStats' smart constructor. newtype AggregatedStats = AggregatedStats' { _asStats :: Maybe [Stats] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AggregatedStats' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asStats' aggregatedStats :: AggregatedStats aggregatedStats = AggregatedStats' { _asStats = Nothing } asStats :: Lens' AggregatedStats [Stats] asStats = lens _asStats (\ s a -> s{_asStats = a}) . _Default . _Coerce instance FromJSON AggregatedStats where parseJSON = withObject "AggregatedStats" (\ o -> AggregatedStats' <$> (o .:? "stats" .!= mempty)) instance ToJSON AggregatedStats where toJSON AggregatedStats'{..} = object (catMaybes [("stats" .=) <$> _asStats]) -- -- /See:/ 'statsReply' smart constructor. newtype StatsReply = StatsReply' { _srTestValue :: Maybe Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'StatsReply' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'srTestValue' statsReply :: StatsReply statsReply = StatsReply' { _srTestValue = Nothing } srTestValue :: Lens' StatsReply (Maybe Text) srTestValue = lens _srTestValue (\ s a -> s{_srTestValue = a}) instance FromJSON StatsReply where parseJSON = withObject "StatsReply" (\ o -> StatsReply' <$> (o .:? "testValue")) instance ToJSON StatsReply where toJSON StatsReply'{..} = object (catMaybes [("testValue" .=) <$> _srTestValue])
rueshyna/gogol
gogol-latencytest/gen/Network/Google/LatencyTest/Types/Product.hs
mpl-2.0
8,631
0
14
2,276
1,980
1,128
852
219
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.AdExchangeSeller -- 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) -- -- Accesses the inventory of Ad Exchange seller users and generates -- reports. -- -- /See:/ <https://developers.google.com/ad-exchange/seller-rest/ Ad Exchange Seller API Reference> module Network.Google.AdExchangeSeller ( -- * Service Configuration adExchangeSellerService -- * OAuth Scopes , adExchangeSellerReadOnlyScope , adExchangeSellerScope -- * API Declaration , AdExchangeSellerAPI -- * Resources -- ** adexchangeseller.accounts.adclients.list , module Network.Google.Resource.AdExchangeSeller.Accounts.AdClients.List -- ** adexchangeseller.accounts.alerts.list , module Network.Google.Resource.AdExchangeSeller.Accounts.Alerts.List -- ** adexchangeseller.accounts.customchannels.get , module Network.Google.Resource.AdExchangeSeller.Accounts.CustomChannels.Get -- ** adexchangeseller.accounts.customchannels.list , module Network.Google.Resource.AdExchangeSeller.Accounts.CustomChannels.List -- ** adexchangeseller.accounts.get , module Network.Google.Resource.AdExchangeSeller.Accounts.Get -- ** adexchangeseller.accounts.list , module Network.Google.Resource.AdExchangeSeller.Accounts.List -- ** adexchangeseller.accounts.metadata.dimensions.list , module Network.Google.Resource.AdExchangeSeller.Accounts.Metadata.Dimensions.List -- ** adexchangeseller.accounts.metadata.metrics.list , module Network.Google.Resource.AdExchangeSeller.Accounts.Metadata.Metrics.List -- ** adexchangeseller.accounts.preferreddeals.get , module Network.Google.Resource.AdExchangeSeller.Accounts.PreferredDeals.Get -- ** adexchangeseller.accounts.preferreddeals.list , module Network.Google.Resource.AdExchangeSeller.Accounts.PreferredDeals.List -- ** adexchangeseller.accounts.reports.generate , module Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Generate -- ** adexchangeseller.accounts.reports.saved.generate , module Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Saved.Generate -- ** adexchangeseller.accounts.reports.saved.list , module Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Saved.List -- ** adexchangeseller.accounts.urlchannels.list , module Network.Google.Resource.AdExchangeSeller.Accounts.URLChannels.List -- * Types -- ** AdClients , AdClients , adClients , acEtag , acNextPageToken , acKind , acItems -- ** ReportingMetadataEntry , ReportingMetadataEntry , reportingMetadataEntry , rmeKind , rmeRequiredMetrics , rmeCompatibleMetrics , rmeRequiredDimensions , rmeId , rmeCompatibleDimensions , rmeSupportedProducts -- ** Accounts , Accounts , accounts , aEtag , aNextPageToken , aKind , aItems -- ** Alerts , Alerts , alerts , aleKind , aleItems -- ** SavedReports , SavedReports , savedReports , srEtag , srNextPageToken , srKind , srItems -- ** SavedReport , SavedReport , savedReport , sKind , sName , sId -- ** URLChannels , URLChannels , urlChannels , ucEtag , ucNextPageToken , ucKind , ucItems -- ** CustomChannels , CustomChannels , customChannels , ccEtag , ccNextPageToken , ccKind , ccItems -- ** Report , Report , report , rKind , rAverages , rWarnings , rRows , rTotals , rHeaders , rTotalMatchedRows -- ** Alert , Alert , alert , aaKind , aaSeverity , aaId , aaType , aaMessage -- ** Account , Account , account , accKind , accName , accId -- ** AdClient , AdClient , adClient , adKind , adArcOptIn , adSupportsReporting , adId , adProductCode -- ** ReportHeadersItem , ReportHeadersItem , reportHeadersItem , rhiName , rhiCurrency , rhiType -- ** CustomChannelTargetingInfo , CustomChannelTargetingInfo , customChannelTargetingInfo , cctiLocation , cctiSiteLanguage , cctiAdsAppearOn , cctiDescription -- ** PreferredDeals , PreferredDeals , preferredDeals , pdKind , pdItems -- ** Metadata , Metadata , metadata , mKind , mItems -- ** CustomChannel , CustomChannel , customChannel , cTargetingInfo , cKind , cName , cCode , cId -- ** URLChannel , URLChannel , urlChannel , urlcKind , urlcId , urlcURLPattern -- ** PreferredDeal , PreferredDeal , preferredDeal , pAdvertiserName , pCurrencyCode , pStartTime , pKind , pBuyerNetworkName , pEndTime , pId , pFixedCpm ) where import Network.Google.Prelude import Network.Google.AdExchangeSeller.Types import Network.Google.Resource.AdExchangeSeller.Accounts.AdClients.List import Network.Google.Resource.AdExchangeSeller.Accounts.Alerts.List import Network.Google.Resource.AdExchangeSeller.Accounts.CustomChannels.Get import Network.Google.Resource.AdExchangeSeller.Accounts.CustomChannels.List import Network.Google.Resource.AdExchangeSeller.Accounts.Get import Network.Google.Resource.AdExchangeSeller.Accounts.List import Network.Google.Resource.AdExchangeSeller.Accounts.Metadata.Dimensions.List import Network.Google.Resource.AdExchangeSeller.Accounts.Metadata.Metrics.List import Network.Google.Resource.AdExchangeSeller.Accounts.PreferredDeals.Get import Network.Google.Resource.AdExchangeSeller.Accounts.PreferredDeals.List import Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Generate import Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Saved.Generate import Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Saved.List import Network.Google.Resource.AdExchangeSeller.Accounts.URLChannels.List {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Ad Exchange Seller API service. type AdExchangeSellerAPI = AccountsAdClientsListResource :<|> AccountsReportsSavedListResource :<|> AccountsReportsSavedGenerateResource :<|> AccountsReportsGenerateResource :<|> AccountsAlertsListResource :<|> AccountsURLChannelsListResource :<|> AccountsCustomChannelsListResource :<|> AccountsCustomChannelsGetResource :<|> AccountsPreferredDealsListResource :<|> AccountsPreferredDealsGetResource :<|> AccountsMetadataMetricsListResource :<|> AccountsMetadataDimensionsListResource :<|> AccountsListResource :<|> AccountsGetResource
brendanhay/gogol
gogol-adexchange-seller/gen/Network/Google/AdExchangeSeller.hs
mpl-2.0
7,140
0
17
1,438
798
586
212
173
0
{- ORMOLU_DISABLE -} -- Implicit CAD. Copyright (C) 2011, Christopher Olah ([email protected]) -- Copyright (C) 2014 2015, Julia Longtin ([email protected]) -- Released under the GNU AGPLV3+, see LICENSE -- FIXME: required. why? {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} -- Allow us to use string literals for Text {-# LANGUAGE OverloadedStrings #-} module Graphics.Implicit.ExtOpenScad.Util.OVal(OTypeMirror, (<||>), fromOObj, toOObj, divideObjs, caseOType, oTypeStr, getErrors) where import Prelude(Maybe(Just, Nothing), Bool(True, False), Either(Left,Right), (==), fromInteger, floor, ($), (.), fmap, error, (<>), show, flip, filter, not, return) import Graphics.Implicit.Definitions(V2, ℝ, ℝ2, ℕ, SymbolicObj2, SymbolicObj3, ExtrudeMScale(C1, C2, Fn), fromℕtoℝ) import Graphics.Implicit.ExtOpenScad.Definitions (OVal(ONum, OBool, OString, OList, OFunc, OUndefined, OUModule, ONModule, OVargsModule, OError, OObj2, OObj3)) import Control.Monad (msum) import Data.Maybe (fromMaybe, maybe) import Data.Traversable (traverse) import Data.Text.Lazy (Text) -- for some minimal paralellism. import Control.Parallel.Strategies (runEval, rpar, rseq) -- To build vectors of ℝs. import Linear (V2(V2), V3(V3)) -- Convert OVals (and Lists of OVals) into a given Haskell type class OTypeMirror a where fromOObj :: OVal -> Maybe a fromOObjList :: OVal -> Maybe [a] fromOObjList (OList list) = traverse fromOObj list fromOObjList _ = Nothing {-# INLINABLE fromOObjList #-} toOObj :: a -> OVal instance OTypeMirror OVal where fromOObj = Just {-# INLINABLE fromOObj #-} toOObj a = a instance OTypeMirror ℝ where fromOObj (ONum n) = Just n fromOObj _ = Nothing {-# INLINABLE fromOObj #-} toOObj = ONum instance OTypeMirror ℕ where fromOObj (ONum n) = if n == fromInteger (floor n) then Just (floor n) else Nothing fromOObj _ = Nothing {-# INLINABLE fromOObj #-} toOObj = ONum . fromℕtoℝ instance OTypeMirror Bool where fromOObj (OBool b) = Just b fromOObj _ = Nothing {-# INLINABLE fromOObj #-} toOObj = OBool instance (OTypeMirror a) => OTypeMirror [a] where fromOObj = fromOObjList {-# INLINABLE fromOObj #-} toOObj list = OList $ fmap toOObj list instance OTypeMirror Text where fromOObj (OString str) = Just str fromOObj _ = Nothing toOObj a = OString a instance (OTypeMirror a) => OTypeMirror (Maybe a) where fromOObj a = Just $ fromOObj a {-# INLINABLE fromOObj #-} toOObj (Just a) = toOObj a toOObj Nothing = OUndefined instance (OTypeMirror a, OTypeMirror b) => OTypeMirror (a,b) where fromOObj (OList [fromOObj -> Just a,fromOObj -> Just b]) = Just (a,b) fromOObj _ = Nothing {-# INLINABLE fromOObj #-} toOObj (a,b) = OList [toOObj a, toOObj b] instance (OTypeMirror a) => OTypeMirror (V2 a) where fromOObj (OList [fromOObj -> Just a,fromOObj -> Just b]) = Just (V2 a b) fromOObj _ = Nothing {-# INLINABLE fromOObj #-} toOObj (V2 a b) = OList [toOObj a, toOObj b] instance (OTypeMirror a, OTypeMirror b, OTypeMirror c) => OTypeMirror (a,b,c) where fromOObj (OList [fromOObj -> Just a,fromOObj -> Just b,fromOObj -> Just c]) = Just (a,b,c) fromOObj _ = Nothing {-# INLINABLE fromOObj #-} toOObj (a,b,c) = OList [toOObj a, toOObj b, toOObj c] instance (OTypeMirror a) => OTypeMirror (V3 a) where fromOObj (OList [fromOObj -> Just a,fromOObj -> Just b,fromOObj -> Just c]) = Just (V3 a b c) fromOObj _ = Nothing {-# INLINABLE fromOObj #-} toOObj (V3 a b c) = OList [toOObj a, toOObj b, toOObj c] instance (OTypeMirror a, OTypeMirror b) => OTypeMirror (a -> b) where fromOObj (OFunc f) = Just $ \input -> let oInput = toOObj input oOutput = f oInput output :: Maybe b output = fromOObj oOutput in fromMaybe (error $ "coercing OVal to a -> b isn't always safe; use a -> Maybe b" <> " (trace: " <> show oInput <> " -> " <> show oOutput <> " )") output fromOObj _ = Nothing {-# INLINABLE fromOObj #-} toOObj f = OFunc $ \oObj -> case fromOObj oObj :: Maybe a of Nothing -> OError "bad input type" Just obj -> toOObj $ f obj instance (OTypeMirror a, OTypeMirror b) => OTypeMirror (Either a b) where fromOObj (fromOObj -> Just (x :: a)) = Just $ Left x fromOObj (fromOObj -> Just (x :: b)) = Just $ Right x fromOObj _ = Nothing {-# INLINABLE fromOObj #-} toOObj (Right x) = toOObj x toOObj (Left x) = toOObj x instance OTypeMirror ExtrudeMScale where fromOObj (fromOObj -> Just (x :: ℝ)) = Just $ C1 x fromOObj (fromOObj -> Just (x :: ℝ2)) = Just $ C2 x fromOObj (fromOObj -> Just (x :: (ℝ -> Either ℝ ℝ2))) = Just $ Fn x fromOObj _ = Nothing toOObj (C1 x) = toOObj x toOObj (C2 x) = toOObj x toOObj (Fn x) = toOObj x -- A string representing each type. oTypeStr :: OVal -> Text oTypeStr OUndefined = "Undefined" oTypeStr (OBool _ ) = "Bool" oTypeStr (ONum _ ) = "Number" oTypeStr (OList _ ) = "List" oTypeStr (OString _ ) = "String" oTypeStr (OFunc _ ) = "Function" oTypeStr (OUModule _ _ _ ) = "User Defined Module" oTypeStr (ONModule _ _ _ ) = "Built-in Module" oTypeStr (OVargsModule _ _ ) = "VargsModule" oTypeStr (OError _ ) = "Error" oTypeStr (OObj2 _ ) = "2D Object" oTypeStr (OObj3 _ ) = "3D Object" getErrors :: OVal -> Maybe Text getErrors (OError er) = Just er getErrors (OList l) = msum $ fmap getErrors l getErrors _ = Nothing caseOType :: a -> (a -> c) -> c caseOType = flip ($) infixr 2 <||> (<||>) :: OTypeMirror desiredType => (desiredType -> out) -> (OVal -> out) -> (OVal -> out) (<||>) f g input = let coerceAttempt :: OTypeMirror desiredType => Maybe desiredType coerceAttempt = fromOObj input in maybe (g input) f coerceAttempt -- separate 2d and 3d objects from a set of OVals. divideObjs :: [OVal] -> ([SymbolicObj2], [SymbolicObj3], [OVal]) divideObjs children = runEval $ do obj2s <- rseq [ x | OObj2 x <- children ] obj3s <- rseq [ x | OObj3 x <- children ] objs <- rpar (filter (not . isOObj) children) return (obj2s, obj3s, objs) where isOObj (OObj2 _) = True isOObj (OObj3 _) = True isOObj _ = False
colah/ImplicitCAD
Graphics/Implicit/ExtOpenScad/Util/OVal.hs
agpl-3.0
6,560
1
17
1,641
2,225
1,193
1,032
131
3
{-# OPTIONS_GHC -XFlexibleInstances -XTypeSynonymInstances -XStandaloneDeriving #-} {- Commands for HSH Copyright (C) 2004-2008 John Goerzen <[email protected]> Please see the COPYRIGHT file -} {- | Module : HSH.Command Copyright : Copyright (C) 2006-2009 John Goerzen License : GNU LGPL, version 2.1 or above Maintainer : John Goerzen <[email protected]> Stability : provisional Portability: portable Copyright (c) 2006-2009 John Goerzen, jgoerzen\@complete.org -} module HSH.Command (Environment, ShellCommand(..), PipeCommand(..), (-|-), RunResult, run, runIO, runSL, InvokeResult, checkResults, tryEC, catchEC, setenv, unsetenv ) where -- import System.IO.HVIO -- import System.IO.Utils import Prelude hiding (catch) import System.IO import System.Exit import System.Log.Logger import System.IO.Error (isUserError, ioeGetErrorString) import Data.Maybe.Utils import Data.Maybe import Data.List.Utils(uniq) import Control.Exception(try, evaluate, SomeException, catch) import Text.Regex.Posix import Control.Monad(when) import Data.String.Utils(rstrip) import Control.Concurrent import System.Process import System.Environment(getEnvironment) import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString as BS import HSH.Channel d, dr :: String -> IO () d = debugM "HSH.Command" dr = debugM "HSH.Command.Run" em = errorM "HSH.Command" {- | Result type for shell commands. The String is the text description of the command, not its output. -} type InvokeResult = (String, IO ExitCode) {- | Type for the environment. -} type Environment = Maybe [(String, String)] {- | A shell command is something we can invoke, pipe to, pipe from, or pipe in both directions. All commands that can be run as shell commands must define these methods. Minimum implementation is 'fdInvoke'. Some pre-defined instances include: * A simple bare string, which is passed to the shell for execution. The shell will then typically expand wildcards, parse parameters, etc. * A @(String, [String])@ tuple. The first item in the tuple gives the name of a program to run, and the second gives its arguments. The shell is never involved. This is ideal for passing filenames, since there is no security risk involving special shell characters. * A @Handle -> Handle -> IO ()@ function, which reads from the first handle and write to the second. * Various functions. These functions will accept input representing its standard input and output will go to standard output. Some pre-defined instance functions include: * @(String -> String)@, @(String -> IO String)@, plus the same definitions for ByteStrings. * @([String] -> [String])@, @([String] -> IO [String])@, where each @String@ in the list represents a single line * @(() -> String)@, @(() -> IO String)@, for commands that explicitly read no input. Useful with closures. Useful when you want to avoid reading stdin because something else already is. These have the unit as part of the function because otherwise we would have conflicts with things such as bare Strings, which represent a command name. -} class (Show a) => ShellCommand a where {- | Invoke a command. -} fdInvoke :: a -- ^ The command -> Environment -- ^ The environment -> Channel -- ^ Where to read input from -> IO (Channel, [InvokeResult]) -- ^ Returns an action that, when evaluated, waits for the process to finish and returns an exit code. instance Show (Handle -> Handle -> IO ()) where show _ = "(Handle -> Handle -> IO ())" instance Show (Channel -> IO Channel) where show _ = "(Channel -> IO Channel)" instance Show (String -> String) where show _ = "(String -> String)" instance Show (() -> String) where show _ = "(() -> String)" instance Show (String -> IO String) where show _ = "(String -> IO String)" instance Show (() -> IO String) where show _ = "(() -> IO String)" instance Show (BSL.ByteString -> BSL.ByteString) where show _ = "(Data.ByteString.Lazy.ByteString -> Data.ByteString.Lazy.ByteString)" instance Show (() -> BSL.ByteString) where show _ = "(() -> Data.ByteString.Lazy.ByteString)" instance Show (BSL.ByteString -> IO BSL.ByteString) where show _ = "(Data.ByteString.Lazy.ByteString -> IO Data.ByteString.Lazy.ByteString)" instance Show (() -> IO BSL.ByteString) where show _ = "(() -> IO BSL.ByteString)" instance Show (BS.ByteString -> BS.ByteString) where show _ = "(Data.ByteString.ByteString -> Data.ByteString.ByteString)" instance Show (() -> BS.ByteString) where show _ = "(() -> Data.ByteString.ByteString)" instance Show (BS.ByteString -> IO BS.ByteString) where show _ = "(Data.ByteString.ByteString -> IO Data.ByteString.ByteString)" instance Show (() -> IO BS.ByteString) where show _ = "(() -> IO Data.ByteString.ByteString)" instance ShellCommand (String -> IO String) where fdInvoke = genericStringlikeIO chanAsString {- | A user function that takes no input, and generates output. We will deal with it using hPutStr to send the output on. -} instance ShellCommand (() -> IO String) where fdInvoke = genericStringlikeO instance ShellCommand (BSL.ByteString -> IO BSL.ByteString) where fdInvoke = genericStringlikeIO chanAsBSL instance ShellCommand (() -> IO BSL.ByteString) where fdInvoke = genericStringlikeO instance ShellCommand (BS.ByteString -> IO BS.ByteString) where fdInvoke = genericStringlikeIO chanAsBS instance ShellCommand (() -> IO BS.ByteString) where fdInvoke = genericStringlikeO {- | An instance of 'ShellCommand' for a pure Haskell function mapping String to String. Implement in terms of (String -> IO String) for simplicity. -} instance ShellCommand (String -> String) where fdInvoke func = fdInvoke iofunc where iofunc :: String -> IO String iofunc = return . func instance ShellCommand (() -> String) where fdInvoke func = fdInvoke iofunc where iofunc :: () -> IO String iofunc = return . func instance ShellCommand (BSL.ByteString -> BSL.ByteString) where fdInvoke func = fdInvoke iofunc where iofunc :: BSL.ByteString -> IO BSL.ByteString iofunc = return . func instance ShellCommand (() -> BSL.ByteString) where fdInvoke func = fdInvoke iofunc where iofunc :: () -> IO BSL.ByteString iofunc = return . func instance ShellCommand (BS.ByteString -> BS.ByteString) where fdInvoke func = fdInvoke iofunc where iofunc :: BS.ByteString -> IO BS.ByteString iofunc = return . func instance ShellCommand (() -> BS.ByteString) where fdInvoke func = fdInvoke iofunc where iofunc :: () -> IO BS.ByteString iofunc = return . func instance ShellCommand (Channel -> IO Channel) where fdInvoke func _ cstdin = runInHandler (show func) (func cstdin) {- instance ShellCommand (Handle -> Handle -> IO ()) where fdInvoke func cstdin cstdout = runInHandler (show func) (func hstdin hstdout) -} genericStringlikeIO :: (Show (a -> IO a), Channelizable a) => (Channel -> IO a) -> (a -> IO a) -> Environment -> Channel -> IO (Channel, [InvokeResult]) genericStringlikeIO dechanfunc userfunc _ cstdin = do contents <- dechanfunc cstdin runInHandler (show userfunc) (realfunc contents) where realfunc contents = do r <- userfunc contents return (toChannel r) genericStringlikeO :: (Show (() -> IO a), Channelizable a) => (() -> IO a) -> Environment -> Channel -> IO (Channel, [InvokeResult]) genericStringlikeO userfunc _ _ = runInHandler (show userfunc) realfunc where realfunc :: IO Channel realfunc = do r <- userfunc () return (toChannel r) instance Show ([String] -> [String]) where show _ = "([String] -> [String])" instance Show (() -> [String]) where show _ = "(() -> [String])" instance Show ([String] -> IO [String]) where show _ = "([String] -> IO [String])" instance Show (() -> IO [String]) where show _ = "(() -> IO [String])" {- | An instance of 'ShellCommand' for a pure Haskell function mapping [String] to [String]. A [String] is generated from a Handle via the 'lines' function, and the reverse occurs via 'unlines'. So, this function is intended to operate upon lines of input and produce lines of output. -} instance ShellCommand ([String] -> [String]) where fdInvoke func = fdInvoke (unlines . func . lines) instance ShellCommand (() -> [String]) where fdInvoke func = fdInvoke (unlines . func) {- | The same for an IO function -} instance ShellCommand ([String] -> IO [String]) where fdInvoke func = fdInvoke iofunc where iofunc input = do r <- func (lines input) return (unlines r) instance ShellCommand (() -> IO [String]) where fdInvoke func = fdInvoke iofunc where iofunc :: (() -> IO String) iofunc () = do r <- func () return (unlines r) {- | An instance of 'ShellCommand' for an external command. The first String is the command to run, and the list of Strings represents the arguments to the program, if any. -} instance ShellCommand (String, [String]) where fdInvoke (fp, args) = genericCommand (RawCommand fp args) {- | An instance of 'ShellCommand' for an external command. The String is split using words to the command to run, and the arguments, if any. -} instance ShellCommand String where fdInvoke cmd = genericCommand (ShellCommand cmd) {- | How to we handle and external command. -} genericCommand :: CmdSpec -> Environment -> Channel -> IO (Channel, [InvokeResult]) -- Handling external command when stdin channel is a Handle genericCommand c environ (ChanHandle ih) = let cp = CreateProcess {cmdspec = c, cwd = Nothing, env = environ, std_in = UseHandle ih, std_out = CreatePipe, std_err = Inherit, close_fds = True #if MIN_VERSION_process(1,1,0) -- Or use GHC version as a proxy: __GLASGOW_HASKELL__ >= 720 -- Added field in process 1.1.0.0: , create_group = False #endif #if MIN_VERSION_process(1,2,0) , delegate_ctlc = False #endif #if MIN_VERSION_process(1,3,0) , detach_console = False , create_new_console = False , new_session = False #endif #if MIN_VERSION_process(1,4,0) , child_group = Nothing , child_user = Nothing #endif #if MIN_VERSION_process(1,5,0) , use_process_jobs = False #endif } in do (_, oh', _, ph) <- createProcess cp let oh = fromJust oh' return (ChanHandle oh, [(printCmdSpec c, waitForProcess ph)]) genericCommand cspec environ ichan = let cp = CreateProcess {cmdspec = cspec, cwd = Nothing, env = environ, std_in = CreatePipe, std_out = CreatePipe, std_err = Inherit, close_fds = True #if MIN_VERSION_process(1,1,0) -- Added field in process 1.1.0.0: , create_group = False #endif #if MIN_VERSION_process(1,2,0) , delegate_ctlc = False #endif #if MIN_VERSION_process(1,3,0) , detach_console = False , create_new_console = False , new_session = False #endif #if MIN_VERSION_process(1,4,0) , child_group = Nothing , child_user = Nothing #endif #if MIN_VERSION_process(1,5,0) , use_process_jobs = False #endif } in do (ih', oh', _, ph) <- createProcess cp let ih = fromJust ih' let oh = fromJust oh' chanToHandle True ichan ih return (ChanHandle oh, [(printCmdSpec cspec, waitForProcess ph)]) printCmdSpec :: CmdSpec -> String printCmdSpec (ShellCommand s) = s printCmdSpec (RawCommand fp args) = show (fp, args) ------------------------------------------------------------ -- Pipes ------------------------------------------------------------ data PipeCommand a b = (ShellCommand a, ShellCommand b) => PipeCommand a b deriving instance Show (PipeCommand a b) {- | An instance of 'ShellCommand' represeting a pipeline. -} instance (ShellCommand a, ShellCommand b) => ShellCommand (PipeCommand a b) where fdInvoke (PipeCommand cmd1 cmd2) env ichan = do (chan1, res1) <- fdInvoke cmd1 env ichan (chan2, res2) <- fdInvoke cmd2 env chan1 return (chan2, res1 ++ res2) {- | Pipe the output of the first command into the input of the second. -} (-|-) :: (ShellCommand a, ShellCommand b) => a -> b -> PipeCommand a b (-|-) = PipeCommand {- | Different ways to get data from 'run'. * IO () runs, throws an exception on error, and sends stdout to stdout * IO String runs, throws an exception on error, reads stdout into a buffer, and returns it as a string. Note: This output is not lazy. * IO [String] is same as IO String, but returns the results as lines. Note: this output is not lazy. * IO ExitCode runs and returns an ExitCode with the exit information. stdout is sent to stdout. Exceptions are not thrown. * IO (String, ExitCode) is like IO ExitCode, but also includes a description of the last command in the pipe to have an error (or the last command, if there was no error). * IO ByteString and are similar to their String counterparts. * IO (String, IO (String, ExitCode)) returns a String read lazily and an IO action that, when evaluated, finishes up the process and results in its exit status. This command returns immediately. * IO (IO (String, ExitCode)) sends stdout to stdout but returns immediately. It forks off the child but does not wait for it to finish. You can use 'checkResults' to wait for the finish. * IO Int returns the exit code from a program directly. If a signal caused the command to be reaped, returns 128 + SIGNUM. * IO Bool returns True if the program exited normally (exit code 0, not stopped by a signal) and False otherwise. To address insufficient laziness, you can process anything that needs to be processed lazily within the pipeline itself. -} class RunResult a where {- | Runs a command (or pipe of commands), with results presented in any number of different ways. -} run :: (ShellCommand b) => b -> a instance RunResult (IO ()) where run cmd = run cmd >>= checkResults instance RunResult (IO (String, ExitCode)) where run cmd = do (ochan, r) <- fdInvoke cmd Nothing (ChanHandle stdin) chanToHandle False ochan stdout processResults r instance RunResult (IO ExitCode) where run cmd = ((run cmd)::IO (String, ExitCode)) >>= return . snd instance RunResult (IO Int) where run cmd = do rc <- run cmd case rc of ExitSuccess -> return 0 ExitFailure x -> return x instance RunResult (IO Bool) where run cmd = do rc <- run cmd return ((rc::Int) == 0) instance RunResult (IO [String]) where run cmd = do r <- run cmd return (lines r) instance RunResult (IO String) where run cmd = genericStringlikeResult chanAsString (\c -> evaluate (length c)) cmd instance RunResult (IO BSL.ByteString) where run cmd = genericStringlikeResult chanAsBSL (\c -> evaluate (BSL.length c)) cmd instance RunResult (IO BS.ByteString) where run cmd = genericStringlikeResult chanAsBS (\c -> evaluate (BS.length c)) cmd instance RunResult (IO (String, IO (String, ExitCode))) where run cmd = intermediateStringlikeResult chanAsString cmd instance RunResult (IO (BSL.ByteString, IO (String, ExitCode))) where run cmd = intermediateStringlikeResult chanAsBSL cmd instance RunResult (IO (BS.ByteString, IO (String, ExitCode))) where run cmd = intermediateStringlikeResult chanAsBS cmd instance RunResult (IO (IO (String, ExitCode))) where run cmd = do (ochan, r) <- fdInvoke cmd Nothing (ChanHandle stdin) chanToHandle False ochan stdout return (processResults r) intermediateStringlikeResult :: ShellCommand b => (Channel -> IO a) -> b -> IO (a, IO (String, ExitCode)) intermediateStringlikeResult chanfunc cmd = do (ochan, r) <- fdInvoke cmd Nothing (ChanHandle stdin) c <- chanfunc ochan return (c, processResults r) genericStringlikeResult :: ShellCommand b => (Channel -> IO a) -> (a -> IO c) -> b -> IO a genericStringlikeResult chanfunc evalfunc cmd = do (c, r) <- intermediateStringlikeResult chanfunc cmd evalfunc c --evaluate (length c) -- d "runS 6" -- d "runS 7" r >>= checkResults -- d "runS 8" return c {- | Evaluates the result codes and returns an overall status -} processResults :: [InvokeResult] -> IO (String, ExitCode) processResults r = do rc <- mapM procresult r case catMaybes rc of [] -> return (fst (last r), ExitSuccess) x -> return (last x) where procresult :: InvokeResult -> IO (Maybe (String, ExitCode)) procresult (cmd, action) = do rc <- action return $ case rc of ExitSuccess -> Nothing x -> Just (cmd, x) {- | Evaluates result codes and raises an error for any bad ones it finds. -} checkResults :: (String, ExitCode) -> IO () checkResults (cmd, ps) = case ps of ExitSuccess -> return () ExitFailure x -> fail $ cmd ++ ": exited with code " ++ show x {- FIXME: generate these again Terminated sig -> fail $ cmd ++ ": terminated by signal " ++ show sig Stopped sig -> fail $ cmd ++ ": stopped by signal " ++ show sig -} {- | Handle an exception derived from a program exiting abnormally -} tryEC :: IO a -> IO (Either ExitCode a) tryEC action = do r <- Control.Exception.try action case r of Left ioe -> if isUserError ioe then case (ioeGetErrorString ioe =~~ pat) of Nothing -> ioError ioe -- not ours; re-raise it Just e -> return . Left . procit $ e else ioError ioe -- not ours; re-raise it Right result -> return (Right result) where pat = ": exited with code [0-9]+$|: terminated by signal ([0-9]+)$|: stopped by signal [0-9]+" procit :: String -> ExitCode procit e | e =~ "^: exited" = ExitFailure (str2ec e) -- | e =~ "^: terminated by signal" = Terminated (str2ec e) -- | e =~ "^: stopped by signal" = Stopped (str2ec e) | otherwise = error "Internal error in tryEC" str2ec e = read (e =~ "[0-9]+$") {- | Catch an exception derived from a program exiting abnormally -} catchEC :: IO a -> (ExitCode -> IO a) -> IO a catchEC action handler = do r <- tryEC action case r of Left ec -> handler ec Right result -> return result {- | A convenience function. Refers only to the version of 'run' that returns @IO ()@. This prevents you from having to cast to it all the time when you do not care about the result of 'run'. The implementation is simply: >runIO :: (ShellCommand a) => a -> IO () >runIO = run -} runIO :: (ShellCommand a) => a -> IO () runIO = run {- | Another convenience function. This returns the first line of the output, with any trailing newlines or whitespace stripped off. No leading whitespace is stripped. This function will raise an exception if there is not at least one line of output. Mnemonic: runSL means \"run single line\". This command exists separately from 'run' because there is already a 'run' instance that returns a String, though that instance returns the entirety of the output in that String. -} runSL :: (ShellCommand a) => a -> IO String runSL cmd = do r <- run cmd when (r == []) $ fail $ "runSL: no output received from " ++ show cmd return (rstrip . head $ r) {- | Convenience function to wrap a child thread. Kicks off the thread, handles running the code, traps execptions, the works. Note that if func is lazy, such as a getContents sort of thing, the exception may go uncaught here. NOTE: expects func to be lazy! -} runInHandler :: String -- ^ Description of this function -> (IO Channel) -- ^ The action to run in the thread -> IO (Channel, [InvokeResult]) runInHandler descrip func = catch (realfunc) (exchandler) where realfunc = do r <- func return (r, [(descrip, return ExitSuccess)]) exchandler :: SomeException -> IO (Channel, [InvokeResult]) exchandler e = do em $ "runInHandler/" ++ descrip ++ ": " ++ show e return (ChanString "", [(descrip, return (ExitFailure 1))]) ------------------------------------------------------------ -- Environment ------------------------------------------------------------ {- | An environment variable filter function. This is a low-level interface; see 'setenv' and 'unsetenv' for more convenient interfaces. -} type EnvironFilter = [(String, String)] -> [(String, String)] instance Show EnvironFilter where show _ = "EnvironFilter" {- | A command that carries environment variable information with it. This is a low-level interface; see 'setenv' and 'unsetenv' for more convenient interfaces. -} data EnvironCommand a = (ShellCommand a) => EnvironCommand EnvironFilter a deriving instance Show (EnvironCommand a) instance (ShellCommand a) => ShellCommand (EnvironCommand a) where fdInvoke (EnvironCommand efilter cmd) Nothing ichan = do -- No incoming environment; initialize from system default. e <- getEnvironment fdInvoke cmd (Just (efilter e)) ichan fdInvoke (EnvironCommand efilter cmd) (Just ienv) ichan = fdInvoke cmd (Just (efilter ienv)) ichan {- | Sets an environment variable, replacing an existing one if it exists. Here's a sample ghci session to illustrate. First, let's see the defaults for some variables: > Prelude HSH> runIO $ "echo $TERM, $LANG" > xterm, en_US.UTF-8 Now, let's set one: > Prelude HSH> runIO $ setenv [("TERM", "foo")] $ "echo $TERM, $LANG" > foo, en_US.UTF-8 Or two: > Prelude HSH> runIO $ setenv [("TERM", "foo")] $ setenv [("LANG", "de_DE.UTF-8")] $ "echo $TERM, $LANG" > foo, de_DE.UTF-8 We could also do it easier, like this: > Prelude HSH> runIO $ setenv [("TERM", "foo"), ("LANG", "de_DE.UTF-8")] $ "echo $TERM, $LANG" > foo, de_DE.UTF-8 It can be combined with unsetenv: > Prelude HSH> runIO $ setenv [("TERM", "foo")] $ unsetenv ["LANG"] $ "echo $TERM, $LANG" > foo, And used with pipes: > Prelude HSH> runIO $ setenv [("TERM", "foo")] $ "echo $TERM, $LANG" -|- "tr a-z A-Z" > FOO, EN_US.UTF-8 See also 'unsetenv'. -} setenv :: (ShellCommand cmd) => [(String, String)] -> cmd -> EnvironCommand cmd setenv items cmd = EnvironCommand efilter cmd where efilter ienv = foldr efilter' ienv items efilter' (key, val) ienv = (key, val) : (filter (\(k, _) -> k /= key) ienv) {- | Removes an environment variable if it exists; does nothing otherwise. See also 'setenv', which has a more extensive example. -} unsetenv :: (ShellCommand cmd) => [String] -> cmd -> EnvironCommand cmd unsetenv keys cmd = EnvironCommand efilter cmd where efilter ienv = foldr efilter' ienv keys efilter' key = filter (\(k, _) -> k /= key)
jgoerzen/hsh
HSH/Command.hs
lgpl-2.1
24,639
4
16
6,698
4,836
2,539
2,297
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeApplications #-} module TestDay01 where import Control.Lens import Control.Lens.Action (act, (^!)) import qualified Prelude import Protolude hiding (to) import Test.HUnit ((@?=)) import Test.Tasty hiding (Timeout) import Test.Tasty.HUnit (testCase) -- https://chrispenner.ca/posts/advent-of-optics-01 -- https://adventofcode.com/2019/day/1 ------------------------------------------------------------------------------ -- Part 1 -- series of input numbers (mass of ship modules) -- pass through pipeline of mathematic operations (fuel calculations) -- summed together to get solution (total fuel required) -- (note: could solve without lens via foldMap) -- ^.. : infix and flipped toListOf test_worded :: TestTree test_worded = testCase "test_day01_worded" $ do input <- Prelude.readFile "test/01.txt" take 4 (input^..worded) @?= ["50572","126330","143503","136703"] -- parse strings into a numeric via '_Show" -- uses Read instances to parse strings -- skips elements which fail to parse -- _Show :: (Read a, Show a) => Prism' String a test_Show :: TestTree test_Show = testCase "test_day01_Show" $ do input <- Prelude.readFile "test/01.txt" take 4 (input ^.. worded . _Show @ Double) @?= [50572.0,126330.0,143503.0,136703.0] -- steps: -- Divide by 3 -- Round down -- Subtract 2 test_steps :: TestTree test_steps = testCase "test_day01_steps" $ do input <- Prelude.readFile "test/01.txt" take 4 (input ^.. worded . _Show . to (/ 3) . to (floor @Double @Int) . to (subtract 2)) @?= [16855,42108,47832,45565] -- refactor calculateRequiredFuel :: Double -> Double calculateRequiredFuel = fromIntegral . subtract 2 . floor @Double @Int . (/ 3) test_CalculateRequiredFuel :: TestTree test_CalculateRequiredFuel = testGroup "test_day01_CalculateRequiredFuel" [ testCase " 12" $ calculateRequiredFuel 12.0 @?= 2.0 , testCase " 14" $ calculateRequiredFuel 14.0 @?= 2.0 , testCase " 1969" $ calculateRequiredFuel 1969.0 @?= 654.0 , testCase "100756" $ calculateRequiredFuel 100756.0 @?= 33583.0 ] -- sum the stream -- change aggregation from ^.. (a.k.a. toListOf) into sumOf test_sumOf :: TestTree test_sumOf = testCase "test_day01_sumOf" $ do input <- Prelude.readFile "test/01.txt" (input & sumOf (worded . _Show . to calculateRequiredFuel )) @?= 3412531 -- alternative -- computed entire thing in a fold by using lens-action to thread the readFile into IO -- ^! : 'view' a result from a Fold which requires IO -- act : lift a monadic action into a fold -- viewing implicitly folds the output using it's Monoid (e.g., Sum) solve' :: IO (Sum Double) solve' = "test/01.txt" ^! act Prelude.readFile . worded . _Show . to calculateRequiredFuel . to Sum test_lens_action :: TestTree test_lens_action = testCase "test_day01_lens_action" $ do r <- solve' r @?= Sum {getSum = 3412531} {- ------------------------------------------------------------------------------ Part 2 need to account for fuel required to transport all the fuel added (i.e., fuel itself requires fuel) that fuel also requires fuel, and that fuel requires fuel, ... Any mass that would require negative fuel should instead be treated as if it requires zero fuel for each module mass - calculate its fuel and add it to the total - Then, treat the fuel just calculated as the input mass and repeat the process - continuing until a fuel requirement is zero or negative. For example: mass 14 requires 2 fuel - 2 fuel requires no further fuel because - 2 divided by 3 and rounded down is 0, so the total fuel required is still just 2 mass 1969 requires 654 fuel - 654 fuel requires 216 more fuel (654 / 3 - 2) - 216 fuel requires 70 more fuel, ... - total fuel required for module is 654 + 216 + 70 + 21 + 5 = 966 mass 100756 requires - 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346 What is sum of fuel requirements for all modules, taking into account mass of added fuel? the iteration needed is an unfold lens : unfolds can be represented as a Fold that adds more elements when it runs Lensy folds can focus an arbitrary number of focuses a fold in lens that can be used: iterated :: (a -> a) -> Fold a a -} test_iterated :: TestTree test_iterated = testGroup "test_day01_iterated" [ -- Note: iterated emits first input without any iteration testCase "chris" $ 1 ^.. taking 10 (iterated (+1)) @?= [1,2,3,4,5,6,7,8,9,10::Int] , testCase " 1969 listOf" $ 1969 ^.. taking 7 (iterated calculateRequiredFuel) @?= [1969,654,216,70,21,5,-1] , testCase " 1969 sumOf" $ (1969 & sumOf (takingWhile (>0) (dropping 1 (iterated calculateRequiredFuel)))) @?= 966.0 , testCase "100756 listOf" $ 100756 ^.. taking 12 (iterated calculateRequiredFuel) @?= [100756.0,33583.0,11192.0,3728.0,1240.0,411.0,135.0,43.0,12.0,2.0,-2.0,-3.0] , testCase "100756 sumOf" $ (100756 & sumOf (takingWhile (>0) (dropping 1 (iterated calculateRequiredFuel)))) @?= 50346.0 ] -- next -- limit iteration while developing -- switch back to toListOf so can observe what is happening -- output shows fuel numbers getting smaller on each iteration, until they go negative -- after 30 iterations fold moves onto the next input -- so the numbers jump back up again as a new iteration starts solve2 :: IO [Double] solve2 = do input <- Prelude.readFile "test/01.txt" pure $ input & toListOf (worded . _Show . taking 30 (iterated calculateRequiredFuel) ) test_solve2 :: TestTree test_solve2 = testCase "test_day01_solve2" $ solve2 >>= \r -> take (length e) r @?= e where e = [50572.0,16855.0,5616.0,1870.0,621.0,205.0,66.0,20.0,4.0,-1.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,126330.0,42108.0,14034.0,4676.0,1556.0,516.0,170.0,54.0,16.0,3.0,-1.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,-3.0,143503.0,47832.0] -- puzzle says to ignore everything past the point where numbers go negative -- so stop iterating at that point via takingWhile -- note: 0 is filtered, but since 0 has no effect on a sum it is OK solve2' :: IO [Double] solve2' = do input <- Prelude.readFile "test/01.txt" pure $ input & toListOf (worded . _Show . takingWhile (>0) (iterated calculateRequiredFuel) ) test_solve2' :: TestTree test_solve2' = testCase "test_day01_solve2'" $ solve2' >>= \r -> take (length e) r @?= e -- 'e' is different since there is no longer a "20 limiter", instead stops at 0 or below where e = [50572.0,16855.0,5616.0,1870.0,621.0,205.0,66.0,20.0,4.0,126330.0,42108.0,14034.0] -- recall : iterated passes through the original value, which is NOT wanted in this case. -- remove it via 'dropping' solve2'' :: IO Double solve2'' = do input <- Prelude.readFile "test/01.txt" pure $ input & sumOf (worded . _Show . takingWhile (>0) (dropping 1 (iterated calculateRequiredFuel)) ) test_solve2'' :: TestTree test_solve2'' = testCase "test_day01_solve2''" $ solve2'' >>= \r -> r @?= 5115927.0 -- alternative : fewer brackets solve2FB :: IO Double solve2FB = do input <- Prelude.readFile "test/01.txt" pure $ input & sumOf (worded . _Show . (takingWhile (> 0) . dropping 1 . iterated) calculateRequiredFuel) test_solve2FB :: TestTree test_solve2FB = testCase "test_day01_solve2FB" $ solve2FB >>= \r -> r @?= 5115927.0
haroldcarr/learn-haskell-coq-ml-etc
haskell/topic/lens/2019-12-chris-penner-advent-of-optics/test/TestDay01.hs
unlicense
7,584
0
17
1,421
1,666
922
744
-1
-1
import Data.List import Data.Array -- The arctic slide game logic is based on the Macintosh Polar -- shareware game by Go Endo. The game is a simple 4x24 grid -- where a penguin can walk and push objects around. The goal -- is to place all the hearts on the board into houses. Objects -- slide frictionlessly until stopped. Bombs can be used to -- blow up mountains. Ice blocks can be slid around or crushed. data Tile = Empty | Tree | Mountain | House | Ice_Block | Bomb | Heart deriving (Show, Eq) -- In an object-oriented implementation, Walkable, Blocking, -- Movable, and Fixed are subclasses. For the Haskell version -- we just make them predicates and do dispatch that way. -- Different types of tiles have different behaviors depending -- on what they interact with -- for example, the penguin can -- taverse trees but trees will block any sliding objects. walkable :: Tile -> Bool walkable t = ( t == Empty ) || ( t == Tree ) blocking :: Tile -> Bool blocking t = ( t /= Empty ) movable :: Tile -> Bool movable t = ( t == Bomb ) || ( t == Heart ) || ( t == Ice_Block ) fixed :: Tile -> Bool fixed t = ( t == House ) || ( t == Mountain ) -- Tile interactions: create a new list from the old list -- representing the pushed object and tiles ahead of it slide :: [ Tile ] -> [ Tile ] slide ( Ice_Block : ts ) | ( null ts ) || ( blocking $ head ts ) = ( Ice_Block : ts ) slide ( t : Empty : ts ) = ( Empty : ( slide ( t : ts ) ) ) slide ( t : ts ) | ( null ts ) || ( blocking $ head ts ) = collide ( t : ts ) collide :: [ Tile ] -> [ Tile ] collide [] = [] collide ( t : ts ) | fixed t = ( t : ts ) collide ( Bomb : Mountain : ts) = [ Empty, Empty ] ++ ts collide ( Heart : House : ts ) = [ Empty, House ] ++ ts collide ( Ice_Block : ts ) | ( null ts ) || ( blocking $ head ts ) = ( Empty : ts ) collide ( t : ts ) | ( movable t ) && ( ( null ts ) || ( blocking $ head ts ) ) = ( t : ts ) collide ( t : Empty : ts ) | movable t = ( Empty : ( slide( t : ts ) ) ) -- Dir represents the orientation of the penguin data Dir = North | East | South | West deriving ( Show, Eq ) -- Pos represents a location on the board data Pos = Pos { posY :: Int, posX :: Int } deriving (Show, Eq) -- I am comparing two implementations for the board: a Haskell -- array (which is immutable, and generates a new one when we -- update it with as association list of elements to change), -- and a nested list (also immutable, but we can explicitly -- share structure as we build an updated list). type BoardArray = Array ( Int, Int ) Tile type BoardList = [ [ Tile ] ] -- Our array bounds max_row :: Int max_row = 3 max_col :: Int max_col = 23 -- A list of tuples of array indices and tiles, used for generating -- the updated array with (//) type TileAssocList = [ ( ( Int, Int ), Tile ) ] -- View functions return a list of board tiles ahead of the given -- position, in the given direction, up to the edge of the board. -- This is "what the penguin sees." -- Here is a version for the array implementation. This utility -- function just tuples up the parameters to range, for clarity make_2d_range :: Int -> Int -> Int -> Int -> [ ( Int, Int ) ] make_2d_range y0 x0 y1 x1 = range ( ( y0, x0 ), ( y1, x1 ) ) -- The penguin can't see the tile it is standing on, so -- we return [] if the penguin is on max_col or max_row -- otherwise we return a range, reversing it for the -- west and north case. To return an the association -- list form usable by the array (//) function I zip -- up the key/value pairs with the list of board values -- accessed by (!) view_array :: BoardArray -> Pos -> Dir -> TileAssocList view_array board pos dir = let row = ( posY pos ) col = ( posX pos ) coord_list = case dir of East -> if ( col == max_col ) then [] else make_2d_range row ( col + 1 ) row max_col South -> if ( row == max_row ) then [] else make_2d_range ( row + 1 ) col max_row col West -> if ( col == 0 ) then [] else make_2d_range row 0 row ( col - 1 ) North -> if ( row == 0 ) then [] else make_2d_range 0 col ( row - 1 ) col tile_assoc = zip coord_list ( map ( (!) board ) coord_list ) in case dir of East -> tile_assoc South -> tile_assoc West -> reverse tile_assoc North -> reverse tile_assoc next_board_array :: BoardArray -> Pos -> Dir -> ( Bool, BoardArray ) next_board_array board pos dir = let ( penguin_moved, updated_view ) = step_array $ view_array board pos dir in ( penguin_moved, board // updated_view ) -- Get a list of tiles in the form of 2-tuples containing -- coordinates and tiles. Unzip, and forward a list of tiles -- to the collision logic, then zip up with coordinates again -- to be used for making an updated game board array. step_array :: TileAssocList -> ( Bool, TileAssocList ) step_array [] = ( False, [] ) step_array tile_assoc = if ( walkable $ head tile_list ) then ( True, tile_assoc ) else ( False, zip coord_list ( collide tile_list ) ) where ( coord_list, tile_list ) = unzip tile_assoc -- Here is a version for the list implementation view_list :: BoardList -> Pos -> Dir -> [Tile] view_list board pos dir = let row = ( posY pos ) col = ( posX pos ) transposed = elem dir [ South, North ] reversed = elem dir [ West, North ] orient | reversed = reverse | otherwise = id trim = case dir of East -> drop ( col + 1 ) South -> drop ( row + 1 ) West -> take col North -> take row extract | transposed = ( transpose board ) !! col | otherwise = board !! row in orient $ trim $ extract step_list :: [ Tile ] -> ( Bool, [ Tile ] ) step_list [] = ( False, [] ) step_list ts = if walkable ( head ts ) then ( True, ts ) else ( False, collide ts ) -- Credit is due to Jeff Licquia for some refactoring of -- my original next_board method for the list implementation next_board_list :: BoardList -> Pos -> Dir -> ( Bool, BoardList ) next_board_list board pos dir = let ( penguin_moved, updated_view_list ) = step_list $ view_list board pos dir in ( penguin_moved, update_board_from_view_list board pos dir updated_view_list ) apply_view_list_to_row :: [ Tile ] -> Int -> Bool -> [ Tile ] -> [Tile] apply_view_list_to_row orig pos True update = take ( pos + 1 ) orig ++ update apply_view_list_to_row orig pos False update = ( reverse update ) ++ ( drop pos orig ) apply_view_list_to_rows :: BoardList -> Int -> Int -> Bool -> [ Tile ] -> BoardList apply_view_list_to_rows orig row pos is_forward update = take row orig ++ nest ( apply_view_list_to_row ( orig !! row ) pos is_forward update ) ++ drop ( row + 1 ) orig where nest xs = [xs] update_board_from_view_list :: BoardList -> Pos -> Dir -> [ Tile ] -> BoardList update_board_from_view_list board pos dir updated_view_list | is_eastwest = apply_view_list_to_rows board ( posY pos ) ( posX pos ) is_forward updated_view_list | otherwise = transpose ( apply_view_list_to_rows ( transpose board ) ( posX pos ) ( posY pos ) is_forward updated_view_list ) where is_forward = elem dir [ East, South ] is_eastwest = elem dir [ East, West ] -- Our world contains both a BoardArray and BoardList so -- we can compare them data World = World { wBoardList :: BoardList, wBoardArray :: BoardArray, wPenguinPos :: Pos, wPenguinDir :: Dir, wHeartCount :: Int } deriving ( Show ) init_board_list :: BoardList init_board_list = [[Tree,Empty,Empty,Empty,Empty,Empty, Empty,Empty,Empty,Empty,Empty,Empty, Empty,Empty,Empty,Tree,Empty,Empty, Empty,Empty,Empty,Ice_Block,Empty,Empty], [Tree,Empty,Bomb,Empty,Mountain,Empty, Heart,Ice_Block,Heart,Empty,Empty,Empty, Empty,Empty,Empty,Empty,Empty,Empty, Tree,Empty,Empty,Tree,Empty,Empty], [Tree,Empty,Empty,Empty,Empty,Empty, Empty,Empty,Empty,Empty,Empty,Empty, Empty,Empty,Empty,Empty,Heart,Empty, Empty,Empty,Mountain,House,Empty,Empty], [Tree,Tree,Empty,Empty,Empty,Empty, Tree,Empty,Empty,Empty,Empty,Empty, Empty,Empty,Empty,Empty,Empty,Empty, Empty,Empty,Empty,Empty,Empty,Empty]] init_board_array :: BoardArray init_board_array = array dimensions $ zip full_range $ concat init_board_list where dimensions = ( ( 0, 0 ), ( max_row, max_col ) ) full_range = range dimensions init_world :: World init_world = ( World init_board_list init_board_array ( Pos 0 0 ) South 3 ) next_penguin_pos :: Pos -> Dir -> Pos next_penguin_pos pos dir = Pos ( posY pos + fst step ) ( posX pos + snd step ) where step = delta dir delta East = ( 0, 1 ) delta South = ( 1, 0 ) delta West = ( 0, -1 ) delta North = ( -1, 0 ) next_world :: World -> Dir -> World next_world old_world move_dir = if ( move_dir /= wPenguinDir old_world ) then ( World ( wBoardList old_world ) ( wBoardArray old_world ) ( wPenguinPos old_world ) move_dir ( wHeartCount old_world ) ) else ( World board_list board_array ( if penguin_moved_array then next_penguin_pos ( wPenguinPos old_world ) ( wPenguinDir old_world ) else ( wPenguinPos old_world ) ) ( wPenguinDir old_world ) ( wHeartCount old_world ) ) where { ( penguin_moved_array, board_array ) = next_board_array ( wBoardArray old_world ) ( wPenguinPos old_world ) ( wPenguinDir old_world ); ( unused_penguin_moved_list, board_list ) = next_board_list ( wBoardList old_world ) ( wPenguinPos old_world ) ( wPenguinDir old_world ) } pretty_tiles :: [Tile] -> String pretty_tiles [] = "\n" pretty_tiles (t:ts) = case t of Empty -> "___" Mountain -> "mt " House -> "ho " Ice_Block -> "ic " Heart -> "he " Bomb -> "bo " Tree -> "tr " ++ pretty_tiles ts pretty_board_list :: BoardList -> String pretty_board_list [] = "" pretty_board_list (ts:tss) = pretty_tiles ts ++ pretty_board_list tss split_tile_list :: [ Tile ] -> [ [ Tile ] ] split_tile_list [] = [] split_tile_list ts = [ take tiles_in_row ts ] ++ ( split_tile_list $ ( drop tiles_in_row ) ts ) where tiles_in_row = max_col + 1 pretty_board_array :: BoardArray -> String pretty_board_array board = pretty_board_list split_tiles where full_range = make_2d_range 0 0 max_row max_col all_tiles = map ( (!) board ) full_range split_tiles = split_tile_list all_tiles pretty_world :: World -> String pretty_world world = "penguin @: " ++ show ( wPenguinPos world ) ++ ", facing: " ++ show ( wPenguinDir world ) ++ ", hearts: " ++ show ( wHeartCount world ) ++ "\n" ++ pretty_board_list ( wBoardList world ) ++ "\n" ++ pretty_board_array ( wBoardArray world ) moves_to_dirs :: [(Dir, Int)] -> [Dir] moves_to_dirs [] = [] moves_to_dirs (m:ms) = replicate ( snd m ) ( fst m ) ++ moves_to_dirs ms moves_board_1 = [(East,21),(South,2),(East,3),(North,2),(West,2) ,(South,4),(West,7),(North,2) ,(West,14),(North,3),(West,2),(North,2),(West,3),(South,2),(West,2),(South,3),(East,2) ,(East,5),(North,3),(East,3),(South,2) ,(East,3),(South,2),(West,2),(North,2),(West,3),(South,2),(West,3),(South,3),(East,3) ,(East,11),(North,2),(West,11),(North,2),(West,2),(South,2),(West,3),(South,3),(East,3) ,(West,2),(North,3),(East,2),(South,2),(West,2),(South,3),(East,2) ] move_sequence :: [(Dir,Int)] -> [World] move_sequence repeats = scanl next_world init_world steps where steps = moves_to_dirs repeats move_sequence' :: [(Dir,Int)] -> World move_sequence' repeats = foldl next_world init_world steps where steps = moves_to_dirs repeats main :: IO () main = do mapM_ putStrLn pretty_worlds -- putStrLn pretty_final_world where worlds = move_sequence moves_board_1 --final_world = move_sequence' moves_board_1 pretty_worlds = map pretty_world worlds -- pretty_final_world = pretty_world final_world
paulrpotts/arctic-slide-haskell
ArcticSlideCore.hs
unlicense
13,266
0
16
4,023
3,806
2,135
1,671
-1
-1
{-# LANGUAGE DeriveGeneric, StandaloneDeriving, DeriveDataTypeable, FlexibleInstances, Rank2Types, FlexibleContexts #-} module Language.Erlang.Modules where import Language.CoreErlang.Parser as P import Language.CoreErlang.Pretty as PP import Language.CoreErlang.Syntax as S import qualified Data.Map as M import qualified Data.List as L import Data.Char as C import Data.Either.Utils import Control.Monad.RWS (gets, ask) import Control.Monad.Error (throwError) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.State ( put, get, modify) import Control.Concurrent.MVar (readMVar, modifyMVarMasked) import Language.Erlang.Core import Language.Erlang.Lang getModTable :: ErlProcess ModTable getModTable = do Left mvar <- gets mod_table liftIO $ readMVar mvar ensureModule :: ModName -> ErlProcess ErlModule ensureModule moduleName = do Left m <- gets mod_table emodule <- liftIO $ modifyMVarMasked m $ \mt -> case M.lookup moduleName mt of Just emodule -> return (mt, emodule) Nothing -> do Right (emodule, modTable') <- liftIO $ loadEModule mt moduleName return (modTable', emodule) return emodule safeGetModule :: ModName -> ErlPure ErlModule safeGetModule moduleName = do Right modTable <- gets mod_table case M.lookup moduleName modTable of Just emodule -> return emodule Nothing -> do s <- ask throwError (ErlException { exc_type = ExcUnknown, reason = ErlAtom "module_not_found", stack = s}) loadEModule :: ModTable -> String -> IO (Either String (ErlModule, ModTable)) loadEModule modTable moduleName = do res <- loadEModule0 moduleName case res of Left er -> return $ Left er Right m -> do let m' = EModule moduleName m let modTable' = M.insert moduleName m' modTable return $ Right (m', modTable') loadEModule0 :: String -> IO (Either String S.Module) loadEModule0 moduleName = do fileContent <- readFile ("samples/" ++ moduleName ++ ".core") case P.parseModule fileContent of Left er -> do return $ Left $ show er Right m -> do -- putStrLn $ prettyPrint m return $ Right (unann m)
gleber/erlhask
src/Language/Erlang/Modules.hs
apache-2.0
2,233
0
17
502
660
341
319
62
2
module Main (main) where import Language.Haskell.HLint (hlint) import System.Exit (exitFailure, exitSuccess) arguments :: [String] arguments = [ "puzzles/0-easy/onboarding/solution.hs" , "puzzles/0-easy/kirks-quest-the-descent/solution.hs" , "puzzles/0-easy/ragnarok-power-of-thor/solution.hs" , "puzzles/0-easy/skynet-the-chasm/solution.hs" , "puzzles/0-easy/temperatures/solution.hs" , "puzzles/0-easy/mars-lander/solution.hs" ] main :: IO () main = do hints <- hlint arguments if null hints then exitSuccess else exitFailure
lpenz/codingame-haskell-solutions
hlint.hs
apache-2.0
568
0
8
87
103
60
43
15
2
module Helpers.GridPolytopes (countPolygons, Polygon (..)) where import Helpers.ListHelpers (cartesianProduct) import Helpers.Subsets (choose) import Data.List (genericTake, nub) import Math.NumberTheory.Powers.Squares (exactSquareRoot) import Data.Set (Set) import qualified Data.Set as Set data Polygon = Triangle | Square | Hexagon deriving Eq type PVector = [Integer] type VertexSet = Set PVector magnitudeSquared :: [Integer] -> Integer magnitudeSquared = sum . map (^2) magSolutions :: Integer -> [[Integer]] magSolutions n = magSolutionsList !! fromIntegral n magSolutionsList = map magSolutions' [0..] -- solutions to x^2 + y^2 + z^2 = n. magSolutions' :: Integer -> [[Integer]] magSolutions' = recurse 3 where -- recurse :: Int -> Int -> [[Int]] recurse 1 n = case exactSquareRoot n of (Just rootN) -> [[rootN]] Nothing -> [] recurse k n = concatMap (\p -> map (p:) $ recurse (k-1) (n-p^2)) validParts where validParts = takeWhile ((<=n) . (^2)) [0..] -- This reverses; probably this can be fixed with a fold. -- allSigns [0,1,2] = [[-2,-1,0],[2,-1,0],[-2,1,0],[2,1,0]] -- allSigns :: [Int] -> [[Int]] allSigns :: (Eq a, Num a) => [a] -> [[a]] allSigns ns = recurse ns [[]] where recurse [] known = known recurse (0:ks) known = recurse ks $ map (0:) known recurse (k:ks) known = recurse ks $ concatMap (\i -> [-k:i, k:i]) known isValid :: Polygon -> PVector -> PVector -> Bool isValid polygon v u = magnitudesMatch && correctAngle where magnitudesMatch = magnitudeSquared u == magnitudeSquared v dotProduct = sum $ zipWith (*) u v correctAngle | polygon == Triangle = 2 * dotProduct == magnitudeSquared v | polygon == Square = dotProduct == 0 | polygon == Hexagon = -2 * dotProduct == magnitudeSquared v adjacentSides :: Polygon -> Integer -> [[[Integer]]] adjacentSides polygon = filter (\[v,u] -> isValid polygon v u) . choose 2 . concatMap allSigns . magSolutions makeShape :: Polygon -> (PVector -> PVector -> Set PVector) makeShape Triangle = makePolygon (\u v -> [[], [u], [v]]) makeShape Square = makePolygon (\u v -> [[], [u], [v], [u,v]]) makeShape Hexagon = makePolygon (\u v -> [[], [u], [v], [u,u,v], [u,v,v], [u,u,v,v]]) makePolygon :: (PVector -> PVector -> [[PVector]]) -> PVector -> PVector -> VertexSet makePolygon vectorCombinations u v = Set.fromList $ map (\c -> zipWith (-) c maxCoords) coords where maxCoords = foldr1 (zipWith min) coords coords = map (foldr (zipWith (+)) [0,0,0]) $ vectorCombinations u v boundingBox :: VertexSet -> [Integer] boundingBox polygon = foldr1 (zipWith max) $ Set.toList polygon -- Hexagons with side length k, all nonnegative coordinates, and touching the coordinate planes normalized :: Polygon -> Integer -> [VertexSet] normalized polygon k = nub $ map (\[v,u] -> makeShape polygon v u) $ adjacentSides polygon k -- Bounding boxes for hexagons with side length sqrt(k) boundingBoxes :: Polygon -> Integer -> [[Integer]] boundingBoxes shape = map boundingBox . normalized shape allBoundingBoxes :: Polygon -> [[[Integer]]] allBoundingBoxes Square = allSquareBoundingBoxes allBoundingBoxes Triangle = allTriangleBoundingBoxes allBoundingBoxes Hexagon = allHexagonBoundingBoxes allSquareBoundingBoxes :: [[[Integer]]] allSquareBoundingBoxes = map (boundingBoxes Square) [1..] allTriangleBoundingBoxes :: [[[Integer]]] allTriangleBoundingBoxes = map (boundingBoxes Triangle) [1..] allHexagonBoundingBoxes :: [[[Integer]]] allHexagonBoundingBoxes = map (boundingBoxes Hexagon) [1..] countPolygons :: Polygon -> Integer -> Integer countPolygons polygon n = sum $ map countShifts validBoundingBoxes where countShifts = product . map (`subtract` n) validBoundingBoxes = filter ((<n) . maximum) $ concat $ genericTake upperBound (allBoundingBoxes polygon) upperBound | polygon == Triangle = 3 * n^2 | polygon == Square = 3 * n^2 -- improve this bound! | polygon == Hexagon = (3 * n^2) `div` 4 + 1
peterokagey/haskellOEIS
src/Helpers/GridPolytopes.hs
apache-2.0
3,988
0
14
711
1,475
809
666
68
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.ProjectStatus where import GHC.Generics import Data.Text import qualified Data.Aeson -- | data ProjectStatus = ProjectStatus { phase :: Maybe Text -- ^ phase is the current lifecycle phase of the project } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON ProjectStatus instance Data.Aeson.ToJSON ProjectStatus
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/ProjectStatus.hs
apache-2.0
521
0
9
77
83
50
33
14
0
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Bug Tracker</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
secdec/zap-extensions
addOns/bugtracker/src/main/javahelp/org/zaproxy/zap/extension/bugtracker/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
956
77
66
156
407
206
201
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Controller ( withFoundation ) where -- standard libraries import Control.Monad import Control.Concurrent.MVar import System.Directory import System.FilePath -- friends import Foundation import Settings import Yesod.Helpers.Static -- Import all relevant handler modules here. import Handler.Root import Handler.Effects import Handler.Images -- This line actually creates our YesodSite instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see -- the comments there for more details. mkYesodDispatch "Foundation" resourcesFoundation -- Some default handlers that ship with the Yesod site template. You will -- very rarely need to modify this. getFaviconR :: Handler () getFaviconR = sendFile "image/x-icon" "favicon.ico" getRobotsR :: Handler RepPlain getRobotsR = return $ RepPlain $ toContent "User-agent: *" -- This function allocates resources (such as a database connection pool), -- performs initialization and creates a WAI application. This is also the -- place to put your migrate statements to have automatic database -- migrations handled by Yesod. withFoundation :: (Application -> IO a) -> IO a withFoundation f = Settings.withConnectionPool $ \p -> do lock <- newMVar () wrapper <- readFile "EffectWrapper.hs" cache <- createCache let static = fileLookupDir Settings.staticdir typeByExt foundation = Foundation { getStatic = static , connPool = p , cudaLock = lock , effectCodeWrapper = wrapper , cacheDir = cache } toWaiApp foundation >>= f where -- Temporary directory where images and code are stored createCache = do cache <- getAppUserDataDirectory "funky-foto-cache" exists <- doesDirectoryExist cache when exists (removeDirectoryRecursive cache) createDirectory cache createDirectory $ cache </> "images" createDirectory $ cache </> "code" return cache
sseefried/funky-foto
Controller.hs
bsd-2-clause
2,165
0
13
532
332
176
156
39
1
module Cologne.ParseNFF (parseNFF) where import Text.ParserCombinators.Parsec import qualified Text.ParserCombinators.Parsec.Token as PT import Text.ParserCombinators.Parsec.Language (emptyDef) import Data.Vect import Graphics.Formats.Assimp (Camera(Camera)) import Control.Arrow (left) import Control.Applicative hiding ((<|>), many) import Control.Monad (ap) import Cologne.Primitives import qualified Cologne.Primitives.Sphere as S import Cologne.Accel.List {- Parser for NFF (Neutral File Format). This is the first scene description - language Cologne supports. The language is not very expressive. It's like - training wheels, really. - - NOTE: We're using a modified version of nff, more suited to our ray tracer. - We may decide to implement the exact spec in the future. - - TODO: Expressions would be very helpful - Comments - - More info on NFF: - http://tog.acm.org/resources/Sfloat/NFF.TXT -} {- Let's make an instance of Applicative for GenParser like they do in Real - World Haskell: - http://book.realworldhaskell.org/read/using-parsec.html -} -- instance Applicative (GenParser s a) where -- pure = return -- (<*>) = ap type ColorInfo = (Vec3, Vec3, ReflectionType) type ObjParser a = GenParser Char ColorInfo a type ContextType = Context [Primitive ColorInfo] ColorInfo {- - Use some predefined helpers from parsec for ints and floats. The only - interesting bit is that their float parser doesn't like negatives so we have - to be a bit more careful there. -} lexer :: PT.TokenParser st lexer = PT.makeTokenParser emptyDef int = PT.integer lexer uFloat = PT.float lexer float' = try (negate <$ char '-' <*> uFloat) <|> try uFloat <|> fromIntegral <$> int float = realToFrac <$> float' {- light - format l %g %g %g [%g %g %g] - X Y Z R G B - - e.g. l 3 7 8 0.9 0.8 0.7 - l 3 7 8 - - This represents a point light source, which we just represent as a tiny - sphere with emission. - - First strip off the 'l' then build the light in an applicative manner. <$> - just lifts light to the functor level then we apply it to the parsed - doubles. -} light :: ObjParser (Primitive ColorInfo) light = char 'l' *> spaces *> (light' <$> float <*> float <*> float <*> float <*> float <*> float) <* spaces where light' x y z r g b = S.sphere (Vec3 x y z) 0.0000001 ((Vec3 0 0 0), (Vec3 r g b), Diffuse) {- sphere - format: s %g %g %g %g - center.x center.y center.z radius - - A difficulty here is that this format doesn't include the color information - with the primitives. They're supposed to take on whatever color most - recently preceded them, thus we must keep the previous color as state. - - One potentially tricky thing here is that 'spaces' reads in the end-of-line - characters of well. This is because it's defined using isSpace from - Data.Char, which returns true on ' ', '\t', '\n', and '\r', and possibly - others. -} sphere :: ObjParser (Primitive ColorInfo) sphere = char 's' *> spaces *> (sph <$> float <*> float <*> float <*> float <*> getState) <* spaces where sph x y z r c = S.sphere (Vec3 x y z) r c {- color - format f %g %g %g %g %g %g %s - R G B R G B spec|diff|refr - - All of the floats should be between 0 and 1. The first triple represents the - color and the second represents the color of the emitted light, if any. - - I'm sticking to this format for now, since the way it's defined in the nff - spec doesn't suit us very well. -} color :: ObjParser () color = do info <- (char 'f' *> spaces *> (clr <$> float <*> float <*> float <*> float <*> float <*> float <*> reflT) <* spaces) setState info where clr r1 g1 b1 r2 g2 b2 r = (Vec3 r1 g1 b1, Vec3 r2 g2 b2, r) reflT = spaces *> (Refractive <$ string "refr" <|> Specular <$ string "spec" <|> Diffuse <$ string "diff" <?> "reflection type") background :: ObjParser Vec3 background = char 'b' *> (Vec3 <$> float <*> float <*> float) <* spaces --background = char 'b' *> (Vec3 <$> count 3 float) --background = char 'b' *> (Vec3 <$> (chainr1 float (<*>))) --nToken 1 comb1 comb2 = comb1 <$> comb2 --nToken n comb1 comb2 = (nToken (n-1) comb1 comb2) <*> comb2 {- viewpoint - - Where the camera is located and where it points. We expect - it at the beginning of the file. -} viewpoint :: ObjParser (Vec3, Vec3) viewpoint = do char 'v' >> spaces from <- string "from " *> (Vec3 <$> float <*> float <*> float) <* spaces at <- string "at " *> (Vec3 <$> float <*> float <*> float) <* spaces return (from, normalize at) -- If we were complying fully to the nff spec we would implement these but we -- have no need for them yet -- up <- string "up " *> (Vec3 <$> float <*> float <*> float) <* spaces -- angle <- string "angle " *> float <* spaces -- hither <- string "hither " *> float -- return (from, at, up, angle, hither) file :: ObjParser ContextType file = do (at, look) <- viewpoint objs <- many $ (skipMany color) *> objects eof let camera = Camera "" at (Vec3 0 0 1) look 60 1 1000000000 1 pos <- getPosition return $ Context defaultOptions [camera] objs where objects = sphere <|> light parseNFF :: String -> String -> Either String ContextType parseNFF input filename = (flip left) (runParser file noState filename input) show where noState = ((Vec3 0 0 0), (Vec3 0 0 0), (Diffuse))
joelburget/Cologne
Cologne/ParseNFF.hs
bsd-3-clause
5,595
0
18
1,362
1,017
543
474
69
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.NV.TextureExpandNormal -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/NV/texture_expand_normal.txt NV_texture_expand_normal> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.NV.TextureExpandNormal ( -- * Enums gl_TEXTURE_UNSIGNED_REMAP_MODE_NV ) where import Graphics.Rendering.OpenGL.Raw.Tokens
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/NV/TextureExpandNormal.hs
bsd-3-clause
688
0
4
78
37
31
6
3
0
-------------------------------------------------------------------------------- -- Chip16 Assembler written in Haskell -------------------------------------------------------------------------------- module HC.Ops where import Data.Bits import Data.Int import Data.List import Data.Maybe import Data.Word import Control.Applicative data Parameter = Bit Int | Imm4 Int | Imm8 Int | Imm16 | RegX | RegY | RegZ | SP deriving (Eq, Show) type Op = ( String, Int, [ Parameter ] ) jump :: [ ( String, Int ) ] jump = [ ( "z", 0x0 ) , ( "mz", 0x0 ) , ( "nz", 0x1 ) , ( "n", 0x2 ) , ( "nn", 0x3 ) , ( "p", 0x4 ) , ( "o", 0x5 ) , ( "no", 0x6 ) , ( "a", 0x7 ) , ( "ae", 0x8 ) , ( "nc", 0x8 ) , ( "b", 0x9 ) , ( "c", 0x9 ) , ( "mc", 0x9 ) , ( "be", 0xA ) , ( "g", 0xB ) , ( "ge", 0xC ) , ( "l", 0xD ) , ( "le", 0xE ) , ( "f", 0xF ) -- Reserved ] operators :: [ Op ] operators = [ ( "nop", 0x00, [ ] ) , ( "cls", 0x01, [ ] ) , ( "vblnk", 0x02, [ ] ) , ( "bgc", 0x03, [ Imm4 4 ] ) , ( "spr", 0x04, [ Imm16 ] ) , ( "drw", 0x05, [ RegX, RegY, Imm16 ] ) , ( "drw", 0x06, [ RegX, RegY, RegZ ] ) , ( "rnd", 0x07, [ RegX, Imm16 ] ) , ( "flip", 0x08, [ Bit 25, Bit 24] ) , ( "snd0", 0x09, [ ] ) , ( "snd1", 0x0A, [ Imm16 ] ) , ( "snd2", 0x0B, [ Imm16 ] ) , ( "snd3", 0x0C, [ Imm16 ] ) , ( "snp", 0x0D, [ RegX, Imm16 ] ) , ( "sng", 0x0E, [ Imm8 1, Imm16 ] ) , ( "jmp", 0x10, [ Imm16 ] ) , ( "", 0x12, [ Imm16 ] ) -- special , ( "jme", 0x13, [ RegX, RegY, Imm16 ] ) , ( "call", 0x14, [ Imm16 ] ) , ( "ret", 0x15, [ ] ) , ( "jmp", 0x16, [ RegX ] ) , ( "", 0x17, [ Imm16 ] ) -- special , ( "call", 0x18, [ Imm16 ] ) , ( "ldi", 0x20, [ RegX, Imm16 ] ) , ( "ldi", 0x21, [ SP, Imm16 ] ) , ( "ldm", 0x22, [ RegX, Imm16] ) , ( "ldm", 0x23, [ RegX, RegY ] ) , ( "mov", 0x24, [ RegX, RegY ] ) , ( "stm", 0x30, [ RegX, Imm16 ] ) , ( "stm", 0x31, [ RegX, RegY ] ) , ( "addi", 0x40, [ RegX, Imm16 ] ) , ( "add", 0x41, [ RegX, RegY ] ) , ( "add", 0x42, [ RegX, RegY, RegZ ] ) , ( "subi", 0x50, [ RegX, Imm16 ] ) , ( "sub", 0x51, [ RegX, RegY ] ) , ( "sub", 0x52, [ RegX, RegY, RegZ ] ) , ( "cmpi", 0x53, [ RegX, Imm16 ] ) , ( "cmp", 0x54, [ RegX, RegY ] ) , ( "andi", 0x60, [ RegX, Imm16 ] ) , ( "and", 0x61, [ RegX, RegY ] ) , ( "and", 0x62, [ RegX, RegY, RegZ ] ) , ( "tsti", 0x63, [ RegX, Imm16 ] ) , ( "tst", 0x64, [ RegX, RegY ] ) , ( "ori", 0x70, [ RegX, Imm16] ) , ( "or", 0x71, [ RegX, RegY ] ) , ( "or", 0x72, [ RegX, RegY, RegZ ] ) , ( "xori", 0x80, [ RegX, Imm16 ] ) , ( "xor", 0x81, [ RegX, RegY ] ) , ( "xor", 0x82, [ RegX, RegY, RegZ ] ) , ( "muli", 0x90, [ RegX, Imm16 ] ) , ( "mul", 0x91, [ RegX, RegY ] ) , ( "mul", 0x92, [ RegX, RegY, RegZ ] ) , ( "divi", 0xA0, [ RegX, Imm16 ] ) , ( "div", 0xA1, [ RegX, RegY] ) , ( "div", 0xA2, [ RegX, RegY, RegZ ] ) , ( "shl", 0xB0, [ RegX, Imm4 4 ] ) , ( "shr", 0xB1, [ RegX, Imm4 4 ] ) , ( "sar", 0xB2, [ RegX, Imm4 4 ] ) , ( "shl", 0xB3, [ RegX, RegY ] ) , ( "shr", 0xB4, [ RegX, RegY ] ) , ( "sar", 0xB5, [ RegX, RegY ] ) , ( "push", 0xC0, [ RegX ] ) , ( "pop", 0xC1, [ RegX ] ) , ( "pushall", 0xC2, [ ] ) , ( "popall", 0xC3, [ ] ) , ( "pushf", 0xC4, [ ] ) , ( "popf", 0xC5, [ ] ) , ( "pal", 0xD0, [ Imm16 ] ) , ( "pal", 0xD1, [ RegX ] ) ] getOperatorByName :: String -> [ Op ] getOperatorByName name = filter (\( name', _, _ ) -> name == name') operators getOperatorByCode :: Int -> Maybe Op getOperatorByCode n = find (\( _, n', _ ) -> n == n' ) operators getJumpByCode :: Int -> String getJumpByCode n = fst . fromJust $ find (\( j, n' ) -> n' == n ) jump getJumpByName :: String -> Maybe Int getJumpByName j = snd <$> find (\( j', n ) -> j' == j ) jump
nandor/hcasm
HC/Ops.hs
bsd-3-clause
4,323
0
9
1,613
1,716
1,107
609
124
1
module Main where import qualified Language.Modelica.Test.Lexer as Lexer import qualified Language.Modelica.Test.Expression as Expr import qualified Language.Modelica.Test.Modification as Mod import qualified Language.Modelica.Test.Basic as Basic import qualified Language.Modelica.Test.ClassDefinition as ClassDef import qualified Language.Modelica.Test.Equation as Equation import qualified Language.Modelica.Test.ComponentClause as CompClause import qualified Language.Modelica.Test.Programme as Prog import qualified Language.Modelica.Test.Utility as Utility import Control.Monad (when) main :: IO () main = do Utility.banner "Lexer" as <- Lexer.test Utility.banner "Basic" bs <- Basic.test Utility.banner "Expression" cs <- Expr.test Utility.banner "Modification" ds <- Mod.test Utility.banner "Equation" es <- Equation.test Utility.banner "Component Clause" fs <- CompClause.test Utility.banner "Class Definition" gs <- ClassDef.test Utility.banner "Comment" hs <- Prog.test Utility.banner "QuickCheck tests" i <- Prog.runTests let tests = as ++ bs ++ cs ++ ds ++ es ++ fs ++ gs ++ hs ++ [i] testsLen = length tests passedLen = length $ filter (== True) tests Utility.banner "Final Result" putStrLn $ "Have we successfully passed all " ++ (show testsLen) ++ " tests? " when (testsLen /= passedLen) (putStrLn $ "Passed only " ++ show passedLen ++ " tests!") Utility.printBoolOrExit (and tests) putStrLn ""
xie-dongping/modelicaparser
test/Main.hs
bsd-3-clause
1,500
0
17
265
424
225
199
40
1
------------------------------------------------------------------------------- -- | -- Module : Control.Monad.Trans.Supply -- Copyright : (C) 2013 Merijn Verstraaten -- License : BSD-style (see the file LICENSE) -- Maintainer : Merijn Verstraaten <[email protected]> -- Stability : experimental -- Portability : non-portable -- -- [Computation type:] Computations that require a supply of values. -- -- [Binding strategy:] Applicative values are functions that consume an input -- from a supply to produce a value. -- -- [Useful for:] Providing a supply of unique names or other values to -- computations needing them. -- -- [Zero and plus:] Identical to the underlying implementations (if any) of -- 'empty', '<|>', 'mzero' and 'mplus'. -- -- The @'Supply' s a@ monad represents a computation that consumes a supply of -- @s@'s to produce a value of type @a@. One example use is to simplify -- computations that require the generation of unique names. The 'Supply' monad -- can be used to provide a stream of unique names to such a computation. ------------------------------------------------------------------------------- module Control.Monad.Supply ( -- * The MonadSupply Class MonadSupply (..) , demand -- * The Supply Monad , Supply , withSupply , runSupply , runListSupply , runMonadSupply -- * The Supply Monad Transformer , SupplyT , withSupplyT , runSupplyT , runListSupplyT , runMonadSupplyT , module Control.Monad , module Control.Monad.Trans ) where import Control.Monad.Supply.Class import Control.Monad.Trans.Supply ( Supply , SupplyT , withSupply , withSupplyT , runSupply , runSupplyT , runListSupply , runListSupplyT , runMonadSupply , runMonadSupplyT ) import Control.Monad import Control.Monad.Trans
merijn/transformers-supply
Control/Monad/Supply.hs
bsd-3-clause
1,868
0
5
383
147
108
39
29
0
module Text.Velocity ( defaultVelocityState , Vstate(..) , render , pretty_ast -- * Parsing , parseVelocityM , parseVelocity , parseVelocityFile ) where import Control.Applicative hiding ((<|>), many) import Control.Arrow import Control.Monad import Control.Monad.IO.Class import Data.Maybe import Control.Monad.State import qualified Control.Monad.State.Class as State import Text.Velocity.Context import Text.Velocity.Parse import Text.Velocity.Types data Vstate = Vstate { vs_template_root :: FilePath , vs_stack :: Stack Context } vs_add_macro :: Macbind -> Vstate -> Vstate vs_add_macro binding state_ = state_ { vs_stack = stack_map_top (addMacro binding) (vs_stack state_) } stack_map_top :: (a -> a) -> Stack a -> Stack a stack_map_top f stack = case stack of [] -> [] x : xs -> f x : xs defaultVelocityState :: Vstate defaultVelocityState = Vstate "/home/john/sender/templates/" [] v_get_var :: (Functor m, Monad m) => String -> StateT Vstate m (Maybe VarBind) v_get_var name = State.gets $ vs_stack >>> concatMap co_vars >>> filter (varName >>> (name ==)) >>> listToMaybe v_get_macro :: (Functor m, Monad m) => String -> StateT Vstate m (Maybe Macbind) v_get_macro name = State.gets $ vs_stack >>> concatMap co_macs >>> filter (macroName >>> (name ==)) >>> listToMaybe render :: [Node] -> StateT Vstate IO String render = phase1 >=> phase_2 pretty_ast :: [Node] -> String pretty_ast nodes = case nodes of [] -> "" node : tail_ -> pretty 0 node ++ pretty_ast tail_ where pretty level node = let level' = succ level indent = replicate (4 * level) ' ' in indent ++ case node of Fragment nodes_ -> "Fragment\n" ++ concatMap (pretty level') nodes_ Call name args -> "Call " ++ name ++ "\n" ++ concatMap (pretty level') args -- MacroDef name args body -> "MacroDef " ++ name ++ " " ++ show args ++ "\n" ++ concatMap (pretty level') body _ -> show node ++ "\n" -- | You can use a macro before its definition. phase1 :: [Node] -> StateT Vstate IO [Node] phase1 nodes = case nodes of [] -> return [] node : tail_ -> do replacements <- case node of BlockComment _ -> return [] LineComment _ -> return [] MacroDef name args body -> do State.modify $ vs_add_macro (Macbind name args body) return [] _ -> return [node] (replacements ++) <$> phase1 tail_ with_context :: Context -> StateT Vstate IO a -> StateT Vstate IO a with_context context = withStateT (\ s -> s { vs_stack = context : vs_stack s }) -- | True if @bind@ does not occur in @macparams@. free_var :: VarBind -> [Node] -> Bool free_var bind macparams = not $ elem (varName bind) (flip mapMaybe macparams $ \ node -> case node of Var name -> Just name _ -> Nothing) -- | This is supposed to be similar to lambda calculus beta-reduction. replace_var :: VarBind -> [Node] -> [Node] replace_var bind@(VarBind name content) nodes = flip concatMap nodes $ \ node -> case node of Fragment nodes_ -> [Fragment (replace_var bind nodes_)] -- Var name2 | name == name2 -> [content] -- QuietVar name2 | name == name2 -> [content] defn@(MacroDef mname mparams mbody) -> if free_var bind (map (Var . maName) mparams) -- then [MacroDef mname mparams (replace_var bind mbody)] then undefined -- FIXME else [defn] Call name_ args -> [Call name_ (replace_var bind args)] _ -> [node] -- what to do when undefined variable? -- * print '$var' literally -- * throw an error invoke :: Node -> StateT Vstate IO String invoke (Call name argvals) = do m_macbind <- v_get_macro name case m_macbind of Nothing -> error $ "undefined macro: #" ++ name Just macbind@(Macbind _ macargs mbody) -> do unless (length macargs == length argvals) $ do error $ "macro formal and actual argument count must match:\nformal: " ++ show macbind ++ "\nactual: " ++ show argvals -- let assignment = zipWith (\ (Var m) a -> VarBind m a) (map (Var . maName) macargs) argvals -- let mbody' = foldr (\ a b -> replace_var a b) mbody assignment let mbody' = undefined -- FIXME render mbody' {- with_context (Context (zipWith (\ formal actual -> case formal of Var name -> VarBind name actual _ -> error $ "macro formal argument must be variable reference; got " ++ show formal ) macargs argvals) []) (render mbody) -} -- | Render the parsed template into string. phase_2 :: [Node] -> StateT Vstate IO String phase_2 nodes_ = action 0 nodes_ where depth_limit = 8 action :: Integer -> [Node] -> StateT Vstate IO String action depth nodes = let descend = action (succ depth) in do case nodes of node : tail_ -> do when (depth > depth_limit) $ do error $ "possible cycle: phase_2 depth reached " ++ show depth ++ " while evaluating " ++ show node -- liftIO $ putStrLn $ show node result <- case node of Literal s -> return s Fragment nodes__ -> descend nodes__ -- Var name -> v_get_var name >>= maybe (error $ "undefined variable: $" ++ name) (descend . (: []) . varContent) -- QuietVar name -> v_get_var name >>= maybe (return "") (descend . (: []) . varContent) Zacall name -> do m_macbind <- v_get_macro $ nameToString name case m_macbind of Nothing -> do liftIO . putStrLn $ "warning: silently converting #" ++ nameToString name ++ " to literal" return ('#' : nameToString name) Just _ -> invoke (Call (nameToString name) []) call@(Call _ _) -> invoke call _ -> error $ "phase_2 not implemented: " ++ show node (result ++) <$> render tail_ _ -> return ""
edom/velocity
Text/Velocity.hs
bsd-3-clause
7,030
0
30
2,676
1,614
821
793
128
7
{-# LANGUAGE ScopedTypeVariables, FlexibleContexts, TypeFamilies, TypeSynonymInstances, FlexibleInstances, GADTs, RankNTypes, UndecidableInstances #-} -- | The 'Enabled' module allows the construction of circuits that use -- additional control logic -- an enable signal -- that externalizes whether a -- data signal is valid. module Language.KansasLava.Protocols.Enabled (Enabled, packEnabled, unpackEnabled, enabledVal, isEnabled, mapEnabled, enabledS, disabledS, ) where import Language.KansasLava.Signal import Language.KansasLava.Rep -- | Enabled is a synonym for Maybe. type Enabled a = Maybe a -- | This is lifting *Comb* because Comb is stateless, and the 'en' Bool being -- passed on assumes no history, in the 'a -> b' function. mapEnabled :: (Rep a, Rep b, sig ~ Signal clk) => (forall clk' . Signal clk' a -> Signal clk' b) -> sig (Enabled a) -> sig (Enabled b) mapEnabled f en = pack (en_bool,f en_val) where (en_bool,en_val) = unpack en -- | Lift a data signal to be an Enabled signal, that's always enabled. enabledS :: (Rep a, sig ~ Signal clk) => sig a -> sig (Enabled a) enabledS s = pack (pureS True,s) -- | Create a signal that's never enabled. disabledS :: (Rep a, sig ~ Signal clk) => sig (Enabled a) disabledS = pack (pureS False,undefinedS) -- | Combine a boolean control signal and an data signal into an enabled signal. packEnabled :: (Rep a, sig ~ Signal clk) => sig Bool -> sig a -> sig (Enabled a) packEnabled s1 s2 = pack (s1,s2) -- | Break the representation of an Enabled signal into a Bool signal (for whether the -- value is valid) and a signal for the data. unpackEnabled :: (Rep a, sig ~ Signal clk) => sig (Enabled a) -> (sig Bool, sig a) unpackEnabled = unpack -- | Drop the Enabled control from the signal. The output signal will be Rep -- unknown if the input signal is not enabled. enabledVal :: (Rep a, sig ~ Signal clk) => sig (Enabled a) -> sig a enabledVal = snd . unpackEnabled -- | Determine if the the circuit is enabled. isEnabled :: (Rep a, sig ~ Signal clk) => sig (Enabled a) -> sig Bool isEnabled = fst . unpackEnabled
andygill/kansas-lava
Language/KansasLava/Protocols/Enabled.hs
bsd-3-clause
2,134
0
10
420
524
279
245
29
1
module AssetsHelper where import Assets import Utils.Utils import TypeSystem.Parser.TypeSystemParser import TypeSystem import Data.List import qualified Data.Map as M import Control.Arrow ((&&&)) import SyntaxHighlighting.Coloring stfl = parseTypeSystem Assets._Test_STFL_language (Just "Assets/STFL.language") & either (error . show) id stflSyntax = get tsSyntax stfl optionsSyntax = parseTypeSystem Assets._Manual_Options_language (Just "Assets/Manual/Options.Language") & either (error . show) id & get tsSyntax terminalStyle = Assets._Terminal_style & parseColoringFile "Assets/Terminal.style" & either error id knownStyles :: M.Map Name FullColoring knownStyles = Assets.allAssets & filter ((".style" `isSuffixOf`) . fst) |> (fst &&& (\(fp, style) -> parseColoringFile ("Assets: "++fp) style & either error id)) & M.fromList fetchStyle name = let errMsg = "No builtin style with name "++name ++ "\nBuiltin styles are:\n" ++ (knownStyles & M.keys & unlines & indent) in checkExists (name++".style") knownStyles errMsg minimalStyleTypes = Assets._MinimalStyles_txt & validLines
pietervdvn/ALGT
src/AssetsHelper.hs
bsd-3-clause
1,127
23
14
175
343
185
158
27
1
{-# LANGUAGE CPP , GADTs , Rank2Types , DataKinds , TypeFamilies , FlexibleContexts , UndecidableInstances , LambdaCase , MultiParamTypeClasses , OverloadedStrings #-} {-# OPTIONS_GHC -Wall -fwarn-tabs -fsimpl-tick-factor=1000 #-} module Language.Hakaru.Runtime.LogFloatPrelude where #if __GLASGOW_HASKELL__ < 710 import Data.Functor ((<$>)) import Control.Applicative (Applicative(..)) #endif import Data.Foldable as F import qualified System.Random.MWC as MWC import qualified System.Random.MWC.Distributions as MWCD import Data.Number.Natural import Data.Number.LogFloat hiding (sum, product) import qualified Data.Number.LogFloat as LF import Data.STRef import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Generic as G import qualified Data.Vector.Generic.Mutable as M import Control.Monad import Control.Monad.ST import Prelude hiding (init, sum, product, exp, log, (**), pi) import qualified Prelude as P type family MinBoxVec (v1 :: * -> *) (v2 :: * -> *) :: * -> * type instance MinBoxVec V.Vector v = V.Vector type instance MinBoxVec v V.Vector = V.Vector type instance MinBoxVec U.Vector U.Vector = U.Vector type family MayBoxVec a :: * -> * type instance MayBoxVec () = U.Vector type instance MayBoxVec Int = U.Vector type instance MayBoxVec Double = U.Vector type instance MayBoxVec LogFloat = U.Vector type instance MayBoxVec Bool = U.Vector type instance MayBoxVec (U.Vector a) = V.Vector type instance MayBoxVec (V.Vector a) = V.Vector type instance MayBoxVec (a,b) = MinBoxVec (MayBoxVec a) (MayBoxVec b) newtype instance U.MVector s LogFloat = MV_LogFloat (U.MVector s Double) newtype instance U.Vector LogFloat = V_LogFloat (U.Vector Double) instance U.Unbox LogFloat instance M.MVector U.MVector LogFloat where {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicOverlaps #-} {-# INLINE basicUnsafeNew #-} #if __GLASGOW_HASKELL__ > 710 {-# INLINE basicInitialize #-} #endif {-# INLINE basicUnsafeReplicate #-} {-# INLINE basicUnsafeRead #-} {-# INLINE basicUnsafeWrite #-} {-# INLINE basicClear #-} {-# INLINE basicSet #-} {-# INLINE basicUnsafeCopy #-} {-# INLINE basicUnsafeGrow #-} basicLength (MV_LogFloat v) = M.basicLength v basicUnsafeSlice i n (MV_LogFloat v) = MV_LogFloat $ M.basicUnsafeSlice i n v basicOverlaps (MV_LogFloat v1) (MV_LogFloat v2) = M.basicOverlaps v1 v2 basicUnsafeNew n = MV_LogFloat `liftM` M.basicUnsafeNew n #if __GLASGOW_HASKELL__ > 710 basicInitialize (MV_LogFloat v) = M.basicInitialize v #endif basicUnsafeReplicate n x = MV_LogFloat `liftM` M.basicUnsafeReplicate n (logFromLogFloat x) basicUnsafeRead (MV_LogFloat v) i = logToLogFloat `liftM` M.basicUnsafeRead v i basicUnsafeWrite (MV_LogFloat v) i x = M.basicUnsafeWrite v i (logFromLogFloat x) basicClear (MV_LogFloat v) = M.basicClear v basicSet (MV_LogFloat v) x = M.basicSet v (logFromLogFloat x) basicUnsafeCopy (MV_LogFloat v1) (MV_LogFloat v2) = M.basicUnsafeCopy v1 v2 basicUnsafeMove (MV_LogFloat v1) (MV_LogFloat v2) = M.basicUnsafeMove v1 v2 basicUnsafeGrow (MV_LogFloat v) n = MV_LogFloat `liftM` M.basicUnsafeGrow v n instance G.Vector U.Vector LogFloat where {-# INLINE basicUnsafeFreeze #-} {-# INLINE basicUnsafeThaw #-} {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicUnsafeIndexM #-} {-# INLINE elemseq #-} basicUnsafeFreeze (MV_LogFloat v) = V_LogFloat `liftM` G.basicUnsafeFreeze v basicUnsafeThaw (V_LogFloat v) = MV_LogFloat `liftM` G.basicUnsafeThaw v basicLength (V_LogFloat v) = G.basicLength v basicUnsafeSlice i n (V_LogFloat v) = V_LogFloat $ G.basicUnsafeSlice i n v basicUnsafeIndexM (V_LogFloat v) i = logToLogFloat `liftM` G.basicUnsafeIndexM v i basicUnsafeCopy (MV_LogFloat mv) (V_LogFloat v) = G.basicUnsafeCopy mv v elemseq _ x z = G.elemseq (undefined :: U.Vector a) (logFromLogFloat x) z lam :: (a -> b) -> a -> b lam = id {-# INLINE lam #-} app :: (a -> b) -> a -> b app f x = f x {-# INLINE app #-} let_ :: a -> (a -> b) -> b let_ x f = let x1 = x in f x1 {-# INLINE let_ #-} ann_ :: a -> b -> b ann_ _ a = a {-# INLINE ann_ #-} exp :: Double -> LogFloat exp = logToLogFloat {-# INLINE exp #-} log :: LogFloat -> Double log = logFromLogFloat {-# INLINE log #-} newtype Measure a = Measure { unMeasure :: MWC.GenIO -> IO (Maybe a) } instance Functor Measure where fmap = liftM {-# INLINE fmap #-} instance Applicative Measure where pure x = Measure $ \_ -> return (Just x) {-# INLINE pure #-} (<*>) = ap {-# INLINE (<*>) #-} instance Monad Measure where return = pure {-# INLINE return #-} m >>= f = Measure $ \g -> do Just x <- unMeasure m g unMeasure (f x) g {-# INLINE (>>=) #-} makeMeasure :: (MWC.GenIO -> IO a) -> Measure a makeMeasure f = Measure $ \g -> Just <$> f g {-# INLINE makeMeasure #-} uniform :: Double -> Double -> Measure Double uniform lo hi = makeMeasure $ MWC.uniformR (lo, hi) {-# INLINE uniform #-} normal :: Double -> LogFloat -> Measure Double normal mu sd = makeMeasure $ MWCD.normal mu (fromLogFloat sd) {-# INLINE normal #-} beta :: LogFloat -> LogFloat -> Measure LogFloat beta a b = makeMeasure $ \g -> logFloat <$> MWCD.beta (fromLogFloat a) (fromLogFloat b) g {-# INLINE beta #-} gamma :: LogFloat -> LogFloat -> Measure LogFloat gamma a b = makeMeasure $ \g -> logFloat <$> MWCD.gamma (fromLogFloat a) (fromLogFloat b) g {-# INLINE gamma #-} categorical :: MayBoxVec LogFloat LogFloat -> Measure Int categorical a = makeMeasure $ \g -> fromIntegral <$> MWCD.categorical (U.map prep a) g where prep p = fromLogFloat (p / m) m = G.maximum a {-# INLINE categorical #-} plate :: (G.Vector (MayBoxVec a) a) => Int -> (Int -> Measure a) -> Measure (MayBoxVec a a) plate n f = G.generateM (fromIntegral n) $ \x -> f (fromIntegral x) {-# INLINE plate #-} bucket :: Int -> Int -> (forall s. Reducer () s a) -> a bucket b e r = runST $ case r of Reducer{init=initR,accum=accumR,done=doneR} -> do s' <- initR () F.mapM_ (\i -> accumR () i s') [b .. e - 1] doneR s' {-# INLINE bucket #-} data Reducer xs s a = forall cell. Reducer { init :: xs -> ST s cell , accum :: xs -> Int -> cell -> ST s () , done :: cell -> ST s a } r_fanout :: Reducer xs s a -> Reducer xs s b -> Reducer xs s (a,b) r_fanout Reducer{init=initA,accum=accumA,done=doneA} Reducer{init=initB,accum=accumB,done=doneB} = Reducer { init = \xs -> liftM2 (,) (initA xs) (initB xs) , accum = \bs i (s1, s2) -> accumA bs i s1 >> accumB bs i s2 , done = \(s1, s2) -> liftM2 (,) (doneA s1) (doneB s2) } {-# INLINE r_fanout #-} r_index :: (G.Vector (MayBoxVec a) a) => (xs -> Int) -> ((Int, xs) -> Int) -> Reducer (Int, xs) s a -> Reducer xs s (MayBoxVec a a) r_index n f Reducer{init=initR,accum=accumR,done=doneR} = Reducer { init = \xs -> V.generateM (n xs) (\b -> initR (b, xs)) , accum = \bs i v -> let ov = f (i, bs) in accumR (ov,bs) i (v V.! ov) , done = \v -> fmap G.convert (V.mapM doneR v) } {-# INLINE r_index #-} r_split :: ((Int, xs) -> Bool) -> Reducer xs s a -> Reducer xs s b -> Reducer xs s (a,b) r_split b Reducer{init=initA,accum=accumA,done=doneA} Reducer{init=initB,accum=accumB,done=doneB} = Reducer { init = \xs -> liftM2 (,) (initA xs) (initB xs) , accum = \bs i (s1, s2) -> if (b (i,bs)) then accumA bs i s1 else accumB bs i s2 , done = \(s1, s2) -> liftM2 (,) (doneA s1) (doneB s2) } {-# INLINE r_split #-} r_add :: Num a => ((Int, xs) -> a) -> Reducer xs s a r_add e = Reducer { init = \_ -> newSTRef 0 , accum = \bs i s -> modifySTRef' s (+ (e (i,bs))) , done = readSTRef } {-# INLINE r_add #-} r_nop :: Reducer xs s () r_nop = Reducer { init = \_ -> return () , accum = \_ _ _ -> return () , done = \_ -> return () } {-# INLINE r_nop #-} pair :: a -> b -> (a, b) pair = (,) {-# INLINE pair #-} true, false :: Bool true = True false = False nothing :: Maybe a nothing = Nothing just :: a -> Maybe a just = Just unit :: () unit = () data Pattern = PVar | PWild newtype Branch a b = Branch { extract :: a -> Maybe b } ptrue, pfalse :: a -> Branch Bool a ptrue b = Branch { extract = extractBool True b } pfalse b = Branch { extract = extractBool False b } {-# INLINE ptrue #-} {-# INLINE pfalse #-} extractBool :: Bool -> a -> Bool -> Maybe a extractBool b a p | p == b = Just a | otherwise = Nothing {-# INLINE extractBool #-} pnothing :: b -> Branch (Maybe a) b pnothing b = Branch { extract = \ma -> case ma of Nothing -> Just b Just _ -> Nothing } pjust :: Pattern -> (a -> b) -> Branch (Maybe a) b pjust PVar c = Branch { extract = \ma -> case ma of Nothing -> Nothing Just x -> Just (c x) } pjust _ _ = error "Runtime.Prelude pjust" ppair :: Pattern -> Pattern -> (x -> y -> b) -> Branch (x,y) b ppair PVar PVar c = Branch { extract = (\(x,y) -> Just (c x y)) } ppair _ _ _ = error "ppair: TODO" uncase_ :: Maybe a -> a uncase_ (Just a) = a uncase_ Nothing = error "case_: unable to match any branches" {-# INLINE uncase_ #-} case_ :: a -> [Branch a b] -> b case_ e [c1] = uncase_ (extract c1 e) case_ e [c1, c2] = uncase_ (extract c1 e `mplus` extract c2 e) case_ e bs_ = go bs_ where go [] = error "case_: unable to match any branches" go (b:bs) = case extract b e of Just b' -> b' Nothing -> go bs {-# INLINE case_ #-} branch :: (c -> Branch a b) -> c -> Branch a b branch pat body = pat body {-# INLINE branch #-} dirac :: a -> Measure a dirac = return {-# INLINE dirac #-} pose :: LogFloat -> Measure a -> Measure a pose _ a = a {-# INLINE pose #-} superpose :: [(LogFloat, Measure a)] -> Measure a superpose pms = do i <- categorical (G.fromList $ map fst pms) snd (pms !! i) {-# INLINE superpose #-} reject :: Measure a reject = Measure $ \_ -> return Nothing nat_ :: Int -> Int nat_ = id int_ :: Int -> Int int_ = id unsafeNat :: Int -> Int unsafeNat = id nat2prob :: Int -> LogFloat nat2prob = fromIntegral fromInt :: Int -> Double fromInt = fromIntegral nat2int :: Int -> Int nat2int = id nat2real :: Int -> Double nat2real = fromIntegral fromProb :: LogFloat -> Double fromProb = fromLogFloat unsafeProb :: Double -> LogFloat unsafeProb = logFloat real_ :: Rational -> Double real_ = fromRational prob_ :: NonNegativeRational -> LogFloat prob_ = fromRational . fromNonNegativeRational infinity :: Double infinity = 1/0 abs_ :: Num a => a -> a abs_ = abs (**) :: LogFloat -> Double -> LogFloat (**) = pow {-# INLINE (**) #-} pi :: LogFloat pi = logFloat P.pi {-# INLINE pi #-} thRootOf :: Int -> LogFloat -> LogFloat thRootOf a b = b `pow` (recip $ fromIntegral a) {-# INLINE thRootOf #-} array :: (G.Vector (MayBoxVec a) a) => Int -> (Int -> a) -> MayBoxVec a a array n f = G.generate (fromIntegral n) (f . fromIntegral) {-# INLINE array #-} arrayLit :: (G.Vector (MayBoxVec a) a) => [a] -> MayBoxVec a a arrayLit = G.fromList {-# INLINE arrayLit #-} (!) :: (G.Vector (MayBoxVec a) a) => MayBoxVec a a -> Int -> a a ! b = a G.! (fromIntegral b) {-# INLINE (!) #-} size :: (G.Vector (MayBoxVec a) a) => MayBoxVec a a -> Int size v = fromIntegral (G.length v) {-# INLINE size #-} class Num a => Num' a where product :: Int -> Int -> (Int -> a) -> a product a b f = F.foldl' (\x y -> x * f y) 1 [a .. b-1] {-# INLINE product #-} summate :: Int -> Int -> (Int -> a) -> a summate a b f = F.foldl' (\x y -> x + f y) 0 [a .. b-1] {-# INLINE summate #-} instance Num' Int instance Num' Double instance Num' LogFloat where product a b f = LF.product (map f [a .. b-1]) {-# INLINE product #-} summate a b f = LF.sum (map f [a .. b-1]) {-# INLINE summate #-} run :: Show a => MWC.GenIO -> Measure a -> IO () run g k = unMeasure k g >>= \case Just a -> print a Nothing -> return () iterateM_ :: Monad m => (a -> m a) -> a -> m b iterateM_ f = g where g x = f x >>= g withPrint :: Show a => (a -> IO b) -> a -> IO b withPrint f x = print x >> f x
zaxtax/hakaru
haskell/Language/Hakaru/Runtime/LogFloatPrelude.hs
bsd-3-clause
13,161
8
15
3,695
4,702
2,531
2,171
-1
-1
module ADP.Tests.RGExample where import ADP.Multi.All type RG_Algebra alphabet answer = ( EPS -> answer, -- nil answer -> answer -> answer, -- left answer -> answer -> answer -> answer, -- pair answer -> answer -> answer -> answer -> answer -> answer -> answer, -- knot answer -> answer -> answer, -- knot1 answer -> answer, -- knot2 (alphabet, alphabet) -> answer, -- basepair alphabet -> answer, -- base [answer] -> [answer] -- h ) data Start = Nil | Left' Start Start | Pair Start Start Start | Knot Start Start Start Start Start Start | Knot1 Start Start | Knot2 Start | BasePair (Char, Char) | Base Char deriving (Eq, Show) enum :: RG_Algebra Char Start enum = (\_->Nil,Left',Pair,Knot,Knot1,Knot2,BasePair,Base,id) maxBasepairs :: RG_Algebra Char Int maxBasepairs = (nil,left,pair,knot,knot1,knot2,basepair,base,h) where nil _ = 0 left a b = a + b pair a b c = a + b + c knot a b c d e f = a + b + c + d + e + f knot1 a b = a + b knot2 a = a basepair _ = 1 base _ = 0 h [] = [] h xs = [maximum xs]
adp-multi/adp-multi-monadiccp
tests/ADP/Tests/RGExample.hs
bsd-3-clause
1,413
0
11
608
453
258
195
35
2